Author SHA1 Message Date
faumaray 38436b18c8 update version
Release / release (push) Failing after 5m4s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-29 07:06:52 +03:00
faumaray 7d7d23ec0a Merge branch 'feat/roadmap-p3-wave10' (P3 Discovery, Scheduler, Messaging) 2026-11-27 05:55:45 +03:00
faumaray f3f66e0c8c docs(workflow): record Wave 10 P3 Discovery, Scheduler, and Messaging verification 2026-11-27 05:55:45 +03:00
faumaray 60ee28e4ca feat(messaging): implement P3 S-MESSAGING-01..04 Messaging queue, StorageQueue/OutboxInbox, and MessagingRpc adapter 2026-11-27 05:45:43 +03:00
faumaray aaeab50758 feat(scheduler): implement P3 S-SCHEDULER-01..04 Scheduler engine, calendar/DST, and SchedulerStorage durable store 2026-11-27 05:38:06 +03:00
faumaray ec8c0bd40a feat(discovery): implement P3 S-DISCOVERY-01..04 Discovery catalog and optional DiscoveryRpc adapter 2026-11-27 05:25:43 +03:00
faumaray 0cf187d664 docs(wave10): add P3 Discovery, Scheduler, and Messaging specs and error domains 2026-11-27 05:14:52 +03:00
faumaray 65ad9b3f31 Merge branch 'feat/roadmap-p2-wave9' (P2 Net, TestingMock, ShortUrl, RPC) 2026-11-27 01:37:15 +03:00
faumaray 385a441b0b docs(workflow): record Wave 9 P2 Net, TestingMock, ShortUrl, and RPC verification 2026-11-27 01:37:15 +03:00
faumaray 5184d1cf8c feat(rpc): implement P2 S-RPC-01..03 Wire v1 binary codec and unary HTTP/1.1 RPC subsystem 2026-11-27 01:27:32 +03:00
faumaray 691808eab6 feat(shorturl): complete P2 M-SHORTURL-01..04 V2 local, storage, and remote providers with frozen V1 2026-11-27 01:27:32 +03:00
faumaray 658c21a2fa feat(testing-mock): complete P2 M-TESTINGMOCK-01..04 sessions, action-outside-lock, move-only, combinators 2026-11-27 01:15:36 +03:00
faumaray 86d777eae6 feat(net): complete P2 M-NET-01..05 codec, pool, safe static open, redirects, and RFC 6455 WebSocket 2026-11-27 01:15:36 +03:00
faumaray 700024a24d docs(wave9): add P2 Net, TestingMock, ShortUrl, and RPC task specs and error domains 2026-11-26 22:58:30 +03:00
faumaray 3e254055e0 Merge branch 'feat/upstream-vbs-requests' (VL-001..VL-013) 2026-11-26 22:01:33 +03:00
faumaray bb0b2e1701 docs(workflow): record VL-001..VL-013 verification and completion state 2026-11-26 22:01:33 +03:00
faumaray 9920bfdaac fix(net): scope GCC -Wno-tsan to Http.cpp and fix StallServer race 2026-11-26 22:00:17 +03:00
faumaray 66baae74a0 feat(net): implement VL-004 HttpServer and VL-005 streaming HttpClient with secure TLS 2026-11-26 21:47:15 +03:00
faumaray 22c8538754 feat(crypto,archive): implement VL-007 built-in hashes and VL-006 archive creation/gzip/tar fallback 2026-11-26 20:55:45 +03:00
faumaray b50131f52e feat(system,config,sqlite): implement VL-001, VL-003, VL-010, VL-011 2026-11-26 20:45:52 +03:00
faumaray adfc8548dc feat(data,text,testing): implement VL-002 TOML, VL-008 StrictJson UTF-8, VL-009 native tests, and VL-013 Semver shorthands 2026-11-26 20:27:42 +03:00
faumaray 53d42bda42 merge: Wave 8 P2 Service, Plugin, Configuration, and Fsm lifecycle hardening 2026-11-26 20:19:09 +03:00
145 changed files with 35365 additions and 471 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 4.0.0)
project(Void VERSION 1.2.1 LANGUAGES CXX)
project(Void VERSION 1.2.3 LANGUAGES C CXX)
if(PROJECT_IS_TOP_LEVEL)
option(BUILD_SHARED_LIBS "Build Void modules as shared libraries" ON)
elseif(NOT DEFINED BUILD_SHARED_LIBS)
+82 -2
View File
@@ -158,9 +158,89 @@ function(void_fetch_dependency DEP_NAME)
endif()
if(DEP_NAME STREQUAL "SQLite3")
if(NOT TARGET SQLite3::SQLite3 AND NOT TARGET SQLite::SQLite3)
find_package(SQLite3 REQUIRED)
if(TARGET SQLite3::SQLite3)
return()
endif()
if(TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
return()
endif()
set(_void_sqlite_dir "${VOID_SQLITE3_AMALGAMATION_DIR}")
if(NOT _void_sqlite_dir)
find_package(SQLite3 QUIET)
if(TARGET SQLite3::SQLite3)
return()
endif()
if(TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
return()
endif()
endif()
option(VOID_FETCH_SQLITE3
"Allow FetchContent SQLite3 amalgamation fallback when system SQLite3 is unavailable"
ON)
set(VOID_SQLITE3_AMALGAMATION_DIR "" CACHE PATH
"Path containing pre-downloaded sqlite3.c and sqlite3.h amalgamation sources")
set(VOID_SQLITE3_FETCH_URL
"https://www.sqlite.org/2025/sqlite-amalgamation-3490100.zip"
CACHE STRING "SQLite3 amalgamation archive URL for FetchContent fallback")
set(VOID_SQLITE3_FETCH_HASH "" CACHE STRING
"Optional SHA256 hash (SHA256=...) for VOID_SQLITE3_FETCH_URL")
if(NOT _void_sqlite_dir AND VOID_FETCH_SQLITE3 AND
NOT CMAKE_DISABLE_FIND_PACKAGE_SQLite3)
message(STATUS "[Void] System SQLite3 not found — falling back to SQLite3 amalgamation")
if(VOID_SQLITE3_FETCH_HASH)
FetchContent_Declare(SQLite3
URL "${VOID_SQLITE3_FETCH_URL}"
URL_HASH "${VOID_SQLITE3_FETCH_HASH}"
SYSTEM
)
else()
FetchContent_Declare(SQLite3
URL "${VOID_SQLITE3_FETCH_URL}"
SYSTEM
)
endif()
FetchContent_MakeAvailable(SQLite3)
if(EXISTS "${sqlite3_SOURCE_DIR}/sqlite3.c")
set(_void_sqlite_dir "${sqlite3_SOURCE_DIR}")
else()
file(GLOB _found_sqlite_c LIST_DIRECTORIES FALSE
"${sqlite3_SOURCE_DIR}/*/sqlite3.c")
if(_found_sqlite_c)
list(GET _found_sqlite_c 0 _first_sqlite_c)
get_filename_component(_void_sqlite_dir "${_first_sqlite_c}" DIRECTORY)
endif()
endif()
endif()
if(_void_sqlite_dir AND EXISTS "${_void_sqlite_dir}/sqlite3.c" AND
EXISTS "${_void_sqlite_dir}/sqlite3.h")
void_fetch_dependency(Threads)
add_library(void_sqlite3_amalgamation STATIC
"${_void_sqlite_dir}/sqlite3.c")
set_target_properties(void_sqlite3_amalgamation PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_STANDARD 11
SYSTEM TRUE)
target_include_directories(void_sqlite3_amalgamation SYSTEM PUBLIC
"${_void_sqlite_dir}")
target_compile_definitions(void_sqlite3_amalgamation PRIVATE
SQLITE_THREADSAFE=1
SQLITE_ENABLE_FTS5
SQLITE_ENABLE_JSON1
SQLITE_DQS=0)
target_link_libraries(void_sqlite3_amalgamation PUBLIC
Threads::Threads
"$<$<NOT:$<PLATFORM_ID:Windows>>:${CMAKE_DL_LIBS};m>")
add_library(SQLite3::SQLite3 ALIAS void_sqlite3_amalgamation)
return()
endif()
find_package(SQLite3 REQUIRED)
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
endif()
+51 -9
View File
@@ -1,8 +1,8 @@
# Workflow state
Updated: 2026-11-26.
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave8` (from `main`
at `d83d0f4`, merged Waves 1–7 and pushed to `origin/main`).
Updated: 2026-11-27.
Repository: VoidLibrary; active branch `feat/roadmap-p3-wave10` (from `main`
at `65ad9b3`, merged Waves 1–9 + `VL-001`..`VL-013` and pushed to `origin/main`).
## Completed objective
@@ -320,11 +320,53 @@ while leaving local untracked files untouched.
- Full Debug ASan+UBSan (`/tmp/void-w8-asan`, 45 modules): `VoidTests` 1,437 tests (`37.13s`), 0 leaks, 0 UB.
- Debug TSan (`/tmp/void-w8-tsan`, `ServicePlugin;ConfigurationAsync;Fsm;Testing`, 20 modules): `VoidTests` 1,110 tests (1,107 passed, 3 skipped, 0 failed, `11.49s`), 0 data races.
### VoidBuildSystem Upstream Feature Wave (`VL-001`..`VL-013`, `feat/upstream-vbs-requests`)
- **Batch A (`adfc854`, `VL-002`, `VL-008`, `VL-009`, `VL-012`, `VL-013`)**:
- Reserved `kNetErrorDomain = 26`; enforced `PascalCase` types / `snake_case` methods naming (`VL-012`); added strict RFC 3629/8259 UTF-8 validation in `StrictJson`, `Semver` shorthand comparators (`^1`, `^1.0`, `~1.2`, `>=1.2 <2`), header-only `Data/Toml.hpp` TOML 1.0 parser/serializer with `Origin`, and zero-CMake self-registering `VOID_TEST*` macros.
- Verified (`Data;Text;Testing`, `-Werror`): `690 tests (687 ✔, 3 ⊘)` in `351.9ms`; pure `g++` multi-file stem-collision binary `4/4` (`0.1ms`).
- **Batch B (`b50131f`, `VL-001`, `VL-003`, `VL-010`, `VL-011`)**:
- Full process-group supervision (`PR_SET_CHILD_SUBREAPER`, `waitpid(-pgid)`, `SIGKILL` escalation), `FileLock` / `atomic_symlink_swap` / `reflink_copy_file` / `set_timestamps_nofollow`, Linux `inotify` recursive `DirectoryWatcher`, `Argparse` subcommands/`option_many`/`positional_many`/`ParseOutcome`, top-level `LANGUAGES C CXX`, and FetchContent SQLite3 amalgamation fallback.
- Verified (`/tmp/void-vbs-b`, `-Werror`): `791 tests (788 ✔, 3 ⊘)` in `1.72s`, `ctest` `2/2` (`14.44s` incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`).
- **Batch C (`22c8538`, `VL-006`, `VL-007`)**:
- Optional `OpenSSL::Crypto` (`VOID_CRYPTO_HAS_OPENSSL`) + pure-C++ FIPS 180-4 SHA-1/256/512 & RFC 7693 BLAKE2b-256/512 + HMAC/HKDF + `snake_case` aliases; optional `LibArchive` (`VOID_ARCHIVE_HAS_LIBARCHIVE`) + pure-C++ USTAR/PAX tar & deterministic `ArchiveCompression::Gzip` + `create()`.
- Verified zero-OpenSSL (`534 ✔ / 3 ⊘`, `ctest` `2/2` `5.59s`), zero-LibArchive (`405 ✔ / 3 ⊘`, `ctest` `2/2` `6.22s`), and full backends (`888 ✔ / 3 ⊘`, `ctest` `2/2` `15.53s`).
- **Batch D (`66baae7`, `VL-004`, `VL-005`) + TSan/race fix (`9920bfd`)**:
- POSIX TCP HTTP/1.1 `HttpServer`, streaming `HttpClient` + `HttpClient::secure()` TLS >= 1.2 + CA/SAN verification + cross-origin/downgrade/redaction + `std::stop_token` cancellation + `NetOnly` consumer (`66baae7`); scoped GCC `-Wno-tsan` to `src/Net/Http.cpp` and fixed `StallServer` join order (`9920bfd`).
- Verified `Net;System;Crypto;Testing` (`563 ✔ / 3 ⊘`, `ctest` `2/2` `8.48s` incl. `NetOnly`).
- **Full-suite & sanitizer checks**:
- Full RelWithDebInfo (`/tmp/void-vbs-full`, 45 modules, `-Werror`): `VoidTests` `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `21.94s` (`22.09s` post-`9920bfd`), `ctest` `2/2` in `82.82s` (`VoidTests` `22.03s`, `VoidInstalledComponentConsumers` `60.79s` across all `35` consumers incl. `NetOnly`), `VoidFoundationBench` (`rev=66baae74a0b7`) recorded.
- Full Debug ASan+UBSan (`/tmp/void-vbs-asan`, 45 modules, `-Werror`): `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB (+ post-`9920bfd` `Http|Net|Server` `9/9 ✔` in `1.58s`).
- Debug TSan (`/tmp/void-vbs-tsan`, `Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`, 17 modules, `-Werror`): `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings.
### Wave 9 — P2 Completion: `Net`, `TestingMock`, `ShortUrl`, `RPC` (`feat/roadmap-p2-wave9`)
- **Specs & Error Domains (`700024a`)**: authored `M-NET-01-05.md`, `M-TESTINGMOCK-01-04.md`, `M-SHORTURL-01-04.md`, `S-RPC-01-03.md`; reserved `kTestingMockErrorDomain = 27`, `kShortUrlErrorDomain = 28`, `kRpcErrorDomain = 29`, `kDiscoveryErrorDomain = 30`.
- **`Net` P2 Hardening (`86d777e`, `M-NET-01..05`)**: native incremental RFC 9110/9112 `HttpRequestParser` / `HttpResponseParser`, bounded `ConnectionPool` (`PoolKey` origin+proxy+TLS generation, `MonotonicClock` idle eviction, RAII `ConnectionLease`), descriptor-pinned `StaticFileResolver::open_safe()` (`openat`+`O_NOFOLLOW`), `HttpClient` `303`/`307` redirect & single-deadline hardening, RFC 6455 `WebSocket` codec/decoder/`WebSocketClient` & `HttpServer::add_websocket_route()`.
- **`TestingMock` P2 Hardening (`658c21a`, `M-TESTINGMOCK-01..04`)**: explicit `MockSession` (`freeze`, `verify_and_close`, `MockLimits`, `RegistrationToken`), `Sequence` order groups, action-outside-lock reservation (same-thread reentry + `ConcurrentActions`), perfect forwarding + `returns_once`/`invokes_once` move-only support, `never()`/`at_least`/`at_most`/`between`, matcher combinators (`Ne`, `EndsWith`, `IsNull`, `NotNull`, `NotOf`, `AllOf`, `AnyOf`, depth bound 32), `TestingMockOnly` consumer.
- **`ShortUrl` P2 Completion (`691808e`, `M-SHORTURL-01..04`)**: preserved frozen `V1` ABI; added `Void::ShortUrl::V2` (`LocalProvider`, URL/key validation, base62 keys, civil expiry, tombstone non-reuse, 24h idempotency, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (pre-mutation capability checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer.
- **`RPC` Subsystem (`5184d1c`, `S-RPC-01..03`)**: NEW `Void::RPC` module with Wire v1 deterministic binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` (`AuthHook`, schema check, timeout clamp, sanitized exceptions, `Registration::unregister_and_drain()`), `RpcOnly` consumer.
- **Full-suite & sanitizer checks**:
- Full integrated RelWithDebInfo (`/tmp/void-w9-full`, 48 modules, `-Werror`): `VoidTests` `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `23.56s`; `ctest` `2/2` in `91.13s` (`VoidTests` `23.27s`, `VoidInstalledComponentConsumers` `67.86s` across all `38` consumers); `VoidFoundationBench` (`rev=5184d1cf8cdd`) recorded.
- Full Debug ASan+UBSan (`/tmp/void-w9-asan`, 48 modules, `-Werror`): `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB.
- Debug TSan (`/tmp/void-w9-tsan`, `Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`, 22 modules, `-Werror`): `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings.
### Wave 10 — P3 Core Subsystems: `Discovery`, `Scheduler`, `Messaging` (`feat/roadmap-p3-wave10`)
- **Specs & Error Domains (`0cf187d`)**: authored `S-DISCOVERY-01-04.md`, `S-SCHEDULER-01-04.md`, `S-MESSAGING-01-04.md`; reserved `kSchedulerErrorDomain = 31` and `kMessagingErrorDomain = 32` (`kDiscoveryErrorDomain = 30` reserved in Wave 9).
- **`Discovery` & `DiscoveryRpc` (`ec8c0bd`, `S-DISCOVERY-01..04`)**: NEW zero-external-dep `Void::Discovery` subsystem (`Catalog` with pure thread-free construction, atomic `replace_static()`, provider generation resets, local RAII `Registration` handles with steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` overflow recovery + self-cancel + `SelfJoin` diagnosis, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` endpoint adapter preserving `expected_tls_name` / blocking TLS downgrades while keeping `RPC` independent; `DiscoveryOnly` consumer (`_no_external_deps`).
- **`Scheduler` & `SchedulerStorage` (`aaeab50`, `S-SCHEDULER-01..04`)**: NEW zero-external-dep `Void::Scheduler` subsystem (monotonic min-heap ordered by `(due_time, sequence)`, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` with DST gap/fold & unknown-zone rejection without silent UTC fallback, O(1) backward-scanning `CoalesceLatest` over millions of missed slots, 100/pass `CatchUpBounded`, `Forbid`/`QueueOne`/`AllowBounded` overlap, exponential full-jitter retries & dead-letter acknowledgement, revision invalidation watermark, `close_and_join` returning incomplete report on deadline) + durable `Void::SchedulerStorage` (`StorageJobStore` on `Void::Storage::Engine` conditional batches, exclusive owner lock, unique civil-slot dedup, startup `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause without cursor loss); `SchedulerOnly` consumer (`_no_external_deps`).
- **`Messaging`, `MessagingStorage`, & `MessagingRpc` (`60ee28e`, `S-MESSAGING-01..04`)**: NEW zero-external-dep `Void::Messaging` subsystem (explicit `PublishDurability::{Memory,Durable}`, `InMemoryQueue` rejecting `Durable`, `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`, competing & `SingleActive` groups, stale-receipt fencing & idempotent repeat ack, bounded retries -> DLQ, corrupt-payload quarantine) + `Void::MessagingStorage` (`StorageQueue` on `Void::Storage::Engine` conditional batches, restart `InFlight -> Pending` generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency ledger refusing silent eviction, `BlockAtQuota` default & clock-health expiry pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`); `MessagingOnly` consumer (`_no_external_deps`).
- **Full-suite & sanitizer checks**:
- Full integrated RelWithDebInfo (`/tmp/void-w10-full`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly` with `_no_external_deps`); `VoidFoundationBench` (`rev=60ee28e4ca9b`) recorded.
- Full Debug ASan+UBSan (`/tmp/void-w10-asan`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB.
- Debug TSan (`/tmp/void-w10-tsan`, `Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`, 23 modules, `-Werror`): `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings.
## Ownership and next step
Waves 1–8 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`,
`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`,
`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`, and
`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`) are complete
and merged to `main`, proceeding to the VoidBuildSystem upstream feature wave
(`VL-001`..`VL-013`) and P2 `Net`.
Waves 1–10 (`P0`, `P1`, all `P2` modules, `VL-001`..`VL-013`, and P3 core
subsystems `Discovery`, `Scheduler`, `Messaging`) are complete, verified, and
ready for `--no-ff` merge to `main`. Next wave: **Wave 11 — P3 Completion**
(`S-RPC-04..05` WebSocket multiplexed streaming + `NetworkedApplications` &
`ReloadableApplications` platform integrations), followed by **P4**
(`Coordination`, `Replication`, `DistributedStorage`, `DistributedApplications`).
+26
View File
@@ -110,6 +110,32 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| M-CONFIGURATION-01..05 | Hardened `Configuration` (`kConfigurationErrorDomain = 24`, `Bind.hpp` attributes, bounded `Schema<T>` reflection/provenance/redaction/deprecation checks) + split `ConfigurationAsync` (transactional `ReloadController<T>`, `Snapshot<T>`, `prepare_external`, coalescing `WatcherService` integration), `ConfigurationOnly` & `ConfigurationAsyncOnly` consumers (`1dc51d5`) | [M-CONFIGURATION-01-05](tasks/M-CONFIGURATION-01-05.md) | VERIFIED | Standalone `ConfigurationAsync;Testing` `Configuration*` 6/6 (`0.7ms`), `ctest` 2/2 (`13.75s`), Debug TSan 1,107 ✔ (0 races), full RelWithDebInfo (`1,434 ✔`), ASan+UBSan (0 leaks/UB) |
| M-FSM-01..05 | Hardened `Fsm` (`kFsmErrorDomain = 25`, shared `terminal(Status)` incl. `Faulted`, `TerminationReason`, `FsmLimits` bounds & reserved control lane, `MonotonicClock` & borrowed `ExecutionBinding`, per-state stop scopes & waiter/timer purge before `on_exit()`, `run_parallel_structured` / `run_parallel_any_structured` loser stop+join & tie-break, boundary `request_checkpoint` / `safe_point` / `restore_checkpoint` / `restore_legacy_checkpoint`, `acquire_service<I>()`, hardened `Orchestrator` `StopOnFault`/`BoundedRestart` & `FsmModel::~FsmModel()` worker join), `FsmOnly` consumer (`ef5312c`, `40b579d`, `cb988fa`) | [M-FSM-01-05](tasks/M-FSM-01-05.md) | VERIFIED | Standalone `Fsm;Testing` 814 ✔ / 2 skips (`789.1ms`), `ctest` 2/2 (`9.59s`), Debug TSan 1,107 ✔ (0 races, `internal_FsmServiceHotReload` 4/4), full RelWithDebInfo (`1,434 ✔`, `ctest` 2/2 `77.11s`), ASan+UBSan (`1,434 ✔`, 0 leaks/UB) |
## VoidBuildSystem Upstream Requests (`VL-001`..`VL-013`, `feat/upstream-vbs-requests`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| VL-002, VL-008, VL-009, VL-012, VL-013 | `Data/Toml.hpp` (TOML 1.0 parser/serializer + `Origin`), strict RFC 3629/8259 UTF-8 in `StrictJson`, zero-CMake self-registering `VOID_TEST*` macros, `Semver` shorthand comparators (`^1`, `^1.0`, `~1.2`, `>=1.2 <2`), `PascalCase`/`snake_case` naming (`VL-012`), `kNetErrorDomain = 26` (`adfc854`) | — | VERIFIED | Standalone `Data;Text;Testing` `-Werror` `687 ✔ / 3 ⊘` (`351.9ms`); pure `g++` zero-CMake multi-file stem collision binary `4/4` (`0.1ms`), `--list`, `--filter from_dir_b` `1/1`; full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
| VL-001, VL-003, VL-010, VL-011 | Process-group supervision (`PR_SET_CHILD_SUBREAPER`, `waitpid(-pgid)`, leader-exit `SIGKILL` escalation), `FileLock` / `atomic_symlink_swap` / `reflink_copy_file` / `set_timestamps_nofollow`, Linux `inotify` recursive `DirectoryWatcher`, `Argparse` subcommands/`option_many`/`positional_many`/`ParseOutcome`, top-level `LANGUAGES C CXX` & FetchContent SQLite3 amalgamation (`b50131f`) | — | VERIFIED | Standalone `/tmp/void-vbs-b` `-Werror` `788 ✔ / 3 ⊘` (`1.72s`), `ctest` `2/2` (`14.44s`, incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`); full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
| VL-006, VL-007 | Optional `OpenSSL::Crypto` (`VOID_CRYPTO_HAS_OPENSSL`) + pure-C++ FIPS 180-4 SHA-1/256/512 & RFC 7693 BLAKE2b-256/512 + HMAC/HKDF + `snake_case` hash aliases (`22c8538`); optional `LibArchive` (`VOID_ARCHIVE_HAS_LIBARCHIVE`) + pure-C++ USTAR/PAX tar & deterministic `ArchiveCompression::Gzip` + `create()` (`22c8538`) | — | VERIFIED | Zero-OpenSSL `534 ✔ / 3 ⊘` (`1.09s`, `ctest` `2/2` `5.59s`); zero-LibArchive `405 ✔ / 3 ⊘` (`1.45s`, `ctest` `2/2` `6.22s`); full-backend `888 ✔ / 3 ⊘` (`3.70s`, `ctest` `2/2` `15.53s`); full RelWithDebInfo (`1,452 ✔`), ASan+UBSan (`0` leaks/UB), TSan (`954 ✔`, `0` races) |
| VL-004, VL-005 | POSIX TCP HTTP/1.1 `HttpServer` (`query`, `file_body`/`from_file`, `Router::allowed_methods`, `bound_port`, `431`/`413`, TE+CL smuggling `400`, streaming `BodyReader`, `HEAD`->`GET`, `shutdown`), streaming `HttpClient` + `HttpClient::secure()` TLS >= 1.2 + CA/SAN + cross-origin/downgrade/redaction + `NetErrorCode` (`kNetErrorDomain = 26`) + `std::stop_token` + `NetOnly` consumer (`66baae7`) + TSan `-Wno-tsan` scope & `StallServer` fix (`9920bfd`) | — | VERIFIED | Standalone `Net;System;Crypto;Testing` `563 ✔ / 3 ⊘` (`2.36s`), `ctest` `2/2` (`8.48s` incl. `NetOnly`); Debug TSan `954 ✔ / 3 ⊘` (`10.65s`, `0` races); full RelWithDebInfo `1,452 ✔ / 4 ⊘` (`22.09s`), `ctest` `2/2` (`82.82s`, `35` consumers); ASan+UBSan `1,452 ✔` (`39.11s`) + `Http\|Net\|Server` `9/9` (`1.58s`, `0` leaks/UB) |
## Wave 9 — P2 Completion: Net, TestingMock, ShortUrl, RPC (`feat/roadmap-p2-wave9`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| M-NET-01..05 | Native incremental RFC 9110/9112 `HttpRequestParser` / `HttpResponseParser` (smuggling rejection, 1xx/HEAD/chunked/trailers/EOF), bounded `ConnectionPool` (`PoolKey` origin+proxy+TLS generation, `MonotonicClock` idle eviction, RAII `ConnectionLease`), descriptor-pinned `StaticFileResolver::open_safe()` (`openat`+`O_NOFOLLOW`), `HttpClient` `303`/`307` redirect & single-deadline hardening, RFC 6455 `WebSocket` codec/decoder/`WebSocketClient` & `HttpServer::add_websocket_route()` (`86d777e`) | [M-NET-01-05](tasks/M-NET-01-05.md) | VERIFIED | Standalone `Net;System;Crypto;TestingMock;Testing` `44/44 ✔` (`1.31s`), `ctest` `2/2` (`10.96s` incl. `NetOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔ / 4 ⊘` (`23.56s`, `ctest` `2/2` `91.13s`, `38` consumers); ASan+UBSan `1,466 ✔` (`41.95s`, `0` leaks/UB) |
| M-TESTINGMOCK-01..04 | Explicit `MockSession` (`kTestingMockErrorDomain = 27`, `freeze(SingleThread\|ConcurrentActions)`, `verify_and_close()`, `MockLimits`, `RegistrationToken`), `Sequence` order groups, action-outside-lock reservation (same-thread reentry + concurrent actions), perfect forwarding + `returns_once`/`invokes_once` move-only support, `never()`/`at_least`/`at_most`/`between`, matcher combinators (`Ne`, `EndsWith`, `IsNull`, `NotNull`, `NotOf`, `AllOf`, `AnyOf`, depth bound 32), `TestingMockOnly` consumer (`658c21a`) | [M-TESTINGMOCK-01-04](tasks/M-TESTINGMOCK-01-04.md) | VERIFIED | Standalone `TestingMock*` 18/18 ✔ + `ctest` `TestingMockOnly`; Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
| M-SHORTURL-01..04 | Frozen `V1` ABI preserved + additive `Void::ShortUrl::V2` (`kShortUrlErrorDomain = 28`, URL/key validation, base62 rejection-sampled keys, civil expiry, tombstone non-reuse, 24h idempotency, `LocalProvider`, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (capability pre-checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer (`691808e`) | [M-SHORTURL-01-04](tasks/M-SHORTURL-01-04.md) | VERIFIED | Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing` `ShortUrl*` 5/5 ✔, `ctest` `2/2` (`36.84s` incl. `ShortUrlOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
| S-RPC-01..03 | NEW `Void::RPC` subsystem (`kRpcErrorDomain = 29`), Wire v1 big-endian binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` with `AuthHook`, schema negotiation, timeout clamping, sanitized handler exceptions, `Registration::unregister_and_drain()`, `RpcOnly` consumer (`5184d1c`) | [S-RPC-01-03](tasks/S-RPC-01-03.md) | VERIFIED | Standalone `Rpc` 2/2 ✔, `ctest` `2/2` (`36.84s` incl. `RpcOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
## Wave 10 — P3 Core Subsystems: Discovery, Scheduler, Messaging (`feat/roadmap-p3-wave10`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| S-DISCOVERY-01..04 | NEW `Void::Discovery` (`kDiscoveryErrorDomain = 30`, pure `Catalog`, atomic `replace_static()`, provider generation resets, local RAII `Registration` + steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` + self-cancel + `SelfJoin`, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` (identity-preserving TLS refresh; `RPC` remains Discovery-free), `DiscoveryOnly` consumer (`ec8c0bd`) | [S-DISCOVERY-01-04](tasks/S-DISCOVERY-01-04.md) | VERIFIED | Standalone `Discovery;DiscoveryRpc;Testing` `5/5 ✔` (`9.4ms`), `ctest` `2/2` (`11.26s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔ / 4 ⊘` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
| S-SCHEDULER-01..04 | NEW `Void::Scheduler` (`kSchedulerErrorDomain = 31`, monotonic min-heap, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` DST gap/fold & unknown-zone rejection, O(1) `CoalesceLatest` over >2.6M missed minutes, 100/pass `CatchUpBounded`, overlap policies, retries/dead-letter, revision invalidation watermark, `close_and_join`) + durable `Void::SchedulerStorage` (`StorageJobStore` exclusive owner lock, unique civil-slot dedup, crash `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause), `SchedulerOnly` consumer (`aaeab50`) | [S-SCHEDULER-01-04](tasks/S-SCHEDULER-01-04.md) | VERIFIED | Standalone `Scheduler;SchedulerStorage;System;Testing` `5/5 ✔` (`167.3ms`), `ctest` `2/2` (`30.06s` incl. `SchedulerOnly` `_no_external_deps`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
| S-MESSAGING-01..04 | NEW `Void::Messaging` (`kMessagingErrorDomain = 32`, explicit `PublishDurability`, nondurable `InMemoryQueue`, `Pending -> InFlight(gen, visibility) -> Acked \| Pending \| DeadLetter`, competing/`SingleActive` groups, stale-receipt fencing, idempotent ack, retries/DLQ, corrupt quarantine) + `Void::MessagingStorage` (`StorageQueue` durable batches, restart generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency, `BlockAtQuota` & clock-health pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`), `MessagingOnly` consumer (`60ee28e`) | [S-MESSAGING-01-04](tasks/S-MESSAGING-01-04.md) | VERIFIED | Standalone `Messaging;MessagingStorage;MessagingRpc;System;Testing` `4/4 ✔` (`217.4ms`), `ctest` `2/2` (`31.73s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`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
+23
View File
@@ -281,3 +281,26 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
| Wave 8 integrated RelWithDebInfo + consumers (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w8-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `20.99s`; `ctest` `2/2` in `77.11s` (`VoidTests` `20.97s`, all `34` installed consumers `56.13s`) |
| Wave 8 full Debug ASan+UBSan (`cb988fa`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w8-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,437` discovered (`1,434 ✔`, `3 ⊘` skipped, `0 ✘`) in `37.13s`, `0` leaks, `0` UB |
| Post-W8 Benchmark (`cb988fa`, `rev=cb988fa98509`) | `/tmp/void-w8-full/benchmarks/VoidFoundationBench --json /tmp/void-w8-full/post-w8.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.71ns, `core_uuid_to_string` 16.45ns, `core_hash_fnv1a64_256b` 179.94ns, `core_hash_murmur3_256b` 67.31ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 57.98ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.72ns, `containers_lru_get_put` 20.58ns, `binary_reader_u64_be` 1.30ns, `data_json_parse_small_object` 319.62ns, `data_json_serialize_small_object` 167.55ns |
| Batch A `VL-002`/`008`/`009`/`012`/`013` (`adfc854`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-a`, `Data;Text;Testing`) + pure `g++` zero-CMake multi-file stem collision binary (`tests/package/TestingNativeGxx/{dir_a,dir_b}/dup.cpp`) | **PASSED**: `VoidTests` `690 tests` (`687 ✔`, `3 ⊘`, `0 ✘`) in `351.9ms`; pure `g++` `4/4` (`0.1ms`), `--list`, `--filter from_dir_b` `1/1` |
| Batch B `VL-001`/`003`/`010`/`011` (`b50131f`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-b`, FetchContent SQLite3 amalgamation), `VoidTests` + `ctest` | **PASSED**: `VoidTests` `791 tests` (`788 ✔`, `3 ⊘`, `0 ✘`) in `1.72s`; `ctest` `2/2` in `14.44s` (`VoidTests` `1.76s`, `VoidInstalledComponentConsumers` `12.68s` incl. `SystemOnly`, `ConfigurationOnly`, `SqliteOnly`) |
| Batch C zero-OpenSSL `VL-007` (`22c8538`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-no-openssl`, `-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE`, `Crypto;System;Text;Testing`) | **PASSED**: `VoidTests` `537 tests` (`534 ✔`, `3 ⊘`, `0 ✘`) in `1.09s`; `ctest` `2/2` in `5.59s` incl. `CryptoOnly` |
| Batch C zero-LibArchive `VL-006` (`22c8538`) | `dev cpp-gcc -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-no-libarchive`, `-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE`, `Archive;Testing`) | **PASSED**: `VoidTests` `408 tests` (`405 ✔`, `3 ⊘`, `0 ✘`) in `1.45s`; `ctest` `2/2` in `6.22s` incl. `ArchiveOnly` |
| Batch C full backends `VL-006`/`007` (`22c8538`) | `dev cpp-gcc -p libarchive -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-c`, `Crypto;CryptoAsync;Archive;Update;Testing`) | **PASSED**: `VoidTests` `891 tests` (`888 ✔`, `3 ⊘`, `0 ✘`) in `3.70s`; `ctest` `2/2` in `15.53s` incl. `CryptoOnly`, `CryptoAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `Audited` |
| Batch D `VL-004`/`005` (`66baae7`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-d`, `Net;System;Crypto;Testing`) | **PASSED**: `VoidTests` `566 tests` (`563 ✔`, `3 ⊘`, `0 ✘`) in `2.36s`; `ctest` `2/2` in `8.48s` (`VoidTests` `2.39s`, `VoidInstalledComponentConsumers` `6.09s` incl. `NetOnly`) |
| Integrated RelWithDebInfo + consumers (`66baae7`, `9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-vbs-full`), 45 modules, `VoidTests` + `ctest` | **PASSED**: `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `21.94s`; `ctest` `2/2` in `82.82s` (`VoidTests` `22.03s`, `VoidInstalledComponentConsumers` `60.79s` across all `35` consumers incl. `NetOnly`); post-`9920bfd` rebuild `VoidTests` `1,456` (`1,452 ✔`, `4 ⊘`) in `22.09s` |
| Full Debug ASan+UBSan (`66baae7`, `9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-vbs-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 45 modules | **PASSED**: `1,456` discovered (`1,452 ✔`, `4 ⊘`, `0 ✘`) in `39.11s`, `0` leaks, `0` UB; post-`9920bfd` incremental `--filter 'Http\|Net\|Server'` `9/9 ✔` in `1.58s` |
| Debug TSan (`9920bfd`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug TSan (`-Werror`, `/tmp/void-vbs-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 17 modules (`Net;System;SystemAsync;Configuration;Crypto;Archive;Data;Text;Testing`) | **PASSED**: `957` discovered (`954 ✔`, `3 ⊘`, `0 ✘`) in `10.65s`, `0` data races, `0` lock-order warnings |
| Post-VBS Benchmark (`66baae7`, `rev=66baae74a0b7`) | `/tmp/void-vbs-full/benchmarks/VoidFoundationBench --json /tmp/void-vbs-full/post-vbs.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 26.35ns, `core_uuid_to_string` 18.33ns, `core_hash_fnv1a64_256b` 185.86ns, `core_hash_murmur3_256b` 69.58ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 59.59ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.97ns, `containers_lru_get_put` 21.17ns, `binary_reader_u64_be` 1.34ns, `data_json_parse_small_object` 316.05ns, `data_json_serialize_small_object` 174.83ns |
| Wave 9 `Net` & `TestingMock` standalone (`86d777e`, `658c21a`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w9-net`, `Net;System;Crypto;TestingMock;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `44/44 ✔` in `1.31s` (`NetHardening` 5/5, `SessionHardening` 4/4, all legacy Net/TestingMock suites); `ctest` `2/2` in `10.96s` (`VoidTests` `2.46s`, `VoidInstalledComponentConsumers` `8.50s` incl. `NetOnly` & `TestingMockOnly`) |
| Wave 9 `ShortUrl` & `RPC` standalone (`691808e`, `5184d1c`) | `dev cpp-gcc -p openssl -p libsodium -c` RelWithDebInfo (`-Werror`, `/tmp/void-w9-shorturl-rpc`, `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `7/7 ✔` in `1.20s` (`Rpc` 2/2, `ShortUrl` 2/2, `ShortUrlV2` 1/1, `StorageRepository` 1/1, `RemoteProvider` 1/1); `ctest` `2/2` in `36.84s` (`VoidTests` `17.31s`, `VoidInstalledComponentConsumers` `19.54s` incl. `ShortUrlOnly` & `RpcOnly`) |
| Wave 9 integrated RelWithDebInfo + consumers (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w9-full`), 48 modules, `VoidTests` + `ctest` | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `23.56s`; `ctest` `2/2` in `91.13s` (`VoidTests` `23.27s`, `VoidInstalledComponentConsumers` `67.86s` across all `38` consumers incl. `NetOnly`, `TestingMockOnly`, `ShortUrlOnly`, `RpcOnly`) |
| Wave 9 full Debug ASan+UBSan (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w9-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 48 modules | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB |
| Wave 9 Debug TSan (`5184d1c`) | `dev cpp-gcc -p openssl -p libsodium` Debug TSan (`-Werror`, `/tmp/void-w9-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 22 modules (`Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`) | **PASSED**: `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings |
| Post-W9 Benchmark (`5184d1c`, `rev=5184d1cf8cdd`) | `/tmp/void-w9-full/benchmarks/VoidFoundationBench --json /tmp/void-w9-full/post-w9.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.49ns, `core_uuid_parse_hyphenated` 25.02ns, `core_uuid_to_string` 16.55ns, `core_hash_fnv1a64_256b` 183.63ns, `core_hash_murmur3_256b` 69.12ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.06ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.93ns, `containers_lru_get_put` 21.47ns, `binary_reader_u64_be` 1.15ns, `data_json_parse_small_object` 297.72ns, `data_json_serialize_small_object` 172.85ns |
| Wave 10 `Discovery` & `DiscoveryRpc` standalone (`ec8c0bd`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m1`, `Discovery;DiscoveryRpc;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `9.4ms` (`Catalog` 4/4, `EndpointAdapter` 1/1); `ctest` `2/2` in `11.26s` (`VoidTests` `0.60s`, `VoidInstalledComponentConsumers` `10.66s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`) |
| Wave 10 `Scheduler` & `SchedulerStorage` standalone (`aaeab50`) | `dev cpp-gcc -c` zero external deps RelWithDebInfo (`-Werror`, `/tmp/void-w10-m2`, `Scheduler;SchedulerStorage;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `167.3ms` (`Scheduler` 3/3, `StorageJobStore` 2/2); `ctest` `2/2` in `30.06s` (`VoidTests` `16.51s`, `VoidInstalledComponentConsumers` `13.54s` incl. `SchedulerOnly` `_no_external_deps`) |
| Wave 10 `Messaging`, `MessagingStorage`, & `MessagingRpc` standalone (`60ee28e`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m3`, `Messaging;MessagingStorage;MessagingRpc;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `4/4 ✔` in `217.4ms` (`Messaging` 1/1, `StorageQueue` 2/2, `RpcAdapter` 1/1); `ctest` `2/2` in `31.73s` (`VoidTests` `16.09s`, `VoidInstalledComponentConsumers` `15.63s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`) |
| Wave 10 integrated RelWithDebInfo + consumers (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w10-full`), 55 modules, `VoidTests` + `ctest` | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly`) |
| Wave 10 full Debug ASan+UBSan (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w10-asan`), 55 modules | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB |
| Wave 10 Debug TSan (`60ee28e`) | `dev cpp-gcc -p openssl` Debug TSan (`-Werror`, `/tmp/void-w10-tsan`), 23 modules (`Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`) | **PASSED**: `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings |
| Post-W10 Benchmark (`60ee28e`, `rev=60ee28e4ca9b`) | `/tmp/void-w10-full/benchmarks/VoidFoundationBench --json /tmp/void-w10-full/post-w10.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.18ns, `core_uuid_to_string` 16.66ns, `core_hash_fnv1a64_256b` 182.46ns, `core_hash_murmur3_256b` 68.53ns, `functional_result_ok_chain` 1.14ns, `functional_error_with_context` 59.10ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.85ns, `containers_lru_get_put` 20.87ns, `binary_reader_u64_be` 1.14ns, `data_json_parse_small_object` 287.18ns, `data_json_serialize_small_object` 164.76ns |
+29
View File
@@ -0,0 +1,29 @@
# Task Spec: `M-NET-01..05` — P2 Network Hardening, Native HTTP/1.1 Codec, Connection Pool, Safe Static Open & RFC 6455 WebSockets
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`, building on `VL-004`/`VL-005` in `66baae7` + `9920bfd`).
- **Roadmap authority**: `docs/roadmap/modules/Net.md` (`M-NET-01`..`M-NET-05`), `ARCHITECTURE.md` C-02..C-06, C-11, C-13.
- **Error domain**: `Void::Result::kNetErrorDomain = 26` (`NetErrorCode` in `include/Void/Net/Http.hpp`).
## Scope & Deliverables
1. **Native Incremental HTTP/1.1 Codec (`include/Void/Net/HttpCodec.hpp`, `src/Net/HttpCodec.cpp`)**:
- `HttpCodecLimits` (defaults: `max_start_line_bytes = 8 KiB`, `max_header_bytes = 32 KiB`, `max_headers = 100`, `max_body_bytes = 8 MiB`, `max_chunk_ext_bytes = 1 KiB`, `max_trailer_bytes = 8 KiB`).
- `HttpRequestParser` and `HttpResponseParser`: byte-by-byte / arbitrary-split incremental RFC 9110/9112 state machines.
- Strict CRLF framing, header field-name token validation, rejection of duplicate/conflicting `Content-Length`, rejection of `Transfer-Encoding` + `Content-Length` smuggling ambiguity, handling of `1xx` informational responses, `HEAD`/`204`/`304` no-body responses, chunked transfer encoding with chunk extensions and trailers, close-delimited response bodies (`finish_eof()`), and explicit `connection_reusable()` check.
2. **Bounded HTTP/1.1 Connection Pool (`include/Void/Net/Pool.hpp`, `src/Net/Pool.cpp`)**:
- `PoolLimits` (defaults: `max_total_connections = 256`, `max_per_origin = 8`, `max_idle_connections = 128`, `idle_timeout = 30s`).
- `PoolKey` keyed by `{scheme, host, port, proxy_identity, tls_policy_generation}` (so changing proxy or trust generation never reuses stale connections).
- `ConnectionPool` using injectable `Void::Time::MonotonicClock` for deterministic idle eviction, returning RAII `ConnectionLease` handles that only return clean, reusable connections to the pool (`mark_reusable(true)`); abandoned/unmarked/dirty/expired leases close cleanly.
3. **Descriptor-Pinned Static File Opening (`include/Void/Net/Server.hpp`, `src/Net/Server.cpp`)**:
- `OpenedStaticFile` (move-only RAII descriptor + `content_type` + `size`, `read_all()`, `native_handle()`).
- `StaticFileResolver::open_safe(std::string_view request_path)` walking components beneath a retained root directory fd (`O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC`), rejecting symlinks/traversal/non-regular files without pathname TOCTOU.
4. **Redirect Compliance in `HttpClient` (`src/Net/Http.cpp`)**:
- Follow only `301`, `302`, `303`, `307`, `308`; `303` converts non-HEAD to `GET` and strips body + `Content-Length`/`Content-Type`; `307`/`308` preserve method/body; resolve relative `Location` references against current URL; reject HTTPS->HTTP downgrade unless `allow_insecure_redirects`; strip `Authorization`, `Cookie`, `Proxy-Authorization`, `X-Api-Key` on cross-origin hops; enforce single absolute steady deadline across redirect hops.
5. **Native RFC 6455 WebSocket Wire Framing & Loopback Transport (`include/Void/Net/WebSocket.hpp`, `src/Net/WebSocket.cpp`, `include/Void/Net/HttpServer.hpp`, `src/Net/HttpServer.cpp`)**:
- `compute_websocket_accept(key)` (RFC 6455 SHA-1 + Base64), `validate_websocket_upgrade_request()` (version 13, `Upgrade: websocket`, `Connection: Upgrade`, 16-byte base64 key, optional origin/subprotocol policy).
- `WebSocketOpcode`, `WebSocketLimits` (`max_message_bytes = 1 MiB`, `max_output_messages = 64`, `max_output_bytes = 4 MiB`), `WebSocketFrame`, `encode_websocket_frame()`, `WebSocketFrameDecoder` enforcing client masking / server non-masking, fragmentation, control-frame rules (<= 125 bytes, FIN=1), strict RFC 3629 UTF-8 validation for text frames & close reasons, ping/pong, and single close handshake.
- `HttpServer::add_websocket_route(pattern, WebSocketSessions&, WebSocketUpgradeOptions)` upgrading incoming HTTP/1.1 requests into live RFC 6455 connections integrated with `WebSocketSessions`, plus loopback `WebSocketClient` for full client/server wire verification.
## Verification
- Standalone `Net;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`): split-byte smuggling & chunked/trailer/1xx/HEAD codec corpus, pool eviction & key isolation, `open_safe` symlink-swap rejection, redirect `303`/`307`/relative/cross-origin tests, RFC 6455 wire & loopback `WebSocketClient`/`HttpServer` ping/pong/fragmented/UTF-8/close/shutdown tests.
- `ctest` `NetOnly` installed consumer, full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
@@ -0,0 +1,27 @@
# Task Spec: `M-SHORTURL-01..04` — Frozen V1, Additive V2 Local/Durable/Remote Providers & V1 Adapter
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
- **Roadmap authority**: `docs/roadmap/modules/ShortUrl.md` (`M-SHORTURL-01`..`M-SHORTURL-04`), `ARCHITECTURE.md` C-02..C-05, C-09, C-13.
- **Error domain**: `Void::Result::kShortUrlErrorDomain = 28`.
## Scope & Deliverables
1. **Frozen `V1` Contract (`include/Void/ShortUrl/ShortUrl.hpp`, `docs/short-url.md`)**:
- Zero changes to `Void::ShortUrl::V1` layout, enum ordinals, virtual table order, or `docs/short-url.md`.
- Keep `ShortUrl` module's internal dependencies lightweight (`Service Time`), with zero `Storage`, `Net`, or `Security` dependencies.
2. **Additive `Void::ShortUrl::V2` Core & Local Provider (`include/Void/ShortUrl/V2.hpp`)**:
- `V2ErrorCode` mapped via `kShortUrlErrorDomain = 28` (`InvalidUrl`, `InvalidKey`, `InvalidExpiry`, `Conflict`, `NotFound`, `Expired`, `Revoked`, `Unsupported`, `RateLimited`, `QuotaExceeded`, `IdentityExpired`, `StorageError`, `UnknownOutcome`, `ProviderError`, `Timeout`, `Unavailable`).
- `CreateLink`, `ShortenOptions` (`operation_id`, `idempotency_ttl = 24h`), `Link`, `LinkRecord`, `LinkState::{Active, Revoked}`, `LocalProviderLimits` (`max_url_bytes = 8192`, `max_key_bytes = 64`, `generated_key_length = 16`, `max_collision_retries = 8`, `max_retained_identities = 10000`, `max_entries = 100000`, `max_concurrent_ops = 128`).
- Strict target URL validation (absolute `http`/`https`, no userinfo, no control chars, <= 8 KiB, optional host deny predicate) and custom key validation (1..64 `[A-Za-z0-9_-]`, case-sensitive, reserved route rejection).
- Abstract `LinkRepositoryPort` + `RandomBytesPort`, explicitly nondurable `InMemoryLinkRepository` (for unit/semantics tests), rejection-sampled base62 key generation, atomic conditional insert + idempotency record, civil expiry via injected `Void::Time::CivilClock`, tombstone `revoke()` (never reusing revoked keys), `V1Adapter` implementing `V1::IShortener` without modifying `V1`.
3. **Durable Storage Provider (`src/ShortUrlStorage/module.cmake`, `include/Void/ShortUrlStorage/StorageRepository.hpp`, `src/ShortUrlStorage/StorageRepository.cpp`)**:
- Separate module (`INTERNAL_DEPS ShortUrl Storage Security`) keeping `ShortUrl` free of `Storage`/`libsodium`.
- `StorageLinkRepository` backed by `Void::Storage::Engine` conditional `WriteBatch` (versioned records, atomic link + idempotency commit, tombstone persistence, byte quota enforcement, full recovery across engine reopen) + `SecurityRandomBytesPort` backed by `Void::Security::random_bytes`.
4. **Remote Provider SPI (`src/ShortUrlRemote/module.cmake`, `include/Void/ShortUrlRemote/RemoteProvider.hpp`, `src/ShortUrlRemote/RemoteProvider.cpp`)**:
- Separate module (`INTERNAL_DEPS ShortUrl Net Data`) keeping `ShortUrl` free of `Net`/Boost/OpenSSL.
- `RemoteCapabilities`, `RemoteProviderOptions` (explicit origin, secure `HttpClient`, max 1 MiB response, 10s deadline), `RemoteProvider` checking capability flags before network mutation, preserving `Retry-After` and classifying transport failures after send as `UnknownOutcome` without blind replay, plus loopback fixture tests.
5. **Installed Consumers**:
- `tests/package/ShortUrlOnly/` (`ShortUrl` with zero external packages) + `ShortUrlProviders` in `tests/package/InstalledComponents.cmake`.
## Verification
- Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`), `ctest` (`ShortUrlOnly`, `ShortUrlProviders`), full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
@@ -0,0 +1,28 @@
# Task Spec: `M-TESTINGMOCK-01..04` — Deterministic Sessions, Action-Outside-Lock, Move-Only Forwarding & Matcher Combinators
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
- **Roadmap authority**: `docs/roadmap/modules/TestingMock.md` (`M-TESTINGMOCK-01`..`M-TESTINGMOCK-04`), `ARCHITECTURE.md` C-02..C-05.
- **Error domain**: `Void::Result::kTestingMockErrorDomain = 27`.
## Scope & Deliverables
1. **Preserve 1.x API & Existing Tests**:
- Existing `Mock<Derived>`, `MockBase`, `MockFunction<R(Args...)>`, `Matcher<T>`, `Eq`, `_`, `Lt`, `Le`, `Gt`, `Ge`, `Range`, `Pred`, `StartsWith`, `Contains`, and all existing tests under `tests/standalone/TestingMock/` continue compiling and passing unchanged.
2. **Matcher Combinators (`include/Void/TestingMock/Matcher.hpp`)**:
- Add `Ne`, `EndsWith`, `Not`, `AllOf`, `AnyOf`, `IsNull`, `NotNull`, with bounded description/nesting depth (`kMaxMatcherDepth = 32`).
3. **Explicit Session, Sequences, Limits & Tokens (`include/Void/TestingMock/Session.hpp`)**:
- `Concurrency::{SingleThread, ConcurrentActions}`.
- `MockLimits{max_expectations = 1024, max_matchers = 64, max_events = 4096, max_diagnostic_bytes = 4 MiB, max_arg_render_bytes = 4 KiB}` (zero means zero capacity, never unlimited).
- `Sequence`: explicit per-group call ordering independent of global registration order.
- `Verification`: structured report (`ok()`, `unmet`, `excess`, `unmatched`, `prohibited`, `matcher_errors`, `threading_errors`, `events_truncated`, `total_events`, `format()`), idempotent across repeated calls.
- `MockSession`: `freeze(Concurrency)` (mutating a frozen session returns `ErrorKind::invalid_argument` / `InvalidState`), `verify_and_close()` (drains/joins active calls; returns `WouldDeadlock` if called from inside an active action), bounded event log with truncation tracking, RAII `RegistrationToken` stopping admission and waiting for admitted calls on unregister.
4. **Hardened `Expectation` & `SessionMockFunction` (`include/Void/TestingMock/Expectation.hpp`, `include/Void/TestingMock/MockFunction.hpp`)**:
- Action-outside-lock reservation protocol: snapshot immutable candidates under short lock -> evaluate matchers outside lock (catching matcher exceptions as `MatcherFailure`) -> reacquire lock to reserve matching unsaturated expectation & sequence slot -> release lock -> execute action -> decrement in-flight counter & record completion.
- Same-thread reentrant calls succeed in `SingleThread`; cross-thread concurrent entry in `SingleThread` reports deterministic threading violation; `ConcurrentActions` permits concurrent action execution safely.
- Perfect argument forwarding (`Args&&...`) to actions; `returns_once(U&&)` for move-only return types (`std::unique_ptr`), `invokes_once(F&&)` for one-shot move-only callables, `at_least(n)`, `at_most(n)`, `between(min, max)`, `never()` (checked before ordinary candidates), `in_sequence(Sequence&)`.
- Non-default-constructible return type on unmatched call records failure and throws TestingMock's invocation-abort exception (never `R{}` fallback).
5. **Installed Consumer (`tests/package/TestingMockOnly/`)**:
- Register `TestingMockOnly` in `tests/package/InstalledComponents.cmake` with `_no_external_deps`.
## Verification
- Standalone `TestingMock;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`), `ctest` `TestingMockOnly`, Debug `ASan+UBSan`, Debug `TSan` (concurrent action reservation & dynamic unregister races).
@@ -0,0 +1,39 @@
# S-DISCOVERY-01..04 — Discovery Subsystem (Catalog, Leases, Watches, Selectors, Optional RPC Adapter)
## Scope
Implement the P1–P3 native `Void::Discovery` subsystem per `docs/roadmap/subsystems/Discovery.md` and `docs/roadmap/DEPENDENCIES.md`, plus the optional `Void::DiscoveryRpc` endpoint adapter living strictly above `RPC` and `Discovery`:
1. **`S-DISCOVERY-01` — Boundary, Error Domain, and Immutable Value Contracts**:
- Module `src/Discovery/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero network, storage, or consensus dependencies.
- Error domain `kDiscoveryErrorDomain = 30` with `DiscoveryErrorCode` covering validation, conflict, cap exhaustion, expiry, stale/unavailable freshness, cancellation, and self-join diagnosis.
- Strict endpoint/attribute validation before publication (valid scheme/host/port, `weight > 0`, `max_attributes_per_record = 16`, `max_metadata_bytes_per_record = 4096`, `max_services = 1024`, `max_endpoints_per_service = 256`, `max_total_records = 10000`).
2. **`S-DISCOVERY-02` — Pure Catalog, Atomic Static Snapshots, and Local RAII Registrations**:
- Pure `Catalog` construction creating zero hidden threads.
- Atomic candidate `replace_static()` rejecting invalid/conflicting candidates while preserving the active revision; explicit `provider_generation` bump resets revision domain and emits `ResyncRequired`.
- Local move-only RAII `Registration` handles with explicit `LeasePolicy` (default 30s TTL / 10s renew interval via injected `MonotonicClock`; zero TTL rejected as `InvalidArgument`; unleased explicit mode valid until release; static entries never expire).
- Duplicate `(service, instance)` returns `Conflict` without stealing existing handles.
- Deterministic `resolve()` sorted by `instance`, filtering logically expired records before cleanup runs, respecting `ResolvePolicy::allow_stale` and `Freshness`.
3. **`S-DISCOVERY-03` — Bounded Watches, Resync, Client Selectors, and Managed Renewal**:
- Bounded `watch()` (`max_watches = 1024`, `max_events_per_watch = 64`, shared `16 MiB` event budget) emitting `InitialSnapshot`, serialized per-watch `Delta`, and explicit `ResyncRequired` + full latest `Snapshot` on overflow or provider-generation reset.
- Callbacks run outside catalog and watch locks; `cancel()` stops new admission (including self-cancel inside a callback); `join()` drains admitted callbacks and diagnoses synchronous self-join (`SelfJoin`) instead of deadlocking.
- `Catalog::shutdown_and_join()` removes local entries, cancels watches, and joins admitted callbacks; destructor only requests stop.
- `WeightedRoundRobinSelector`, stable HRW `AffinitySelector`, and deterministic `ManagedLeaseRenewer`.
4. **`S-DISCOVERY-04` — Optional RPC Integration (`DiscoveryRpc`)**:
- Separate module `src/DiscoveryRpc/module.cmake` (`INTERNAL_DEPS Discovery RPC`) so `RPC` remains completely independent of `Discovery`.
- `EndpointResolverClient` resolves endpoints from `Discovery::Catalog`, selects via client selector, preserves configured `expected_tls_name` / identity across IP/address refreshes (rejecting TLS scheme/identity downgrade), and executes unary calls via `Void::RPC::Client`.
## File Ownership
- `include/Void/Discovery/{Types,Catalog}.hpp`
- `src/Discovery/{module.cmake,Catalog.cpp}`
- `include/Void/DiscoveryRpc/EndpointAdapter.hpp`
- `src/DiscoveryRpc/{module.cmake,EndpointAdapter.cpp}`
- `tests/standalone/Discovery/Catalog.cpp`
- `tests/standalone/DiscoveryRpc/EndpointAdapter.cpp`
- `tests/package/DiscoveryOnly/{CMakeLists.txt,main.cpp}`
- `tests/package/InstalledComponents.cmake`
## Acceptance & Verification
- Standalone `Discovery;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `DiscoveryOnly` consumer with `_no_external_deps`.
- `DiscoveryRpc` identity-preserving refresh + RPC round-trip tests; `RpcOnly` remains Discovery-free.
- Deterministic fake-clock lease expiry/renewal, atomic bad/good config replacement, duplicate registration conflict, watch overflow -> `ResyncRequired`, self-cancel/self-join, and selector determinism.
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
@@ -0,0 +1,41 @@
# S-MESSAGING-01..04 — Messaging Subsystem (Delivery Model, Ephemeral Queue, Durable Storage Queue, Outbox/Inbox, RPC Adapter)
## Scope
Implement the P1–P3 native `Void::Messaging` subsystem, `Void::MessagingStorage` durable adapter + outbox/inbox helper, and `Void::MessagingRpc` remote adapter per `docs/roadmap/subsystems/Messaging.md` and `docs/roadmap/DEPENDENCIES.md`:
1. **`S-MESSAGING-01..02` — Delivery Model, Receipts, State Machine, and Bounded Ephemeral Queue**:
- Module `src/Messaging/module.cmake` (`INTERNAL_DEPS Core Functional Binary Time Async`) with zero `Storage`, `Net`, or `RPC` dependency.
- Error domain `kMessagingErrorDomain = 32` (`MessagingErrorCode`).
- Explicit `PublishDurability::{Memory, Durable}`: `InMemoryQueue` strictly rejects `PublishDurability::Durable` (`UnsupportedDurability`) and `PublishReceipt` records exact durability so nondurable channels never claim durable success.
- Native state machine `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`.
- FIFO per-queue competing consumers and `ConsumerMode::SingleActive` (blocking group head on retry until ack).
- Visibility timeout (default 30s, explicit extension up to 5m via injected `MonotonicClock`), stale-receipt fencing (`StaleReceipt`), idempotent repeat ack, retry bound (default 5 attempts, full jitter 1s..60s via injectable RNG), corrupt-payload quarantine, and bounded caps (768 KiB message, 8 KiB / 32 headers, 1024 queues, 32 groups/queue, 64 in-flight/group, 1024 waiting receives, 64 MiB transient payload budget).
- Clean `close_and_join()` stopping admission, waking/cancelling waiting receives, and draining active deliveries.
2. **`S-MESSAGING-03` — Durable Storage Queue (`MessagingStorage`)**:
- Module `src/MessagingStorage/module.cmake` (`INTERNAL_DEPS Messaging Storage`).
- `StorageQueue` persists payload, sequence, group state, delivery generation/attempt, DLQ records, and bounded 24h / 100k publish idempotency ledger via `Void::Storage::Engine` conditional batches (`Durability::Sync`).
- At idempotency capacity, rejects new publish (`IdempotencyCapacityExceeded`) instead of silently evicting live contracts.
- On restart/reopen, promotes all prior `InFlight` records to `Pending` with bumped generation so stale worker receipts fail with `StaleReceipt`, preserving attempt counters across restarts.
- Atomic DLQ move (DLQ insert + source group removal in one `Storage::Batch`); when DLQ or persistent quota is full, keeps the message durable, drops zero data, blocks affected admission, and exposes `stuck_dlq_count()`.
- Explicit `RetentionPolicy::BlockAtQuota` default (unread work never silently expired) vs opt-in `DropOldestLossy`, pausing expiry when civil clock health fails; `UnknownOutcome` surfaced on uncertain storage commit.
3. **`S-MESSAGING-04` — Outbox/Inbox Local-Batch Helper and Remote RPC Adapter (`MessagingRpc`)**:
- `OutboxInbox` helper in `MessagingStorage` enabling single-batch local business mutation + outbox insert and single-batch local effect + inbox dedup insert, with explicit documentation that external effects remain outside the local batch boundary.
- Separate module `src/MessagingRpc/module.cmake` (`INTERNAL_DEPS Messaging RPC`) exposing `RpcQueueServer` and `RpcQueueClient` for remote `publish`, `receive`, `ack`, `nack`, and `query_receipt` over Wire v1 unary RPC.
## File Ownership
- `include/Void/Messaging/{Types,Queue}.hpp`
- `src/Messaging/{module.cmake,Queue.cpp}`
- `include/Void/MessagingStorage/{StorageQueue,OutboxInbox}.hpp`
- `src/MessagingStorage/{module.cmake,StorageQueue.cpp}`
- `include/Void/MessagingRpc/RpcAdapter.hpp`
- `src/MessagingRpc/{module.cmake,RpcAdapter.cpp}`
- `tests/standalone/Messaging/Messaging.cpp`
- `tests/standalone/MessagingStorage/StorageQueue.cpp`
- `tests/standalone/MessagingRpc/RpcAdapter.cpp`
- `tests/package/MessagingOnly/{CMakeLists.txt,main.cpp}`
- `tests/package/InstalledComponents.cmake`
## Acceptance & Verification
- Standalone `Messaging;MessagingStorage;MessagingRpc;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `MessagingOnly` consumer with `_no_external_deps`.
- Deterministic tests for ephemeral/durable separation, competing vs single-active ordering, visibility expiry & stale receipt fencing, idempotent ack/publish, restart recovery preserving attempts, poison -> atomic DLQ move, DLQ/quota/idempotency cap pressure, clock-health pause, outbox/inbox single-batch atomicity, and remote RPC round-trip.
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
+30
View File
@@ -0,0 +1,30 @@
# Task Spec: `S-RPC-01..03` — NEW `Void::RPC` Subsystem (Wire v1 Binary Codec & Unary HTTP/1.1 Transport)
- **Branch**: `feat/roadmap-p2-wave9` (baseline `main` at `3e25405`).
- **Roadmap authority**: `docs/roadmap/subsystems/RPC.md` (`S-RPC-01`..`S-RPC-03`), `ARCHITECTURE.md` C-02..C-07, C-11..C-13.
- **Error domain**: `Void::Result::kRpcErrorDomain = 29`.
## Scope & Deliverables
1. **Module Boundary (`src/RPC/module.cmake`)**:
- `void_add_module(RPC INTERNAL_DEPS Core Functional Binary Data Time Async Net)`.
- Zero dependency on `Coordination`, `Discovery`, `Replication`, `Security`, or platform hosts.
2. **Types & Limits (`include/Void/RPC/Types.hpp`)**:
- `RpcStatusCode` (`Ok`, `Cancelled`, `InvalidArgument`, `DeadlineExceeded`, `NotFound`, `PermissionDenied`, `Unauthenticated`, `ResourceExhausted`, `FailedPrecondition`, `Unimplemented`, `Unavailable`, `Internal`, `DataLoss`, `UnknownOutcome`, `ProtocolError`, `IncompatibleVersion`).
- `MethodId{service, method}`, `PrincipalView` (immutable authenticated principal attributes), `MetadataEntry`, `MethodDescriptor{id, service_name, method_name, schema_version, replay_safe}`.
- `RpcLimits`: `max_header_bytes = 16 KiB`, `max_metadata_entries = 64`, `max_payload_bytes = 4 MiB`, `max_client_calls = 1024`, `max_server_executing = 256`, `max_server_queued_bytes = 64 MiB`, `max_server_timeout = 30s`.
3. **Wire v1 Binary Envelope Codec (`include/Void/RPC/Codec.hpp`, `src/RPC/Codec.cpp`)**:
- Explicit network byte order via `Void::Binary::Writer`/`Reader`:
- 4-byte magic `VRPC`, `u16 major (1)`, `u16 minor (0)`, `u32 header_length`, `u32 total_length`, `u8 frame_kind`, `u8 flags`, `u16 reserved (0)`, 128-bit `call_id` (`Uuid`), `u64 service_id`, `u32 method_id`, `u32 schema_version`, `u32 remaining_timeout_ms`, `u16 status_code`, `u16 metadata_count`, length-delimited metadata pairs, payload bytes.
- Strict bounds/overflow checks BEFORE allocating metadata/payload; rejects bad magic, unsupported major, non-zero reserved field, unknown required flags, truncated/extra bytes, oversized header/metadata/payload; skips unknown optional minor trailing header extensions cleanly.
4. **Unary HTTP/1.1 Server & Client (`include/Void/RPC/Rpc.hpp`, `src/RPC/Rpc.cpp`)**:
- `CallContext` (`call_id`, `principal`, local steady `deadline`, `remaining_timeout()`, `metadata`, `stop`).
- `AuthHook` (`authenticate(headers, metadata) -> Result<PrincipalView>` and `authorize(MethodDescriptor, PrincipalView) -> Result<void>`) executed outside dispatch locks before handler admission.
- `Server`: binds methods returning move-only RAII `Registration` (destructor/explicit `unregister_and_drain()` stops admission and waits for in-flight calls), mounts `/void-rpc/v1/call` on `Void::Net::HttpServer`, validates wire v1 envelope, schema version, auth/authz, concurrency/payload budgets, clamps relative timeout to `limits.max_server_timeout`, executes handlers outside locks, and translates handler errors/exceptions into sanitized `RpcStatus`.
- `Client`: encodes wire v1 unary request envelope, sends HTTP/1.1 POST to `/void-rpc/v1/call` via `Void::Net::HttpClient`, propagates remaining relative timeout and `std::stop_token`, separates HTTP transport failures from RPC domain status, enforces client concurrency & payload limits, never implicitly retries non-`replay_safe` methods.
5. **Installed Consumer (`tests/package/RpcOnly/`)**:
- Register `RpcOnly` in `tests/package/InstalledComponents.cmake` proving `Void::RPC` links cleanly without `LibArchive`, `PkgConfig`, or `SQLite3`.
## Verification
- Standalone `RPC;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`): wire v1 round-trip, overflow/truncation/unknown-major/reserved-flag rejection, loopback unary calls, schema mismatch, auth/authz denial, deadline clamping, handler exception sanitization, unregister drain under concurrent load.
- `ctest` (`RpcOnly`), full `RelWithDebInfo`, Debug `ASan+UBSan`, Debug `TSan`.
@@ -0,0 +1,40 @@
# S-SCHEDULER-01..04 — Scheduler Subsystem (Timers, Calendar, Durable Storage Store, Operator Controls)
## Scope
Implement the P1–P3 native `Void::Scheduler` subsystem and `Void::SchedulerStorage` durable adapter per `docs/roadmap/subsystems/Scheduler.md` and `docs/roadmap/DEPENDENCIES.md`:
1. **`S-SCHEDULER-01` — In-Memory Heap, Recurrence, Overlap, Cancellation & Shutdown**:
- Module `src/Scheduler/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero `Storage` dependency.
- Error domain `kSchedulerErrorDomain = 31` (`SchedulerErrorCode`).
- Monotonic min-heap ordered by `(due_time, sequence)` using injected `MonotonicClock` and `CivilClock`, pure construction (no hidden background threads), and `Async::OperationOptions` for deadlines/cancellation.
- One-shot, fixed-delay (advances from durable completion), and fixed-rate (advances from intended schedule time) schedules; `OverlapPolicy` (`Forbid`, `QueueOne`, `AllowBounded`); `RetryPolicy` (default 5 attempts, exponential backoff 1s..5m, x2, injectable full-jitter RNG); callbacks run outside scheduler/store locks.
- `close_and_join()` stops materialization/dispatch, signals active handlers, joins within deadline, and returns `ShutdownReport` preserving running records on timeout.
2. **`S-SCHEDULER-02` — Calendar Grammar, Explicit Timezones/DST, and Bounded Misfire**:
- 5-field cron-like grammar (`minute hour day month weekday` with `*`, lists, ranges, steps; both day-of-month and weekday constraints apply).
- Explicit `TimezoneRegistry` supporting `"UTC"`, fixed offsets (`+HH:MM`/`-HH:MM`), and explicit DST transition rules (`DstGapPolicy::Skip`/`NextValid`, `DstFoldPolicy::First`/`Second`/`Twice` with persisted `fold_index`). Unknown timezone fails with `UnsupportedTimezone` (never silent UTC fallback).
- `MisfirePolicy` (`Skip`, `CoalesceLatest`, `CatchUpBounded` capped at `100` slots/job/pass while preserving remaining cursor state even across millions of missed slots).
3. **`S-SCHEDULER-03` — Durable Persistence Port and `SchedulerStorage` Adapter**:
- `JobStore` port + `InMemoryJobStore` (in `Scheduler`) and `StorageJobStore` (in `src/SchedulerStorage/module.cmake`, `INTERNAL_DEPS Scheduler Storage`) backed by `Void::Storage::Engine` conditional batches (`Durability::Sync`, 1 MiB batch cap).
- Exclusive ownership lock rejecting second concurrent scheduler owner (`OwnershipLocked`).
- Atomic occurrence materialization + cursor advance with unique `(job, revision, civil_slot, fold)` dedup key preventing duplicate materialization on wall-clock rollback.
- Atomic `Pending -> Running` claim checking job tombstone and revision invalidation watermark in the same conditional batch; `Running -> Completed` / `Pending` / `Dead` transitions; `UnknownOutcome` surfaced faithfully on unknown storage write outcome.
- Startup crash recovery returning `Running` occurrences to `Pending` with the exact same `OccurrenceId` (explicit at-least-once semantics).
4. **`S-SCHEDULER-04` — Revision Updates, Tombstone Removal, Retention Caps, and Operator Inspection**:
- `update_job()` bumps revision and atomically writes old-revision invalidation watermark so unstarted old occurrences are cancelled without racing active claims; failed updates leave prior policy intact.
- `remove_job()` writes tombstone, stops admission, and requests stop for active handlers.
- Retention count cap pauses materialization without advancing cursors or deleting unacknowledged work; dead occurrences require explicit `acknowledge_dead()` before pruning; bounded `prune_completed()` / `reclaim_invalidated()` and inspection APIs.
## File Ownership
- `include/Void/Scheduler/{Types,Calendar,Store,Scheduler}.hpp`
- `src/Scheduler/{module.cmake,Calendar.cpp,Scheduler.cpp}`
- `include/Void/SchedulerStorage/StorageJobStore.hpp`
- `src/SchedulerStorage/{module.cmake,StorageJobStore.cpp}`
- `tests/standalone/Scheduler/Scheduler.cpp`
- `tests/standalone/SchedulerStorage/StorageJobStore.cpp`
- `tests/package/SchedulerOnly/{CMakeLists.txt,main.cpp}`
- `tests/package/InstalledComponents.cmake`
## Acceptance & Verification
- Standalone `Scheduler;SchedulerStorage;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `SchedulerOnly` consumer with `_no_external_deps`.
- Deterministic fake-clock ordering, overlap, retry/dead-letter, DST gap/fold/unknown-tz, millions-of-missed-slots coalesce/catch-up cap, crash/reopen recovery preserving `OccurrenceId`, revision watermark race, unknown outcome, and retention-cap cursor preservation tests.
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
+21 -6
View File
@@ -29,9 +29,14 @@ namespace Void::Archive
std::uint64_t bytes{0};
};
/// 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
/// Returns true if Void::Archive was built with LibArchive support (required
/// for .tar.zst and .tar.gz compression/decompression; uncompressed USTAR/PAX
/// .tar reading and writing work with zero external dependencies).
[[nodiscard]] bool has_libarchive_backend() noexcept;
/// Extract a tar/tar.gz/tar.zst archive incrementally into `destination`
/// without invoking an external process. Preserved 1.x incremental API;
/// callers requiring all-or-nothing directory visibility should use
/// `extract_staged` + `StagedTree::publish`.
[[nodiscard]] Void::Result::Result<ExtractionResult>
extract(const std::filesystem::path& archivePath,
@@ -177,9 +182,9 @@ namespace Void::Archive
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.
/// Create a bounded, optionally reproducible tar, tar.gz, or tar.zst
/// archive from regular file and directory entries. Sorts normalized
/// paths, rejects duplicates/conflicts, and opens source files with O_NOFOLLOW.
[[nodiscard]] Void::Result::Result<void>
create_archive(ByteSink& sink, std::span<const CreateEntry> entries,
const CreationOptions& options = {});
@@ -189,6 +194,16 @@ namespace Void::Archive
std::span<const CreateEntry> entries,
const CreationOptions& options = {});
/// Canonical snake_case alias for `create_archive`.
[[nodiscard]] Void::Result::Result<void>
create(ByteSink& sink, std::span<const CreateEntry> entries,
const CreationOptions& options = {});
[[nodiscard]] Void::Result::Result<void>
create(const std::filesystem::path& output_path,
std::span<const CreateEntry> entries,
const CreationOptions& options = {});
/// Hardened untrusted-input profile: extracts the archive in an isolated
/// System child process with bounded execution time and RSS checks, then
/// independently verifies the staged tree and inventory in the parent
+6 -1
View File
@@ -175,13 +175,17 @@ namespace Void::Archive
ProgressCallback on_progress{};
};
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd };
enum class ArchiveCompression : std::uint8_t { None = 0, Zstd, Gzip };
struct CreationOptions {
ArchiveCompression compression{ArchiveCompression::Zstd};
bool reproducible{true};
ReadLimits limits{};
std::stop_token stop{};
std::int64_t canonical_mtime{0};
std::uint32_t canonical_uid{0};
std::uint32_t canonical_gid{0};
bool prefer_builtin_tar{false};
};
struct CreateEntry {
@@ -190,6 +194,7 @@ namespace Void::Archive
bool executable{false};
std::vector<std::byte> content{};
std::optional<std::filesystem::path> source_file{};
std::optional<std::uint32_t> mode{};
};
struct IsolationOptions {
+1 -1
View File
@@ -188,7 +188,7 @@ public:
return std::unexpected{bytes.error()};
}
std::array<std::byte, sizeof(T)> storage{};
std::ranges::copy(*bytes, storage.begin());
std::memcpy(storage.data(), bytes->data(), sizeof(T));
T value = std::bit_cast<T>(storage);
if (byteOrder != std::endian::native) {
value = std::byteswap(value);
+85 -5
View File
@@ -2,7 +2,10 @@
#include <Void/Core/Meta.hpp>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
@@ -11,23 +14,56 @@
namespace Void::Argparse
{
enum class ParseOutcome : std::uint8_t {
Ok,
Help,
Error,
};
struct ParseResult {
ParseOutcome outcome{ParseOutcome::Ok};
std::string message{};
std::vector<std::string> matched_command_path{};
[[nodiscard]] bool ok() const noexcept
{
return outcome == ParseOutcome::Ok;
}
[[nodiscard]] bool is_help() const noexcept
{
return outcome == ParseOutcome::Help;
}
[[nodiscard]] bool is_error() const noexcept
{
return outcome == ParseOutcome::Error;
}
};
// ── Parser
// ────────────────────────────────────────────────────────────────────
// Fluent command-line argument parser.
//
// Supports:
// --flag, -f boolean flag (default false, set to true by
// presence)
// presence)
// --key=value option with value (= or space separator)
// --key value option with value
// option_many(...) repeatable option collecting all occurrences
// subcommand(...) nested subcommand parsers (e.g. "compdb use")
// positional args collected in declaration order
// --help / -h auto-generated help text
// --help / -h auto-generated help text (ParseOutcome::Help)
class Parser
{
public:
explicit Parser(std::string program, std::string description = {});
~Parser();
Parser(const Parser&) = delete;
Parser& operator=(const Parser&) = delete;
Parser(Parser&&) noexcept;
Parser& operator=(Parser&&) noexcept;
// Add a boolean flag.
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name
@@ -43,6 +79,12 @@ namespace Void::Argparse
std::string_view description,
std::optional<std::string>& out);
// Add a repeatable option collecting all occurrences into `out`.
Parser& option_many(std::string_view long_name,
std::string_view short_name,
std::string_view description,
std::vector<std::string>& out);
// Add an option with a default value. out is always set after
// parse().
Parser& option_default(std::string_view long_name,
@@ -55,7 +97,28 @@ namespace Void::Argparse
Parser& positional(std::string_view name,
std::string_view description, std::string& out);
// Parse argc/argv. Returns error message on failure.
// Add a variadic trailing positional argument list.
Parser& positional_many(std::string_view name,
std::string_view description,
std::vector<std::string>& out,
bool required = false);
// Register a nested subcommand and return a reference to its
// Parser. The returned reference remains valid for the lifetime of
// the parent Parser.
Parser& subcommand(std::string name, std::string description = {},
std::function<void()> on_selected = {});
// Control whether a parser with subcommands requires one to be
// selected (default: true when any subcommand is registered).
Parser& require_subcommand(bool required = true) noexcept;
// Parse argc/argv with explicit Ok / Help / Error classification.
[[nodiscard]] ParseResult
parse_detailed(int argc, const char* const* argv) const;
// Parse argc/argv. Returns error message (or help text) on
// non-Ok outcome for 1.x compatibility.
[[nodiscard]] std::expected<void, std::string>
parse(int argc, const char* const* argv) const;
@@ -70,18 +133,33 @@ namespace Void::Argparse
};
struct OptionEntry {
std::string lng, sht, desc, def;
std::optional<std::string>* out_opt;
std::string* out_str;
std::optional<std::string>* out_opt{nullptr};
std::string* out_str{nullptr};
std::vector<std::string>* out_many{nullptr};
};
struct PosEntry {
std::string name, desc;
std::string* out;
};
struct MultiPosEntry {
std::string name, desc;
std::vector<std::string>* out{nullptr};
bool required{false};
};
struct SubcommandEntry {
std::string name;
std::unique_ptr<Parser> parser;
std::function<void()> on_selected;
};
std::string program_, description_;
std::vector<FlagEntry> flags_;
std::vector<OptionEntry> options_;
std::vector<PosEntry> positionals_;
std::optional<MultiPosEntry> positional_many_;
std::vector<SubcommandEntry> subcommands_;
bool has_explicit_require_sub_{false};
bool require_subcommand_{true};
};
// ── reflective options struct
@@ -147,6 +225,8 @@ namespace Void::Argparse
parser.flag(lng, sht, desc, out.[:m:]);
} else if constexpr (Void::Meta::is_optional_v<MT>) {
parser.option(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
parser.option_many(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::string>) {
const std::string def = out.[:m:];
parser.option_default(lng, sht, desc, out.[:m:], def);
+28 -1
View File
@@ -13,9 +13,14 @@
namespace Void::Crypto
{
enum class HashAlgorithm { Sha1, Sha256, Sha512 };
enum class HashAlgorithm { Sha1, Sha256, Sha512, Blake2b256, Blake2b512 };
using Digest = std::vector<std::byte>;
/// Returns true if Void::Crypto was built with OpenSSL support (required
/// for Ed25519; hashing/HMAC/HKDF work on the built-in pure-C++ backend
/// with zero external dependencies).
[[nodiscard]] bool has_openssl_backend() noexcept;
class Hasher
{
public:
@@ -60,6 +65,11 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest>
hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest>
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider);
[[nodiscard]] Void::Result::Result<Digest>
sha1(std::span<const std::byte> data);
@@ -70,12 +80,29 @@ namespace Void::Crypto
[[nodiscard]] Void::Result::Result<Digest>
sha512(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> sha512(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
blake2b256(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> blake2b256(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
blake2b512(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<Digest> blake2b512(std::string_view data);
[[nodiscard]] Void::Result::Result<Digest>
sha1File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha256File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha512File(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha1_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha256_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
sha512_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
blake2b256_file(const std::filesystem::path& path);
[[nodiscard]] Void::Result::Result<Digest>
blake2b512_file(const std::filesystem::path& path);
/// Move-only owning Ed25519 private key handle. Has no implicit copy,
/// string conversion, or secret formatting.
+2 -1
View File
@@ -111,10 +111,11 @@ namespace Void::Crypto
MovedFrom
};
/// Per-operation OpenSSL 3 provider selection. Never mutates process-wide
/// Per-operation backend/provider selection. Never mutates process-wide
/// provider state.
struct ProviderOptions {
std::string property_query{};
bool prefer_builtin{false};
};
struct Ed25519PublicKey {
+246
View File
@@ -1,5 +1,6 @@
#pragma once
#include <array>
#include <charconv>
#include <cmath>
#include <cstddef>
@@ -41,6 +42,72 @@ namespace Void::Json::Strict
ParseError error;
};
[[nodiscard]] constexpr std::size_t
validate_utf8_at(const std::string_view input,
const std::size_t pos) noexcept
{
if (pos >= input.size()) {
return 0U;
}
const auto b0 = static_cast<unsigned char>(input[pos]);
if (b0 <= 0x7FU) {
return 1U;
}
if (b0 >= 0xC2U && b0 <= 0xDFU) {
if (pos + 1U >= input.size()) {
return 0U;
}
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
return (b1 >= 0x80U && b1 <= 0xBFU) ? 2U : 0U;
}
if (b0 >= 0xE0U && b0 <= 0xEFU) {
if (pos + 2U >= input.size()) {
return 0U;
}
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
const unsigned char lo = (b0 == 0xE0U) ? 0xA0U : 0x80U;
const unsigned char hi = (b0 == 0xEDU) ? 0x9FU : 0xBFU;
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU) {
return 0U;
}
return 3U;
}
if (b0 >= 0xF0U && b0 <= 0xF4U) {
if (pos + 3U >= input.size()) {
return 0U;
}
const auto b1 = static_cast<unsigned char>(input[pos + 1U]);
const auto b2 = static_cast<unsigned char>(input[pos + 2U]);
const auto b3 = static_cast<unsigned char>(input[pos + 3U]);
const unsigned char lo = (b0 == 0xF0U) ? 0x90U : 0x80U;
const unsigned char hi = (b0 == 0xF4U) ? 0x8FU : 0xBFU;
if (b1 < lo || b1 > hi || b2 < 0x80U || b2 > 0xBFU ||
b3 < 0x80U || b3 > 0xBFU) {
return 0U;
}
return 4U;
}
return 0U;
}
[[nodiscard]] inline std::expected<void, ParseError>
validate_utf8_bytes(const std::string_view input)
{
std::size_t pos = 0U;
while (pos < input.size()) {
const std::size_t len = validate_utf8_at(input, pos);
if (len == 0U) {
return std::unexpected{ParseError{
.offset = pos,
.message = "invalid UTF-8 sequence",
}};
}
pos += len;
}
return {};
}
class Parser final
{
public:
@@ -179,6 +246,18 @@ namespace Void::Json::Strict
fail("control character in string");
}
if (value != '\\') {
if (value >= 0x80U) {
const std::size_t seq_start = position_ - 1U;
const std::size_t len =
validate_utf8_at(input_, seq_start);
if (len == 0U) {
position_ = seq_start;
fail("invalid UTF-8 sequence");
}
output.append(input_.substr(seq_start, len));
position_ = seq_start + len;
continue;
}
output.push_back(static_cast<char>(value));
continue;
}
@@ -435,4 +514,171 @@ namespace Void::Json::Strict
.allowDecimals = true});
}
[[nodiscard]] inline bool is_valid_utf8(const std::string_view input) noexcept
{
std::size_t pos = 0U;
while (pos < input.size()) {
const std::size_t len = Detail::validate_utf8_at(input, pos);
if (len == 0U) {
return false;
}
pos += len;
}
return true;
}
[[nodiscard]] inline std::expected<void, ParseError>
validate_utf8(const std::string_view input)
{
return Detail::validate_utf8_bytes(input);
}
namespace Detail
{
inline void append_escaped_string(std::string& out,
const std::string_view text)
{
const auto utf8 = validate_utf8_bytes(text);
if (!utf8.has_value()) {
throw ParseFailure{.error = utf8.error()};
}
out.push_back('"');
std::size_t pos = 0U;
while (pos < text.size()) {
const auto ch = static_cast<unsigned char>(text[pos]);
switch (ch) {
case '"':
out += "\\\"";
++pos;
break;
case '\\':
out += "\\\\";
++pos;
break;
case '\b':
out += "\\b";
++pos;
break;
case '\f':
out += "\\f";
++pos;
break;
case '\n':
out += "\\n";
++pos;
break;
case '\r':
out += "\\r";
++pos;
break;
case '\t':
out += "\\t";
++pos;
break;
default:
if (ch < 0x20U) {
static constexpr char kHex[] = "0123456789abcdef";
out += "\\u00";
out.push_back(kHex[(ch >> 4U) & 0x0FU]);
out.push_back(kHex[ch & 0x0FU]);
++pos;
} else if (ch >= 0x80U) {
const std::size_t len = validate_utf8_at(text, pos);
out.append(text.substr(pos, len));
pos += len;
} else {
out.push_back(static_cast<char>(ch));
++pos;
}
break;
}
}
out.push_back('"');
}
inline void serialize_value(std::string& out, const Value& val,
const std::size_t depth,
const std::size_t maximumDepth)
{
if (depth > maximumDepth) {
throw ParseFailure{
.error =
{
.offset = out.size(),
.message = "nesting limit exceeded during serialize",
},
};
}
std::visit(
[&](const auto& node) {
using T = std::decay_t<decltype(node)>;
if constexpr (std::same_as<T, std::nullptr_t>) {
out += "null";
} else if constexpr (std::same_as<T, bool>) {
out += (node ? "true" : "false");
} else if constexpr (std::same_as<T, std::int64_t>) {
std::array<char, 32> buf{};
const auto res = std::to_chars(
buf.data(), buf.data() + buf.size(), node);
out.append(buf.data(), res.ptr);
} else if constexpr (std::same_as<T, double>) {
if (!std::isfinite(node)) {
throw ParseFailure{
.error =
{
.offset = out.size(),
.message =
"non-finite double is not valid JSON",
},
};
}
std::array<char, 64> buf{};
const auto res = std::to_chars(
buf.data(), buf.data() + buf.size(), node,
std::chars_format::general);
out.append(buf.data(), res.ptr);
} else if constexpr (std::same_as<T, std::string>) {
append_escaped_string(out, node);
} else if constexpr (std::same_as<T, Value::Array>) {
out.push_back('[');
for (std::size_t i = 0; i < node.size(); ++i) {
if (i > 0U) {
out.push_back(',');
}
serialize_value(out, node[i], depth + 1U,
maximumDepth);
}
out.push_back(']');
} else if constexpr (std::same_as<T, Value::Object>) {
out.push_back('{');
bool first = true;
for (const auto& [k, v] : node) {
if (!first) {
out.push_back(',');
}
first = false;
append_escaped_string(out, k);
out.push_back(':');
serialize_value(out, v, depth + 1U, maximumDepth);
}
out.push_back('}');
}
},
val.value);
}
} // namespace Detail
[[nodiscard]] inline std::expected<std::string, ParseError>
serialize(const Value& value,
const std::size_t maximumDepth = default_maximum_depth)
{
try {
std::string out;
Detail::serialize_value(out, value, 0U, maximumDepth);
return out;
} catch (const Detail::ParseFailure& failure) {
return std::unexpected{failure.error};
}
}
} // namespace Void::Json::Strict
File diff suppressed because it is too large. Load diff
+216
View File
@@ -0,0 +1,216 @@
#pragma once
#include <Void/Discovery/Types.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Discovery
{
class Catalog;
/// Move-only RAII handle for a local endpoint registration.
/// Destruction releases the registration from future snapshots.
class Registration final
{
public:
Registration() noexcept = default;
~Registration() noexcept;
Registration(Registration&& other) noexcept;
Registration& operator=(Registration&& other) noexcept;
Registration(const Registration&) = delete;
Registration& operator=(const Registration&) = delete;
[[nodiscard]] bool active() const noexcept;
[[nodiscard]] const std::string& service() const noexcept
{
return m_service;
}
[[nodiscard]] const std::string& instance() const noexcept
{
return m_instance;
}
[[nodiscard]] std::optional<Void::Time::MonotonicClock::time_point>
expires_at() const noexcept;
[[nodiscard]] Result<Void::Time::MonotonicClock::time_point> renew();
void release() noexcept;
private:
friend class Catalog;
struct State;
std::shared_ptr<void> m_catalog_state{};
std::string m_service{};
std::string m_instance{};
std::uint64_t m_token{0};
bool m_leased{false};
std::chrono::milliseconds m_ttl{0};
bool m_active{false};
};
/// Move-only handle for a bounded service watch.
/// `cancel()` stops new admission and is safe from inside the callback.
/// `join()` waits for already-admitted callbacks and returns `SelfJoin`
/// instead of deadlocking when called synchronously from the callback itself.
class WatchHandle final
{
public:
WatchHandle() noexcept = default;
~WatchHandle() noexcept;
WatchHandle(WatchHandle&& other) noexcept;
WatchHandle& operator=(WatchHandle&& other) noexcept;
WatchHandle(const WatchHandle&) = delete;
WatchHandle& operator=(const WatchHandle&) = delete;
[[nodiscard]] bool active() const noexcept;
[[nodiscard]] std::size_t pending_events() const noexcept;
void cancel() noexcept;
[[nodiscard]] Result<void> join() noexcept;
/// Explicit deterministic delivery step for `Manual` watch mode.
/// Returns true if an event was delivered.
bool deliver_one();
std::size_t deliver_all();
private:
friend class Catalog;
std::shared_ptr<void> m_catalog_state{};
std::shared_ptr<void> m_watch_node{};
std::uint64_t m_watch_id{0};
};
/// Pure, thread-free service endpoint catalog supporting atomic static
/// snapshots, local RAII leased/unleased registrations, and bounded watches.
class Catalog final
{
public:
explicit Catalog(CatalogOptions options = {});
~Catalog() noexcept;
Catalog(Catalog&&) noexcept;
Catalog& operator=(Catalog&&) noexcept;
Catalog(const Catalog&) = delete;
Catalog& operator=(const Catalog&) = delete;
/// Validate candidate static snapshot completely before atomic
/// publication. On any validation/conflict/cap error, preserves the
/// active revision unchanged.
[[nodiscard]] Result<std::uint64_t>
replace_static(std::vector<EndpointRecord> candidate,
bool bump_provider_generation = false);
/// Explicitly set provider health (e.g. for stale/unavailable
/// resolution policy testing or upper replicated directory adapters).
void set_provider_health(Freshness freshness,
std::optional<Error> provider_error =
std::nullopt);
[[nodiscard]] Result<Snapshot>
resolve(std::string_view service,
ResolvePolicy policy = {}) const;
[[nodiscard]] Result<Registration>
register_local(EndpointRecord record,
LeasePolicy lease = LeasePolicy::unleased());
[[nodiscard]] Result<WatchHandle>
watch(std::string service, std::uint64_t after_revision,
WatchCallback callback, WatchOptions options = {});
/// Process at most `limits.max_expirations_per_turn` logically
/// expired local leases, advancing revision and notifying watches.
std::size_t reap_expired();
/// Remove local entries, stop watch admission, and join admitted
/// callbacks. Destruction alone only requests stop.
[[nodiscard]] Result<void> shutdown_and_join() noexcept;
[[nodiscard]] std::uint64_t revision() const noexcept;
[[nodiscard]] std::uint64_t provider_generation() const noexcept;
[[nodiscard]] std::size_t active_record_count() const noexcept;
[[nodiscard]] std::size_t active_watch_count() const noexcept;
[[nodiscard]] std::size_t shared_watch_event_bytes() const noexcept;
private:
friend class Registration;
friend class WatchHandle;
struct State;
std::shared_ptr<State> m_state;
};
/// Explicit, thread-free lease renewal helper driven by injected steady time.
class ManagedLeaseRenewer final
{
public:
ManagedLeaseRenewer(
Registration& registration,
std::chrono::milliseconds renew_interval =
std::chrono::seconds{10},
const Void::Time::MonotonicClock* clock =
&Void::Time::SystemMonotonicClock::instance()) noexcept;
[[nodiscard]] bool due() const noexcept;
[[nodiscard]] Result<bool> tick();
[[nodiscard]] std::size_t consecutive_failures() const noexcept
{
return m_consecutive_failures;
}
private:
Registration* m_registration{nullptr};
std::chrono::milliseconds m_interval{std::chrono::seconds{10}};
const Void::Time::MonotonicClock* m_clock{
&Void::Time::SystemMonotonicClock::instance()};
Void::Time::MonotonicClock::time_point m_next_renew{};
std::size_t m_consecutive_failures{0};
};
/// Deterministic client-side smooth weighted round-robin selector over an
/// immutable Snapshot.
class WeightedRoundRobinSelector final
{
public:
WeightedRoundRobinSelector() = default;
[[nodiscard]] Result<EndpointRecord>
select(const Snapshot& snapshot);
void reset() noexcept;
private:
mutable std::mutex m_mu{};
std::map<std::string, std::int64_t, std::less<>> m_current_weights{};
};
/// Deterministic client-side affinity selector using weighted Rendezvous
/// (HRW) hashing over `Void::Hash::fnv1a64`.
class AffinitySelector final
{
public:
[[nodiscard]] static Result<EndpointRecord>
select(const Snapshot& snapshot, std::string_view affinity_key);
};
} // namespace Void::Discovery
+245
View File
@@ -0,0 +1,245 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Discovery
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class DiscoveryErrorCode : std::int32_t {
None = 0,
InvalidArgument = 1,
NotFound = 2,
Conflict = 3,
LimitExceeded = 4,
Expired = 5,
Unavailable = 6,
Stale = 7,
Cancelled = 8,
SelfJoin = 9,
Closed = 10,
TlsIdentityMismatch = 11,
};
[[nodiscard]] inline Error make_discovery_error(DiscoveryErrorCode code,
std::string message)
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case DiscoveryErrorCode::None:
kind = ErrorKind::internal;
break;
case DiscoveryErrorCode::InvalidArgument:
case DiscoveryErrorCode::TlsIdentityMismatch:
kind = ErrorKind::invalid_argument;
break;
case DiscoveryErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case DiscoveryErrorCode::Conflict:
case DiscoveryErrorCode::Expired:
case DiscoveryErrorCode::SelfJoin:
kind = ErrorKind::conflict;
break;
case DiscoveryErrorCode::LimitExceeded:
kind = ErrorKind::exhausted;
break;
case DiscoveryErrorCode::Unavailable:
case DiscoveryErrorCode::Stale:
kind = ErrorKind::overloaded;
break;
case DiscoveryErrorCode::Cancelled:
case DiscoveryErrorCode::Closed:
kind = ErrorKind::cancelled;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kDiscoveryErrorDomain,
static_cast<std::int32_t>(code)}};
}
enum class Freshness : std::uint8_t {
Fresh = 0,
Stale = 1,
Unavailable = 2,
};
struct EndpointAddress {
std::string scheme{"http"};
std::string host{};
std::uint16_t port{0};
/// Configured peer identity retained across IP/address refreshes
/// so DNS/address updates cannot downgrade TLS expected-name checks.
std::string expected_tls_name{};
[[nodiscard]] std::string_view effective_tls_name() const noexcept
{
return expected_tls_name.empty()
? std::string_view{host}
: std::string_view{expected_tls_name};
}
[[nodiscard]] std::string to_origin_url() const
{
return scheme + "://" + host + ":" + std::to_string(port);
}
[[nodiscard]] auto
operator<=>(const EndpointAddress&) const noexcept = default;
};
struct EndpointRecord {
std::string instance{};
std::string service{};
EndpointAddress endpoint{};
std::uint32_t weight{1};
bool ready{true};
std::map<std::string, std::string, std::less<>> attributes{};
[[nodiscard]] bool
operator==(const EndpointRecord&) const noexcept = default;
};
struct Snapshot {
std::uint64_t provider_generation{1};
std::uint64_t revision{0};
std::vector<EndpointRecord> records{};
Freshness freshness{Freshness::Fresh};
std::optional<Error> provider_error{};
};
struct ResolvePolicy {
bool allow_stale{false};
bool include_unready{false};
};
struct LeasePolicy {
bool leased{false};
std::chrono::milliseconds ttl{std::chrono::seconds{30}};
std::chrono::milliseconds renew_interval{std::chrono::seconds{10}};
[[nodiscard]] static constexpr LeasePolicy unleased() noexcept
{
return LeasePolicy{
.leased = false,
.ttl = std::chrono::seconds{30},
.renew_interval = std::chrono::seconds{10},
};
}
[[nodiscard]] static constexpr LeasePolicy with_ttl(
std::chrono::milliseconds lease_ttl,
std::chrono::milliseconds renewal =
std::chrono::seconds{10}) noexcept
{
return LeasePolicy{
.leased = true,
.ttl = lease_ttl,
.renew_interval = renewal,
};
}
};
struct CatalogLimits {
std::size_t max_services{1024};
std::size_t max_endpoints_per_service{256};
std::size_t max_total_records{10000};
std::size_t max_attributes_per_record{16};
std::size_t max_metadata_bytes_per_record{4096};
std::size_t max_watches{1024};
std::size_t max_events_per_watch{64};
std::size_t max_shared_event_bytes{16ULL * 1024 * 1024};
std::size_t max_expirations_per_turn{256};
};
enum class WatchEventKind : std::uint8_t {
InitialSnapshot = 0,
Delta = 1,
ResyncRequired = 2,
};
struct WatchEvent {
WatchEventKind kind{WatchEventKind::InitialSnapshot};
std::string service{};
std::uint64_t provider_generation{1};
std::uint64_t revision{0};
std::optional<Snapshot> snapshot{};
std::vector<EndpointRecord> added{};
std::vector<EndpointRecord> updated{};
std::vector<std::string> removed_instances{};
};
using WatchCallback = std::function<void(WatchEvent)>;
enum class WatchDispatchMode : std::uint8_t {
/// Deliver outside catalog locks immediately on admission/mutation.
Inline = 0,
/// Queue events for explicit `WatchHandle::deliver_one()`/`deliver_all()`.
Manual = 1,
/// Serialize delivery on an injected `Void::Async::Executor`.
Executor = 2,
};
struct WatchOptions {
WatchDispatchMode dispatch_mode{WatchDispatchMode::Inline};
Void::Async::Executor* executor{nullptr};
std::size_t max_queued_events{0}; // 0 => CatalogLimits::max_events_per_watch
};
enum class ObservationKind : std::uint8_t {
Resolve = 0,
Register = 1,
Renew = 2,
Release = 3,
Expire = 4,
ReplaceStatic = 5,
WatchResync = 6,
};
/// Bounded low-cardinality observation event (never includes arbitrary
/// per-instance metric labels).
struct ObservationEvent {
ObservationKind kind{ObservationKind::Resolve};
bool ok{true};
std::size_t count{0};
};
using ObservationHook = std::function<void(const ObservationEvent&)>;
struct CatalogOptions {
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
CatalogLimits limits{};
ObservationHook observer{};
};
[[nodiscard]] Result<void>
validate_endpoint_record(const EndpointRecord& record,
const CatalogLimits& limits = {});
[[nodiscard]] std::size_t
estimate_record_bytes(const EndpointRecord& record) noexcept;
[[nodiscard]] std::size_t
estimate_watch_event_bytes(const WatchEvent& event) noexcept;
} // namespace Void::Discovery
@@ -0,0 +1,73 @@
#pragma once
#include <Void/Discovery/Catalog.hpp>
#include <Void/RPC/Rpc.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
namespace Void::DiscoveryRpc
{
struct EndpointResolverOptions {
std::string service{};
/// Optional pinned TLS peer identity. When set, any refreshed
/// endpoint whose effective TLS name differs or attempts to
/// downgrade from `https` is rejected with `TlsIdentityMismatch`.
std::string expected_tls_name{};
bool require_tls{false};
Void::Discovery::ResolvePolicy resolve_policy{};
Void::Net::HttpClientOptions http_options{
.verify_tls = true,
};
Void::RPC::RpcLimits rpc_limits{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
std::size_t max_outstanding_ops{128};
std::chrono::milliseconds total_deadline{std::chrono::seconds{5}};
};
struct SelectedEndpoint {
Void::Discovery::EndpointRecord record{};
std::string origin_url{};
std::string effective_tls_name{};
};
/// Optional RPC endpoint adapter living strictly above `Discovery` and
/// `RPC` (preserving `RPC`'s independence from `Discovery`).
class EndpointResolverClient final
{
public:
EndpointResolverClient(const Void::Discovery::Catalog& catalog,
EndpointResolverOptions options);
[[nodiscard]] Void::Discovery::Result<SelectedEndpoint>
select_endpoint(
std::optional<std::string_view> affinity_key = std::nullopt);
[[nodiscard]] Void::Result::Result<Void::RPC::OwnedBytes>
call(Void::RPC::MethodId method,
Void::RPC::OwnedBytes payload,
Void::RPC::CallOptions options = {},
std::optional<std::string_view> affinity_key =
std::nullopt);
[[nodiscard]] std::size_t outstanding_ops() const noexcept
{
return m_outstanding.load(std::memory_order_acquire);
}
private:
const Void::Discovery::Catalog* m_catalog{nullptr};
EndpointResolverOptions m_options{};
Void::Discovery::WeightedRoundRobinSelector m_rr{};
std::atomic<std::size_t> m_outstanding{0};
};
} // namespace Void::DiscoveryRpc
+7
View File
@@ -75,6 +75,13 @@ namespace Void::Result
inline constexpr std::uint32_t kPluginErrorDomain = 23;
inline constexpr std::uint32_t kConfigurationErrorDomain = 24;
inline constexpr std::uint32_t kFsmErrorDomain = 25;
inline constexpr std::uint32_t kNetErrorDomain = 26;
inline constexpr std::uint32_t kTestingMockErrorDomain = 27;
inline constexpr std::uint32_t kShortUrlErrorDomain = 28;
inline constexpr std::uint32_t kRpcErrorDomain = 29;
inline constexpr std::uint32_t kDiscoveryErrorDomain = 30;
inline constexpr std::uint32_t kSchedulerErrorDomain = 31;
inline constexpr std::uint32_t kMessagingErrorDomain = 32;
struct ErrorCode {
std::uint32_t domain{kGenericErrorDomain};
+180
View File
@@ -0,0 +1,180 @@
#pragma once
#include <Void/Messaging/Types.hpp>
#include <chrono>
#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Messaging
{
/// Abstract queue interface implemented by both explicitly nondurable
/// `InMemoryQueue` and durable `MessagingStorage::StorageQueue`.
class Queue
{
public:
virtual ~Queue() = default;
[[nodiscard]] virtual Result<void>
create_queue(QueueConfig config) = 0;
[[nodiscard]] virtual Result<void>
create_group(std::string_view queue, GroupConfig config) = 0;
[[nodiscard]] virtual Result<PublishReceipt> publish(
std::string_view queue, Message message,
PublishDurability durability,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<std::optional<Delivery>>
try_receive(std::string_view queue, std::string_view group) = 0;
[[nodiscard]] virtual Result<Delivery> receive(
std::string_view queue, std::string_view group,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<void>
ack(const Receipt& receipt,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<void> nack(
const Receipt& receipt,
std::optional<std::chrono::milliseconds> delay = std::nullopt,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<Void::Time::MonotonicClock::time_point>
extend_visibility(
const Receipt& receipt, std::chrono::milliseconds extension,
Void::Async::OperationOptions options = {}) = 0;
/// Quarantine an unparseable or schema-incompatible message into
/// DLQ without falsely acknowledging it as processed.
[[nodiscard]] virtual Result<void> quarantine_corrupt(
const Receipt& receipt, std::string reason,
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<DeliveryState>
query_receipt(const Receipt& receipt) const = 0;
[[nodiscard]] virtual Result<std::vector<DeadLetterEntry>>
list_dead_letters(std::string_view queue,
std::string_view group,
std::size_t limit = 100) const = 0;
[[nodiscard]] virtual std::size_t
stuck_dlq_count(std::string_view queue,
std::string_view group) const noexcept = 0;
/// Reclaim expired `InFlight` deliveries into `Pending` (with retry
/// backoff) or atomically move exhausted messages to DLQ.
[[nodiscard]] virtual Result<std::size_t>
reap_expired_visibility() = 0;
/// Apply configured retention policy (paused when civil clock
/// health is degraded).
[[nodiscard]] virtual Result<std::size_t> expire_retention() = 0;
virtual void set_clock_healthy(bool healthy) noexcept = 0;
[[nodiscard]] virtual Result<ShutdownReport> close_and_join(
Void::Async::OperationOptions options = {}) = 0;
[[nodiscard]] virtual Result<QueueStats> stats() const = 0;
};
struct InMemoryQueueOptions {
QueueLimits limits{};
const Void::Time::MonotonicClock* monotonic_clock{
&Void::Time::SystemMonotonicClock::instance()};
const Void::Time::CivilClock* civil_clock{
&Void::Time::SystemCivilClock::instance()};
RandomU64Fn rng{};
};
/// Explicitly nondurable in-process queue implementing the full native
/// delivery state machine (`PublishDurability::Durable` is rejected with
/// `UnsupportedDurability`).
class InMemoryQueue final : public Queue
{
public:
explicit InMemoryQueue(InMemoryQueueOptions options = {});
~InMemoryQueue() noexcept override;
InMemoryQueue(InMemoryQueue&&) noexcept;
InMemoryQueue& operator=(InMemoryQueue&&) noexcept;
InMemoryQueue(const InMemoryQueue&) = delete;
InMemoryQueue& operator=(const InMemoryQueue&) = delete;
[[nodiscard]] Result<void> create_queue(QueueConfig config) override;
[[nodiscard]] Result<void>
create_group(std::string_view queue,
GroupConfig config) override;
[[nodiscard]] Result<PublishReceipt> publish(
std::string_view queue, Message message,
PublishDurability durability,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<std::optional<Delivery>>
try_receive(std::string_view queue,
std::string_view group) override;
[[nodiscard]] Result<Delivery> receive(
std::string_view queue, std::string_view group,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<void>
ack(const Receipt& receipt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<void> nack(
const Receipt& receipt,
std::optional<std::chrono::milliseconds> delay = std::nullopt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<Void::Time::MonotonicClock::time_point>
extend_visibility(
const Receipt& receipt, std::chrono::milliseconds extension,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<void> quarantine_corrupt(
const Receipt& receipt, std::string reason,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<DeliveryState>
query_receipt(const Receipt& receipt) const override;
[[nodiscard]] Result<std::vector<DeadLetterEntry>>
list_dead_letters(std::string_view queue,
std::string_view group,
std::size_t limit = 100) const override;
[[nodiscard]] std::size_t
stuck_dlq_count(std::string_view queue,
std::string_view group) const noexcept override;
[[nodiscard]] Result<std::size_t>
reap_expired_visibility() override;
[[nodiscard]] Result<std::size_t> expire_retention() override;
void set_clock_healthy(bool healthy) noexcept override;
[[nodiscard]] Result<ShutdownReport> close_and_join(
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Result<QueueStats> stats() const override;
private:
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::Messaging
+260
View File
@@ -0,0 +1,260 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Messaging
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class MessagingErrorCode : std::int32_t {
None = 0,
InvalidArgument = 1,
NotFound = 2,
Conflict = 3,
StaleReceipt = 4,
Overloaded = 5,
QuotaExceeded = 6,
IdempotencyCapacityExceeded = 7,
DlqFull = 8,
UnsupportedDurability = 9,
CorruptPayload = 10,
PersistenceError = 11,
UnknownOutcome = 12,
Cancelled = 13,
Timeout = 14,
Closed = 15,
};
[[nodiscard]] inline Error make_messaging_error(MessagingErrorCode code,
std::string message)
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case MessagingErrorCode::None:
kind = ErrorKind::internal;
break;
case MessagingErrorCode::InvalidArgument:
kind = ErrorKind::invalid_argument;
break;
case MessagingErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case MessagingErrorCode::Conflict:
case MessagingErrorCode::StaleReceipt:
case MessagingErrorCode::UnknownOutcome:
kind = ErrorKind::conflict;
break;
case MessagingErrorCode::Overloaded:
kind = ErrorKind::overloaded;
break;
case MessagingErrorCode::QuotaExceeded:
case MessagingErrorCode::IdempotencyCapacityExceeded:
case MessagingErrorCode::DlqFull:
kind = ErrorKind::exhausted;
break;
case MessagingErrorCode::UnsupportedDurability:
kind = ErrorKind::unsupported;
break;
case MessagingErrorCode::CorruptPayload:
kind = ErrorKind::corrupt;
break;
case MessagingErrorCode::PersistenceError:
kind = ErrorKind::io;
break;
case MessagingErrorCode::Cancelled:
case MessagingErrorCode::Closed:
kind = ErrorKind::cancelled;
break;
case MessagingErrorCode::Timeout:
kind = ErrorKind::timeout;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kMessagingErrorDomain,
static_cast<std::int32_t>(code)}};
}
/// Explicit publish durability contract. Nondurable queues must reject
/// `PublishDurability::Durable` rather than returning a false durable OK.
enum class PublishDurability : std::uint8_t {
Memory = 0,
Durable = 1,
};
enum class ConsumerMode : std::uint8_t {
Competing = 0,
SingleActive = 1,
};
enum class RetentionPolicy : std::uint8_t {
/// Initial default: block further publish at quota rather than silently
/// expiring unread work.
BlockAtQuota = 0,
/// Explicit opt-in lossy mode allowing retention expiry of unread work.
DropOldestLossy = 1,
};
enum class DeliveryState : std::uint8_t {
Pending = 0,
InFlight = 1,
Acked = 2,
DeadLetter = 3,
};
struct Message {
std::string id{};
std::vector<std::byte> payload{};
std::map<std::string, std::string, std::less<>> headers{};
std::uint32_t schema_version{1};
[[nodiscard]] bool
operator==(const Message&) const noexcept = default;
};
struct Receipt {
std::string queue{};
std::string group{};
std::string message_id{};
std::uint64_t sequence{0};
std::uint64_t generation{0};
[[nodiscard]] auto
operator<=>(const Receipt&) const noexcept = default;
};
struct PublishReceipt {
std::string queue{};
std::string message_id{};
std::uint64_t sequence{0};
PublishDurability durability{PublishDurability::Memory};
bool deduplicated{false};
};
struct Delivery {
Message message{};
Receipt receipt{};
std::uint32_t attempt{1};
Void::Time::MonotonicClock::time_point visibility_deadline{};
};
struct DeadLetterEntry {
Message message{};
std::string queue{};
std::string group{};
std::uint64_t sequence{0};
std::uint32_t attempts{0};
std::string reason{};
std::int64_t dead_lettered_utc_ms{0};
};
struct RetryPolicy {
std::uint32_t max_attempts{5};
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
std::chrono::milliseconds max_delay{std::chrono::seconds{60}};
};
struct QueueLimits {
std::size_t max_message_bytes{768ULL * 1024};
std::size_t max_headers_bytes{8ULL * 1024};
std::size_t max_header_count{32};
std::size_t max_queues{1024};
std::size_t max_groups_per_queue{32};
std::size_t max_in_flight_per_group{64};
std::size_t max_waiting_receives{1024};
std::size_t max_transient_payload_bytes{64ULL * 1024 * 1024};
std::uint64_t persistent_quota_bytes{1024ULL * 1024 * 1024};
std::size_t max_dlq_messages{10000};
std::chrono::milliseconds idempotency_retention{
std::chrono::hours{24}};
std::size_t max_idempotency_entries{100000};
std::chrono::milliseconds default_visibility_timeout{
std::chrono::seconds{30}};
std::chrono::milliseconds max_visibility_extension{
std::chrono::minutes{5}};
std::chrono::milliseconds logical_retention{
std::chrono::hours{24 * 7}};
std::chrono::milliseconds shutdown_drain_timeout{
std::chrono::seconds{10}};
};
struct QueueConfig {
std::string name{};
RetentionPolicy retention_policy{RetentionPolicy::BlockAtQuota};
RetryPolicy retry{};
};
struct GroupConfig {
std::string name{};
ConsumerMode mode{ConsumerMode::Competing};
std::chrono::milliseconds visibility_timeout{
std::chrono::seconds{30}};
std::size_t max_in_flight{64};
};
struct QueueStats {
std::size_t queues{0};
std::size_t pending{0};
std::size_t in_flight{0};
std::size_t acked{0};
std::size_t dead_letter{0};
std::size_t stuck_dlq{0};
std::uint64_t retained_bytes{0};
std::size_t idempotency_entries{0};
};
struct ShutdownReport {
bool complete{true};
std::size_t remaining_in_flight{0};
};
using RandomU64Fn = std::function<std::uint64_t()>;
[[nodiscard]] Result<void>
validate_identifier(std::string_view name, std::string_view label);
[[nodiscard]] Result<void> validate_message(const Message& message,
const QueueLimits& limits);
[[nodiscard]] std::size_t
estimate_message_bytes(const Message& message) noexcept;
[[nodiscard]] std::int64_t
compute_retry_backoff_ms(const RetryPolicy& retry,
std::uint32_t attempt,
const RandomU64Fn& rng);
[[nodiscard]] inline std::int64_t
to_mono_ns(Void::Time::MonotonicClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
tp.time_since_epoch())
.count();
}
[[nodiscard]] inline std::int64_t
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch())
.count();
}
} // namespace Void::Messaging
+89
View File
@@ -0,0 +1,89 @@
#pragma once
#include <Void/Messaging/Queue.hpp>
#include <Void/RPC/Rpc.hpp>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::MessagingRpc
{
inline constexpr std::uint64_t kMessagingRpcServiceId = 0x564D534752504301ULL;
inline constexpr Void::RPC::MethodId kPublishMethod{
kMessagingRpcServiceId, 1U};
inline constexpr Void::RPC::MethodId kTryReceiveMethod{
kMessagingRpcServiceId, 2U};
inline constexpr Void::RPC::MethodId kAckMethod{
kMessagingRpcServiceId, 3U};
inline constexpr Void::RPC::MethodId kNackMethod{
kMessagingRpcServiceId, 4U};
inline constexpr Void::RPC::MethodId kQueryReceiptMethod{
kMessagingRpcServiceId, 5U};
/// Mounts remote Messaging operations (`publish`, `try_receive`, `ack`,
/// `nack`, `query_receipt`) onto a `Void::RPC::Server`.
class RpcQueueServer final
{
public:
RpcQueueServer() = default;
~RpcQueueServer() noexcept;
RpcQueueServer(RpcQueueServer&&) noexcept = default;
RpcQueueServer& operator=(RpcQueueServer&&) noexcept = default;
RpcQueueServer(const RpcQueueServer&) = delete;
RpcQueueServer& operator=(const RpcQueueServer&) = delete;
[[nodiscard]] Void::Messaging::Result<void>
mount(Void::RPC::Server& server,
Void::Messaging::Queue& queue);
void unmount_and_drain() noexcept;
private:
std::vector<Void::RPC::Registration> m_registrations{};
};
/// Remote client executing Messaging operations over unary `Void::RPC::Client`,
/// propagating `UnknownOutcome` faithfully when network replies are lost.
class RpcQueueClient final
{
public:
explicit RpcQueueClient(Void::RPC::ClientOptions options);
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
publish(std::string_view queue,
const Void::Messaging::Message& message,
Void::Messaging::PublishDurability durability,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<
std::optional<Void::Messaging::Delivery>>
try_receive(std::string_view queue, std::string_view group,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<void>
ack(const Void::Messaging::Receipt& receipt,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<void>
nack(const Void::Messaging::Receipt& receipt,
std::optional<std::chrono::milliseconds> delay =
std::nullopt,
const Void::RPC::CallOptions& options = {});
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
query_receipt(const Void::Messaging::Receipt& receipt,
const Void::RPC::CallOptions& options = {});
private:
Void::RPC::Client m_client;
};
} // namespace Void::MessagingRpc
@@ -0,0 +1,260 @@
#pragma once
#include <Void/Messaging/Queue.hpp>
#include <Void/Storage/Batch.hpp>
#include <Void/Storage/Engine.hpp>
#include <cstring>
#include <string>
#include <string_view>
#include <vector>
namespace Void::MessagingStorage
{
struct OutboxRecord {
std::string outbox_id{};
std::string target_queue{};
Void::Messaging::Message message{};
};
/// Atomic local-batch helpers for the Outbox and Inbox patterns over a
/// single shared `Void::Storage::Engine`.
///
/// Boundary guarantee:
/// - Business state + outbox insert (or consumer state + inbox dedup key)
/// commit atomically ONLY within the same `Void::Storage::Batch`.
/// - External effects (email, HTTP/RPC calls, separate databases) remain
/// strictly outside this batch boundary and still require downstream
/// idempotency or compensation.
class OutboxInbox final
{
public:
static void append_outbox_in_batch(
Void::Storage::Batch& batch, const OutboxRecord& record,
std::string_view prefix = "outbox:v1:")
{
const std::string key =
std::string{prefix} + record.outbox_id;
batch.require_absent(key);
batch.put(key, encode_outbox(record));
}
/// Record inbox deduplication key inside the consumer's SAME
/// `Void::Storage::Batch` as its local business mutation. If the
/// message was already applied, the batch fails with `Conflict`
/// (duplicate prevented atomically).
static void apply_inbox_in_batch(
Void::Storage::Batch& batch, std::string_view consumer_id,
std::string_view message_id,
std::string_view prefix = "inbox:v1:")
{
const std::string key = std::string{prefix} +
std::string{consumer_id} + "\x1F" +
std::string{message_id};
batch.require_absent(key);
batch.put(key, "1");
}
/// Relay pending outbox entries to `queue` using stable
/// `Message::id` (idempotent on retry) and delete confirmed entries.
[[nodiscard]] static Void::Messaging::Result<std::size_t>
relay_outbox(Void::Storage::Engine& engine,
Void::Messaging::Queue& queue,
std::string_view prefix = "outbox:v1:",
std::size_t max_entries = 64)
{
auto snap = engine.snapshot();
if (!snap.has_value()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::PersistenceError,
snap.error().message()));
}
auto cur = engine.scan(
std::move(*snap),
Void::Storage::ScanBounds::prefix(prefix));
if (!cur.has_value()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::PersistenceError,
cur.error().message()));
}
std::size_t relayed = 0;
for (;;) {
auto page = cur->next_page();
if (!page.has_value()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
PersistenceError,
page.error().message()));
}
for (const auto& entry : page->entries) {
if (relayed >= max_entries) {
return relayed;
}
auto decoded = decode_outbox(
Void::Storage::to_string_view(entry.value));
if (!decoded.has_value()) {
return Void::Result::fail(decoded.error());
}
auto pub = queue.publish(
decoded->target_queue, decoded->message,
Void::Messaging::PublishDurability::Durable);
if (!pub.has_value()) {
return Void::Result::fail(pub.error());
}
Void::Storage::Batch erase_b{};
erase_b.require_version(entry.key, entry.version);
erase_b.erase(entry.key);
auto wr = engine.write(std::move(erase_b),
Void::Storage::Durability::Sync);
if (!wr.has_value()) {
if (wr.error().outcome ==
Void::Storage::Outcome::Unknown) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
UnknownOutcome,
"Outbox relay delete outcome unknown"));
}
if (wr.error().cause.code !=
Void::Storage::StorageErrorCode::conflict) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
PersistenceError,
wr.error().cause.error.message()));
}
}
++relayed;
}
if (!page->has_more) {
break;
}
}
return relayed;
}
private:
static void append_u32(std::string& out, std::uint32_t v)
{
out.push_back(static_cast<char>((v >> 24U) & 0xFFU));
out.push_back(static_cast<char>((v >> 16U) & 0xFFU));
out.push_back(static_cast<char>((v >> 8U) & 0xFFU));
out.push_back(static_cast<char>(v & 0xFFU));
}
static void append_str(std::string& out, std::string_view s)
{
append_u32(out, static_cast<std::uint32_t>(s.size()));
out.append(s);
}
[[nodiscard]] static bool read_u32(std::string_view& in,
std::uint32_t& out) noexcept
{
if (in.size() < 4U) return false;
out = (static_cast<std::uint32_t>(
static_cast<unsigned char>(in[0]))
<< 24U) |
(static_cast<std::uint32_t>(
static_cast<unsigned char>(in[1]))
<< 16U) |
(static_cast<std::uint32_t>(
static_cast<unsigned char>(in[2]))
<< 8U) |
static_cast<std::uint32_t>(
static_cast<unsigned char>(in[3]));
in.remove_prefix(4U);
return true;
}
[[nodiscard]] static bool read_str(std::string_view& in,
std::string& out)
{
std::uint32_t len = 0;
if (!read_u32(in, len) || len > in.size()) return false;
out.assign(in.data(), len);
in.remove_prefix(len);
return true;
}
[[nodiscard]] static std::string
encode_outbox(const OutboxRecord& r)
{
std::string out;
append_u32(out, 1U);
append_str(out, r.outbox_id);
append_str(out, r.target_queue);
append_str(out, r.message.id);
append_u32(out, r.message.schema_version);
append_u32(out,
static_cast<std::uint32_t>(r.message.payload.size()));
if (!r.message.payload.empty()) {
out.append(
reinterpret_cast<const char*>(r.message.payload.data()),
r.message.payload.size());
}
append_u32(
out, static_cast<std::uint32_t>(r.message.headers.size()));
for (const auto& [k, v] : r.message.headers) {
append_str(out, k);
append_str(out, v);
}
return out;
}
[[nodiscard]] static Void::Messaging::Result<OutboxRecord>
decode_outbox(std::string_view raw)
{
std::uint32_t ver = 0;
if (!read_u32(raw, ver) || ver != 1U) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::CorruptPayload,
"Outbox: unsupported schema version"));
}
OutboxRecord r{};
std::uint32_t plen = 0;
std::uint32_t hcount = 0;
if (!read_str(raw, r.outbox_id) ||
!read_str(raw, r.target_queue) ||
!read_str(raw, r.message.id) ||
!read_u32(raw, r.message.schema_version) ||
!read_u32(raw, plen) || plen > raw.size()) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::CorruptPayload,
"Outbox: truncated payload"));
}
r.message.payload.resize(plen);
if (plen > 0U) {
std::memcpy(r.message.payload.data(), raw.data(), plen);
raw.remove_prefix(plen);
}
if (!read_u32(raw, hcount)) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::CorruptPayload,
"Outbox: truncated header count"));
}
for (std::uint32_t i = 0; i < hcount; ++i) {
std::string k, v;
if (!read_str(raw, k) || !read_str(raw, v)) {
return Void::Result::fail(
Void::Messaging::make_messaging_error(
Void::Messaging::MessagingErrorCode::
CorruptPayload,
"Outbox: truncated header"));
}
r.message.headers.emplace(std::move(k), std::move(v));
}
return r;
}
};
} // namespace Void::MessagingStorage
@@ -0,0 +1,121 @@
#pragma once
#include <Void/Messaging/Queue.hpp>
#include <Void/Storage/Engine.hpp>
#include <memory>
#include <string>
namespace Void::MessagingStorage
{
struct StorageQueueOptions {
Void::Messaging::QueueLimits limits{};
std::string key_prefix{"msg:v1:"};
const Void::Time::MonotonicClock* monotonic_clock{
&Void::Time::SystemMonotonicClock::instance()};
const Void::Time::CivilClock* civil_clock{
&Void::Time::SystemCivilClock::instance()};
Void::Messaging::RandomU64Fn rng{};
};
/// Single-node durable `Void::Messaging::Queue` backed by
/// `Void::Storage::Engine` conditional batches (`Durability::Sync` for
/// `PublishDurability::Durable`).
///
/// Explicit at-least-once delivery:
/// - On open/restart, all prior `InFlight` records are promoted to
/// `Pending` with a bumped delivery generation so stale worker receipts
/// fail with `StaleReceipt` while preserving attempt counters.
/// - DLQ insertion and source delivery update execute in one atomic batch.
class StorageQueue final : public Void::Messaging::Queue
{
public:
[[nodiscard]] static Void::Messaging::Result<StorageQueue>
open(Void::Storage::Engine& engine,
StorageQueueOptions options = {});
~StorageQueue() noexcept override;
StorageQueue(StorageQueue&&) noexcept;
StorageQueue& operator=(StorageQueue&&) noexcept;
StorageQueue(const StorageQueue&) = delete;
StorageQueue& operator=(const StorageQueue&) = delete;
[[nodiscard]] Void::Messaging::Result<void>
create_queue(Void::Messaging::QueueConfig config) override;
[[nodiscard]] Void::Messaging::Result<void>
create_group(std::string_view queue,
Void::Messaging::GroupConfig config) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
publish(std::string_view queue, Void::Messaging::Message message,
Void::Messaging::PublishDurability durability,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<
std::optional<Void::Messaging::Delivery>>
try_receive(std::string_view queue,
std::string_view group) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::Delivery>
receive(std::string_view queue, std::string_view group,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<void>
ack(const Void::Messaging::Receipt& receipt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<void> nack(
const Void::Messaging::Receipt& receipt,
std::optional<std::chrono::milliseconds> delay = std::nullopt,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<
Void::Time::MonotonicClock::time_point>
extend_visibility(
const Void::Messaging::Receipt& receipt,
std::chrono::milliseconds extension,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<void> quarantine_corrupt(
const Void::Messaging::Receipt& receipt, std::string reason,
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
query_receipt(
const Void::Messaging::Receipt& receipt) const override;
[[nodiscard]] Void::Messaging::Result<
std::vector<Void::Messaging::DeadLetterEntry>>
list_dead_letters(std::string_view queue,
std::string_view group,
std::size_t limit = 100) const override;
[[nodiscard]] std::size_t
stuck_dlq_count(std::string_view queue,
std::string_view group) const noexcept override;
[[nodiscard]] Void::Messaging::Result<std::size_t>
reap_expired_visibility() override;
[[nodiscard]] Void::Messaging::Result<std::size_t>
expire_retention() override;
void set_clock_healthy(bool healthy) noexcept override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::ShutdownReport>
close_and_join(
Void::Async::OperationOptions options = {}) override;
[[nodiscard]] Void::Messaging::Result<Void::Messaging::QueueStats>
stats() const override;
private:
struct State;
explicit StorageQueue(std::shared_ptr<State> state) noexcept;
std::shared_ptr<State> m_state;
};
} // namespace Void::MessagingStorage
+182 -2
View File
@@ -4,13 +4,79 @@
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
namespace Void::Net
{
enum class NetErrorCode : std::int32_t {
none = 0,
invalid_url = 1,
invalid_argument = 2,
connect_failed = 3,
tls_error = 4,
protocol_error = 5,
timeout = 6,
cancelled = 7,
quota_exceeded = 8,
io_error = 9,
redirect_blocked = 10,
payload_too_large = 11,
headers_too_large = 12
};
[[nodiscard]] inline Void::Result::Error
make_net_error(NetErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case NetErrorCode::none:
kind = ErrorKind::internal;
break;
case NetErrorCode::invalid_url:
case NetErrorCode::invalid_argument:
case NetErrorCode::redirect_blocked:
kind = ErrorKind::invalid_argument;
break;
case NetErrorCode::connect_failed:
case NetErrorCode::io_error:
kind = ErrorKind::io;
break;
case NetErrorCode::tls_error:
case NetErrorCode::protocol_error:
kind = ErrorKind::corrupt;
break;
case NetErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case NetErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case NetErrorCode::quota_exceeded:
case NetErrorCode::payload_too_large:
case NetErrorCode::headers_too_large:
kind = ErrorKind::exhausted;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kNetErrorDomain,
static_cast<std::int32_t>(code)},
sys_err};
}
enum class Method { Get, Post, Put, Delete, Patch, Head, Options };
@@ -62,6 +128,54 @@ namespace Void::Net
}
};
struct HttpClientOptions {
ProxyConfig proxy{};
std::string user_agent{"Void.Net/1.0"};
bool verify_tls{true};
std::string ca_file{};
std::uint64_t max_body_size{64ULL * 1024 * 1024};
int max_redirects{0};
bool allow_insecure_redirects{false};
};
struct TransferProgress {
std::uint64_t bytes_transferred{0};
std::optional<std::uint64_t> total_bytes{};
};
struct DownloadOptions {
std::vector<Header> headers{};
std::chrono::seconds timeout{30};
std::uint64_t max_bytes{0};
std::stop_token stop{};
std::function<void(std::span<const std::byte>)> on_chunk{};
std::function<void(const TransferProgress&)> on_progress{};
};
struct DownloadResult {
std::uint16_t status{0};
std::vector<Header> headers{};
std::uint64_t bytes_written{0};
std::chrono::milliseconds elapsed{0};
[[nodiscard]] bool ok() const noexcept
{
return status >= 200 && status < 300;
}
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const;
};
struct UploadOptions {
Method method{Method::Put};
std::vector<Header> headers{};
std::string content_type{"application/octet-stream"};
std::chrono::seconds timeout{30};
std::uint64_t max_upload_bytes{0};
std::stop_token stop{};
std::function<void(const TransferProgress&)> on_progress{};
};
/// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL.
/// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS.
/// Generic: no application-specific defaults beyond a configurable
@@ -73,6 +187,12 @@ namespace Void::Net
HttpClient() = default;
explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {}
explicit HttpClient(HttpClientOptions options);
/// Preset with TLS peer & hostname certificate verification enabled
/// by default (`verify_tls = true`).
[[nodiscard]] static HttpClient
secure(ProxyConfig proxy = {});
void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); }
[[nodiscard]] const ProxyConfig& proxy() const noexcept
@@ -83,9 +203,33 @@ namespace Void::Net
/// Default User-Agent applied when a request sets none.
void set_user_agent(std::string ua) { m_user_agent = std::move(ua); }
/// Verify TLS peer certificates (default: false, matching common
/// scraping/proxy use; enable for security-sensitive callers).
/// Verify TLS peer certificates (default constructor keeps `false`
/// for 1.x compatibility; `HttpClient::secure()` defaults `true`).
void set_verify_tls(bool on) noexcept { m_verify_tls = on; }
[[nodiscard]] bool verify_tls() const noexcept
{
return m_verify_tls;
}
/// Optional custom PEM CA bundle/certificate file used when
/// `verify_tls` is enabled.
void set_ca_file(std::string ca_file)
{
m_ca_file = std::move(ca_file);
}
[[nodiscard]] const std::string& ca_file() const noexcept
{
return m_ca_file;
}
void set_allow_insecure_redirects(bool allow) noexcept
{
m_allow_insecure_redirects = allow;
}
[[nodiscard]] bool allow_insecure_redirects() const noexcept
{
return m_allow_insecure_redirects;
}
/// Maximum response body size in bytes. 0 means unlimited. Default
/// is 64 MiB (Beast's own default of ~1 MiB is too small for binary
@@ -100,12 +244,34 @@ namespace Void::Net
/// header). Opt-in so callers that inspect redirects keep working.
void set_max_redirects(int n) noexcept { m_max_redirects = n; }
/// Format request method, scrubbed URL, and headers for logs while
/// redacting `Authorization`, `Proxy-Authorization`, `Cookie`, and
/// `X-Api-Key`.
[[nodiscard]] static std::string
format_request_diagnostics(const Request& req);
/// Execute a request. A per-request `Request::proxy` is not modelled;
/// the client-level proxy applies. Returns an Error only on transport
/// failure — a non-2xx HTTP response is a successful Result.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
send(const Request& req) const;
/// Stream response body directly to `destination` without buffering
/// the full payload in memory, enforcing `options.max_bytes` and
/// `options.stop` cancellation.
[[nodiscard]] Void::Result::Result<DownloadResult,
Void::Result::Error>
download_to_file(std::string_view url,
const std::filesystem::path& destination,
const DownloadOptions& options = {}) const;
/// Stream a regular file directly as the HTTP request body without
/// buffering the full file in memory.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
upload_file(std::string_view url,
const std::filesystem::path& source_path,
const UploadOptions& options = {}) const;
// Convenience wrappers.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
get(std::string_view url,
@@ -113,14 +279,28 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post(std::string_view url, std::string body,
std::vector<Header> headers = {}) const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
put_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
private:
ProxyConfig m_proxy{};
std::string m_user_agent = "Void.Net/1.0";
bool m_verify_tls = false;
std::string m_ca_file{};
std::uint64_t m_max_body = 64ull * 1024 * 1024;
int m_max_redirects = 0;
bool m_allow_insecure_redirects = false;
};
} // namespace Void::Net
+172
View File
@@ -0,0 +1,172 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
struct HttpCodecLimits {
std::size_t max_start_line_bytes{8ULL * 1024};
std::size_t max_header_bytes{32ULL * 1024};
std::size_t max_headers{100};
std::uint64_t max_body_bytes{8ULL * 1024 * 1024};
std::size_t max_chunk_line_bytes{1024};
std::size_t max_trailer_bytes{8ULL * 1024};
std::size_t max_informational_responses{8};
};
enum class HttpParseStatus : std::uint8_t {
NeedMoreData,
Complete,
};
struct ParsedHttpRequest {
Method method{Method::Get};
std::string target{};
std::uint8_t version_major{1};
std::uint8_t version_minor{1};
std::vector<Header> headers{};
std::string body{};
std::vector<Header> trailers{};
bool keep_alive{true};
bool chunked{false};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
struct ParsedHttpResponse {
std::uint16_t status{200};
std::string reason{};
std::uint8_t version_major{1};
std::uint8_t version_minor{1};
std::vector<Header> headers{};
std::string body{};
std::vector<Header> trailers{};
std::vector<std::uint16_t> informational_statuses{};
bool keep_alive{true};
bool chunked{false};
bool close_delimited{false};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
/// Native incremental RFC 9110/9112 HTTP/1.1 request parser.
/// Enforces strict CRLF framing, header/body limits, and rejects
/// Transfer-Encoding + Content-Length smuggling ambiguity and conflicting
/// Content-Length values.
class HttpRequestParser
{
public:
explicit HttpRequestParser(HttpCodecLimits limits = {}) noexcept;
void reset() noexcept;
/// Feed arbitrary byte chunks. Returns Complete once a full message
/// has been parsed; `consumed` reports bytes consumed from `input`.
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::span<const std::byte> input, std::size_t& consumed);
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::string_view input, std::size_t& consumed);
[[nodiscard]] bool complete() const noexcept;
[[nodiscard]] bool connection_reusable() const noexcept;
[[nodiscard]] const ParsedHttpRequest& request() const noexcept;
[[nodiscard]] ParsedHttpRequest take_request();
private:
enum class Phase : std::uint8_t {
Headers,
FixedBody,
ChunkSize,
ChunkData,
ChunkDataCrlf,
Trailers,
Complete,
Failed,
};
HttpCodecLimits m_limits{};
Phase m_phase{Phase::Headers};
std::string m_buf{};
std::size_t m_header_bytes_seen{0};
std::size_t m_trailer_bytes_seen{0};
std::uint64_t m_remaining{0};
std::uint64_t m_body_received{0};
ParsedHttpRequest m_req{};
[[nodiscard]] Void::Result::Result<void> parse_header_block(
std::string_view block);
};
/// Native incremental RFC 9110/9112 HTTP/1.1 response parser.
/// Supports 1xx informational responses, HEAD/204/304 no-body responses,
/// fixed Content-Length, chunked transfer encoding with extensions and
/// trailers, and close-delimited bodies (completed via `finish_eof()`).
class HttpResponseParser
{
public:
explicit HttpResponseParser(
HttpCodecLimits limits = {},
Method request_method = Method::Get) noexcept;
void reset(Method request_method = Method::Get) noexcept;
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::span<const std::byte> input, std::size_t& consumed);
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::string_view input, std::size_t& consumed);
/// Signal peer EOF. Completes close-delimited responses cleanly;
/// errors on truncated fixed-length, chunked, or header frames.
[[nodiscard]] Void::Result::Result<void> finish_eof();
[[nodiscard]] bool complete() const noexcept;
[[nodiscard]] bool connection_reusable() const noexcept;
[[nodiscard]] const ParsedHttpResponse& response() const noexcept;
[[nodiscard]] ParsedHttpResponse take_response();
private:
enum class Phase : std::uint8_t {
Headers,
FixedBody,
ChunkSize,
ChunkData,
ChunkDataCrlf,
Trailers,
CloseDelimitedBody,
Complete,
Failed,
};
HttpCodecLimits m_limits{};
Method m_request_method{Method::Get};
Phase m_phase{Phase::Headers};
std::string m_buf{};
std::size_t m_header_bytes_seen{0};
std::size_t m_trailer_bytes_seen{0};
std::uint64_t m_remaining{0};
std::uint64_t m_body_received{0};
ParsedHttpResponse m_resp{};
[[nodiscard]] Void::Result::Result<bool> parse_header_block(
std::string_view block);
};
} // namespace Void::Net
+117
View File
@@ -0,0 +1,117 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <Void/Net/WebSocket.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
namespace Void::Net
{
struct HttpServerOptions {
std::string bind_host{"127.0.0.1"};
std::uint16_t port{0};
std::size_t max_header_bytes{64ULL * 1024};
std::size_t max_headers{128};
std::uint64_t max_body_bytes{16ULL * 1024 * 1024};
std::uint64_t max_streaming_body_bytes{512ULL * 1024 * 1024};
std::size_t max_concurrent_connections{64};
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
int listen_backlog{128};
};
/// Streaming request body reader passed to streaming HTTP route handlers.
class BodyReader
{
public:
struct State;
explicit BodyReader(State& state) noexcept : m_state(&state) {}
BodyReader(const BodyReader&) = delete;
BodyReader& operator=(const BodyReader&) = delete;
[[nodiscard]] std::optional<std::uint64_t>
content_length() const noexcept;
[[nodiscard]] bool is_chunked() const noexcept;
[[nodiscard]] std::uint64_t bytes_read() const noexcept;
/// Read up to dst.size() decoded body bytes. Returns 0 at EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read_some(std::span<std::byte> dst);
/// Stream the request body atomically to `destination`, enforcing
/// `max_bytes` (or server max_streaming_body_bytes when 0).
[[nodiscard]] Void::Result::Result<std::uint64_t>
read_to_file(const std::filesystem::path& destination,
std::uint64_t max_bytes = 0);
private:
State* m_state{nullptr};
};
using StreamingRouteHandler =
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
/// `Void::Net::Router` and streaming routes via `BodyReader`.
class HttpServer
{
public:
explicit HttpServer(HttpServerOptions options = {});
explicit HttpServer(Router& external_router,
HttpServerOptions options = {});
~HttpServer() noexcept;
HttpServer(HttpServer&&) noexcept;
HttpServer& operator=(HttpServer&&) noexcept;
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
[[nodiscard]] Router& router() noexcept;
[[nodiscard]] Void::Result::Result<void>
add_route(Method method, std::string pattern,
RouteHandler handler);
[[nodiscard]] Void::Result::Result<void>
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
/// `sessions` (caller must keep `sessions` alive until after
/// `shutdown()`).
[[nodiscard]] Void::Result::Result<void>
add_websocket_route(std::string pattern,
WebSocketSessions& sessions,
WebSocketUpgradeOptions options = {});
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
std::chrono::seconds{5}) noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::string bind_address() const;
[[nodiscard]] std::string base_url() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace Void::Net
+142
View File
@@ -0,0 +1,142 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace Void::Net
{
struct PoolLimits {
std::size_t max_total_connections{256};
std::size_t max_per_origin{8};
std::size_t max_idle_connections{128};
std::chrono::milliseconds idle_timeout{std::chrono::seconds{30}};
};
/// Pool partition key isolating origins, proxy identity, and TLS/trust
/// policy generations so connections never cross trust boundaries.
struct PoolKey {
std::string scheme{};
std::string host{};
std::uint16_t port{0};
std::string proxy_identity{};
std::uint64_t tls_policy_generation{0};
[[nodiscard]] auto
operator<=>(const PoolKey&) const noexcept = default;
};
/// Abstract pooled transport entry owned by ConnectionPool / leases.
class PooledConnection
{
public:
virtual ~PooledConnection() = default;
[[nodiscard]] virtual bool is_open() const noexcept = 0;
virtual void close() noexcept = 0;
};
using ConnectionFactory =
std::function<Void::Result::Result<std::unique_ptr<PooledConnection>>(
const PoolKey&)>;
struct PoolStats {
std::size_t total_connections{0};
std::size_t active_leases{0};
std::size_t idle_connections{0};
std::uint64_t total_acquires{0};
std::uint64_t idle_hits{0};
std::uint64_t idle_evictions{0};
std::uint64_t closed_dirty{0};
};
class ConnectionPool;
/// Move-only RAII lease for one HTTP/1.1 exchange. Only leases explicitly
/// marked reusable via `mark_reusable(true)` (after full body+trailers)
/// return to the idle pool on destruction; unmarked or dirty leases close.
class ConnectionLease final
{
public:
ConnectionLease() noexcept = default;
~ConnectionLease() noexcept;
ConnectionLease(ConnectionLease&& other) noexcept;
ConnectionLease& operator=(ConnectionLease&& other) noexcept;
ConnectionLease(const ConnectionLease&) = delete;
ConnectionLease& operator=(const ConnectionLease&) = delete;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool reused() const noexcept;
[[nodiscard]] const PoolKey& key() const noexcept;
[[nodiscard]] PooledConnection* get() const noexcept;
[[nodiscard]] PooledConnection& operator*() const noexcept;
[[nodiscard]] PooledConnection* operator->() const noexcept;
void mark_reusable(bool reusable = true) noexcept;
void release() noexcept;
private:
friend class ConnectionPool;
struct Impl;
std::shared_ptr<void> m_pool_state{};
PoolKey m_key{};
std::unique_ptr<PooledConnection> m_conn{};
bool m_reused{false};
bool m_reusable{false};
bool m_active{false};
};
/// Bounded HTTP/1.1 connection pool keyed by origin, proxy identity, and
/// TLS policy generation, with deterministic clock-driven idle eviction.
class ConnectionPool final
{
public:
explicit ConnectionPool(
PoolLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~ConnectionPool() noexcept;
ConnectionPool(ConnectionPool&&) noexcept;
ConnectionPool& operator=(ConnectionPool&&) noexcept;
ConnectionPool(const ConnectionPool&) = delete;
ConnectionPool& operator=(const ConnectionPool&) = delete;
/// Acquire an idle connection for `key` or invoke `factory(key)`
/// outside pool locks while enforcing total and per-origin limits.
[[nodiscard]] Void::Result::Result<ConnectionLease>
acquire(const PoolKey& key, const ConnectionFactory& factory);
/// Evict all idle connections older than `idle_timeout` or closed.
std::size_t evict_expired();
/// Close all idle connections (e.g. on trust-store rotation).
std::size_t clear_idle();
/// Prevent new leases and close all currently idle connections.
void shutdown() noexcept;
[[nodiscard]] PoolStats stats() const;
private:
friend class ConnectionLease;
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::Net
+72 -2
View File
@@ -30,6 +30,7 @@ namespace Void::Net
std::vector<Header> headers;
std::string body;
RouteParameters parameters;
std::string query{};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
@@ -39,6 +40,12 @@ namespace Void::Net
std::uint16_t status{200};
std::vector<Header> headers;
std::string body;
std::optional<std::filesystem::path> file_body{};
[[nodiscard]] static ServerResponse
from_file(std::filesystem::path path,
std::string content_type = {},
std::uint16_t status = 200);
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
@@ -67,6 +74,9 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
dispatch(ServerRequest request) const;
[[nodiscard]] std::vector<Method>
allowed_methods(std::string_view path) const;
[[nodiscard]] std::size_t size() const;
private:
@@ -88,6 +98,49 @@ namespace Void::Net
std::uintmax_t size{};
};
/// Move-only RAII handle for a regular file opened beneath a pinned root
/// directory descriptor using `openat(..., O_NOFOLLOW)` (zero TOCTOU).
class OpenedStaticFile final
{
public:
OpenedStaticFile() noexcept = default;
OpenedStaticFile(int fd, std::filesystem::path relative_path,
std::string_view content_type,
std::uint64_t size) noexcept;
~OpenedStaticFile() noexcept;
OpenedStaticFile(OpenedStaticFile&& other) noexcept;
OpenedStaticFile& operator=(OpenedStaticFile&& other) noexcept;
OpenedStaticFile(const OpenedStaticFile&) = delete;
OpenedStaticFile& operator=(const OpenedStaticFile&) = delete;
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
[[nodiscard]] int native_handle() const noexcept { return fd_; }
[[nodiscard]] const std::filesystem::path&
relative_path() const noexcept
{
return relative_path_;
}
[[nodiscard]] std::string_view content_type() const noexcept
{
return content_type_;
}
[[nodiscard]] std::uint64_t size() const noexcept { return size_; }
[[nodiscard]] Void::Result::Result<std::string>
read_all(std::uint64_t max_bytes = 64ULL * 1024 * 1024) const;
void close() noexcept;
private:
int fd_{-1};
std::filesystem::path relative_path_{};
std::string_view content_type_{};
std::uint64_t size_{0};
};
[[nodiscard]] std::string_view
content_type_for(const std::filesystem::path& path);
@@ -105,6 +158,12 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<StaticFile>>
resolve(std::string_view request_path) const;
/// Descriptor-pinned open beneath the retained root directory
/// descriptor (`openat` + `O_NOFOLLOW` per component). Rejects
/// symlinks, traversal, and non-regular files without TOCTOU races.
[[nodiscard]] Void::Result::Result<std::optional<OpenedStaticFile>>
open_safe(std::string_view request_path) const;
[[nodiscard]] const std::filesystem::path& root() const noexcept
{
return root_;
@@ -112,14 +171,25 @@ namespace Void::Net
private:
struct DirHandle {
int fd{-1};
explicit DirHandle(int d) noexcept : fd(d) {}
~DirHandle() noexcept;
DirHandle(const DirHandle&) = delete;
DirHandle& operator=(const DirHandle&) = delete;
};
StaticFileResolver(std::filesystem::path root,
std::string index_file)
: root_(std::move(root)), index_file_(std::move(index_file))
std::string index_file,
std::shared_ptr<DirHandle> root_dir)
: root_(std::move(root)), index_file_(std::move(index_file)),
root_dir_(std::move(root_dir))
{
}
std::filesystem::path root_;
std::string index_file_;
std::shared_ptr<DirHandle> root_dir_;
};
struct WebSocketConnectionId {
+185
View File
@@ -0,0 +1,185 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
enum class WebSocketOpcode : std::uint8_t {
Continuation = 0x0,
Text = 0x1,
Binary = 0x2,
Close = 0x8,
Ping = 0x9,
Pong = 0xA,
};
struct WebSocketLimits {
std::size_t max_message_bytes{1024ULL * 1024};
std::size_t max_output_messages{64};
std::size_t max_output_bytes{4ULL * 1024 * 1024};
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
};
struct WebSocketUpgradeOptions {
std::vector<std::string> allowed_origins{};
std::vector<std::string> supported_subprotocols{};
WebSocketLimits limits{};
};
struct WebSocketUpgradeHandshake {
std::string accept_key{};
std::optional<std::string> selected_subprotocol{};
};
struct WebSocketFrame {
bool fin{true};
WebSocketOpcode opcode{WebSocketOpcode::Text};
bool masked{false};
std::array<std::byte, 4> mask_key{};
std::vector<std::byte> payload{};
};
struct WebSocketMessage {
WebSocketOpcode opcode{WebSocketOpcode::Text};
std::vector<std::byte> payload{};
std::optional<WebSocketClose> close_info{};
[[nodiscard]] std::string_view text_view() const noexcept
{
return std::string_view{
reinterpret_cast<const char*>(payload.data()),
payload.size()};
}
};
/// Compute RFC 6455 Sec-WebSocket-Accept = Base64(SHA1(key + GUID)).
[[nodiscard]] std::string compute_websocket_accept(std::string_view key);
/// Validate strict RFC 3629 UTF-8 byte sequences (required for text frames
/// and close reasons by RFC 6455 section 5.6 / 8.1).
[[nodiscard]] bool is_valid_utf8(std::span<const std::byte> data) noexcept;
[[nodiscard]] bool is_valid_utf8(std::string_view data) noexcept;
/// Validate a client HTTP/1.1 Upgrade request per RFC 6455 section 4.2.1.
[[nodiscard]] Void::Result::Result<WebSocketUpgradeHandshake>
validate_websocket_upgrade_request(
const ServerRequest& request,
const WebSocketUpgradeOptions& options = {});
/// Encode a single RFC 6455 frame. When `masked == true`, applies
/// `mask_key` XOR masking to payload bytes.
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_websocket_frame(const WebSocketFrame& frame);
/// Encode a RFC 6455 Close control frame (2-byte big-endian code + UTF-8
/// reason <= 123 bytes).
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_websocket_close_frame(const WebSocketClose& close, bool masked,
std::array<std::byte, 4> mask_key = {});
/// Incremental RFC 6455 frame decoder & fragmented message assembler.
/// `expect_masked_incoming = true` for server side, `false` for client.
class WebSocketDecoder final
{
public:
explicit WebSocketDecoder(bool expect_masked_incoming,
WebSocketLimits limits = {}) noexcept;
void reset() noexcept;
/// Feed arbitrary bytes and append any completed data or control
/// messages (Text, Binary, Ping, Pong, Close) to `out_messages`.
[[nodiscard]] Void::Result::Result<void>
feed(std::span<const std::byte> input,
std::vector<WebSocketMessage>& out_messages);
[[nodiscard]] bool close_received() const noexcept
{
return m_close_received;
}
private:
bool m_expect_masked{true};
WebSocketLimits m_limits{};
std::vector<std::byte> m_buf{};
bool m_in_fragment{false};
WebSocketOpcode m_fragment_opcode{WebSocketOpcode::Text};
std::vector<std::byte> m_fragment_payload{};
bool m_close_received{false};
};
struct WebSocketConnectOptions {
std::vector<Header> extra_headers{};
std::optional<std::string> subprotocol{};
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
WebSocketLimits limits{};
};
/// Synchronous RFC 6455 WebSocket client over loopback/TCP HTTP/1.1 Upgrade
/// (for direct ws:// endpoints and independent conformance testing).
class WebSocketClient final
{
public:
using ConnectOptions = WebSocketConnectOptions;
WebSocketClient() noexcept = default;
~WebSocketClient() noexcept;
WebSocketClient(WebSocketClient&&) noexcept;
WebSocketClient& operator=(WebSocketClient&&) noexcept;
WebSocketClient(const WebSocketClient&) = delete;
WebSocketClient& operator=(const WebSocketClient&) = delete;
[[nodiscard]] static Void::Result::Result<WebSocketClient>
connect(std::string_view ws_url,
const ConnectOptions& options = ConnectOptions{});
[[nodiscard]] bool is_open() const noexcept;
[[nodiscard]] const std::optional<std::string>&
selected_subprotocol() const noexcept;
[[nodiscard]] Void::Result::Result<void>
send_text(std::string_view text);
[[nodiscard]] Void::Result::Result<void>
send_binary(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void>
send_ping(std::span<const std::byte> payload = {});
[[nodiscard]] Void::Result::Result<void>
send_pong(std::span<const std::byte> payload = {});
[[nodiscard]] Void::Result::Result<void>
send_fragmented_text(std::span<const std::string_view> chunks);
/// Receive the next decoded WebSocket message (auto-answering Ping
/// when `auto_pong == true` unless callers want to inspect Ping).
[[nodiscard]] Void::Result::Result<WebSocketMessage>
receive(std::chrono::milliseconds timeout =
std::chrono::seconds{5});
[[nodiscard]] Void::Result::Result<void>
close(WebSocketClose close_info = {1000, ""});
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit WebSocketClient(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Net
+51
View File
@@ -0,0 +1,51 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/RPC/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace Void::RPC
{
/// Decoded Wire v1 envelope (deterministic big-endian binary format).
struct WireEnvelope {
std::uint16_t major{kWireMajorV1};
std::uint16_t minor{kWireMinorV1};
FrameKind kind{FrameKind::UnaryRequest};
std::uint8_t flags{kFlagEndOfMessage};
CallId call_id{};
MethodId method{};
std::uint32_t schema_version{1};
std::uint32_t remaining_timeout_ms{0};
RpcStatusCode status_code{RpcStatusCode::Ok};
std::vector<MetadataEntry> metadata{};
std::vector<std::byte> payload{};
};
/// Fixed Wire v1 header prefix size in bytes before metadata entries:
/// magic(4) + major(2) + minor(2) + header_len(4) + total_len(4) +
/// kind(1) + flags(1) + reserved(2) + call_id(16) + service_id(8) +
/// method_id(4) + schema_ver(4) + timeout_ms(4) + status_code(2) +
/// metadata_count(2) = 60 bytes.
inline constexpr std::size_t kWireFixedHeaderBytes{60};
/// Encode a Wire v1 envelope in explicit network byte order, validating
/// all header, metadata, and payload limits before allocation.
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_envelope(const WireEnvelope& env,
const RpcLimits& limits = {});
/// Decode a Wire v1 envelope in explicit network byte order. Rejects bad
/// magic, unsupported major versions, non-zero reserved bytes, unknown
/// required flags, integer overflow, truncation, trailing garbage, and
/// limit violations BEFORE allocating payload/metadata buffers. Unknown
/// optional minor header extensions beyond metadata are length-skipped.
[[nodiscard]] Void::Result::Result<WireEnvelope>
decode_envelope(std::span<const std::byte> bytes,
const RpcLimits& limits = {});
} // namespace Void::RPC
+184
View File
@@ -0,0 +1,184 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/RPC/Codec.hpp>
#include <Void/RPC/Types.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <cstddef>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::RPC
{
using OwnedBytes = std::vector<std::byte>;
struct CallContext {
CallId call_id{};
MethodDescriptor method{};
PrincipalView principal{};
Void::Time::MonotonicClock::time_point deadline{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
std::vector<MetadataEntry> metadata{};
std::stop_token stop{};
[[nodiscard]] std::chrono::milliseconds
remaining_timeout() const noexcept
{
const auto rem = Void::Time::remaining_until(*clock, deadline);
return std::chrono::duration_cast<std::chrono::milliseconds>(
rem);
}
};
struct CallOptions {
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
std::vector<MetadataEntry> metadata{};
std::vector<Void::Net::Header> transport_headers{};
std::stop_token stop{};
std::uint32_t schema_version{1};
};
using UnaryHandler =
std::function<Void::Result::Result<OwnedBytes>(const CallContext&,
OwnedBytes)>;
struct AuthHook {
std::function<Void::Result::Result<PrincipalView>(
const std::vector<Void::Net::Header>& transport_headers,
const std::vector<MetadataEntry>& metadata)>
authenticate{};
std::function<Void::Result::Result<void>(
const MethodDescriptor& method, const PrincipalView& principal)>
authorize{};
};
/// Move-only RAII method registration handle. Unregistering stops new
/// admission for the method and drains already-admitted calls before
/// returning.
class Registration final
{
public:
Registration() noexcept = default;
~Registration() noexcept;
Registration(Registration&& other) noexcept;
Registration& operator=(Registration&& other) noexcept;
Registration(const Registration&) = delete;
Registration& operator=(const Registration&) = delete;
[[nodiscard]] bool active() const noexcept;
void unregister_and_drain() noexcept;
private:
friend class Server;
struct Entry;
std::shared_ptr<void> m_server_state{};
MethodId m_id{};
std::uint64_t m_reg_gen{0};
bool m_active{false};
};
struct ServerOptions {
Void::Net::HttpServerOptions http_options{};
RpcLimits limits{};
AuthHook auth{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
};
/// Ownership-safe unary HTTP/1.1 RPC server implementing `/void-rpc/v1/call`.
class Server final
{
public:
explicit Server(ServerOptions options = {});
~Server() noexcept;
Server(Server&&) noexcept;
Server& operator=(Server&&) noexcept;
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
[[nodiscard]] Void::Result::Result<Registration>
bind(MethodDescriptor descriptor, UnaryHandler handler);
/// Mount `/void-rpc/v1/call` onto an external HttpServer (or call
/// `start()` to run the owned HttpServer directly).
[[nodiscard]] Void::Result::Result<void>
mount(Void::Net::HttpServer& http_server);
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
std::chrono::seconds{10}) noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::string base_url() const;
/// Direct in-process Wire v1 dispatch (useful for deterministic
/// unit/fault testing without TCP sockets).
[[nodiscard]] Void::Result::Result<OwnedBytes>
handle_raw_envelope(
std::span<const std::byte> request_bytes,
const std::vector<Void::Net::Header>& transport_headers =
{});
private:
friend class Registration;
struct State;
std::shared_ptr<State> m_state;
};
struct ClientOptions {
std::string endpoint_base_url{};
Void::Net::HttpClientOptions http_options{
.verify_tls = true,
};
RpcLimits limits{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
};
/// Unary HTTP/1.1 RPC client encoding Wire v1 envelopes over
/// `Void::Net::HttpClient`.
class Client final
{
public:
explicit Client(ClientOptions options);
~Client() noexcept;
Client(Client&&) noexcept;
Client& operator=(Client&&) noexcept;
Client(const Client&) = delete;
Client& operator=(const Client&) = delete;
[[nodiscard]] Void::Result::Result<OwnedBytes>
call(MethodId method, OwnedBytes payload,
const CallOptions& options = {});
[[nodiscard]] std::size_t in_flight_calls() const noexcept;
private:
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::RPC
+205
View File
@@ -0,0 +1,205 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <array>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <map>
#include <string>
#include <string_view>
#include <vector>
namespace Void::RPC
{
inline constexpr std::array<std::byte, 4> kWireMagic{
std::byte{'V'}, std::byte{'R'}, std::byte{'P'}, std::byte{'C'}};
inline constexpr std::uint16_t kWireMajorV1{1};
inline constexpr std::uint16_t kWireMinorV1{0};
inline constexpr std::string_view kUnaryHttpPath{"/void-rpc/v1/call"};
inline constexpr std::string_view kWireContentType{
"application/vnd.void.rpc.v1"};
enum class RpcStatusCode : std::uint16_t {
Ok = 0,
Cancelled = 1,
InvalidArgument = 2,
DeadlineExceeded = 3,
NotFound = 4,
PermissionDenied = 5,
Unauthenticated = 6,
ResourceExhausted = 7,
FailedPrecondition = 8,
Unimplemented = 9,
Unavailable = 10,
Internal = 11,
DataLoss = 12,
UnknownOutcome = 13,
ProtocolError = 14,
IncompatibleVersion = 15,
};
enum class FrameKind : std::uint8_t {
UnaryRequest = 1,
UnaryResponse = 2,
StreamOpen = 3,
StreamData = 4,
StreamCredit = 5,
StreamHalfClose = 6,
StreamCancel = 7,
StreamTerminal = 8,
};
/// Wire v1 frame flags. Bits 0..3 are optional/informational; bits 4..7 are
/// required-to-understand (unknown required flags fail closed).
inline constexpr std::uint8_t kFlagNone = 0x00U;
inline constexpr std::uint8_t kFlagEndOfMessage = 0x01U;
inline constexpr std::uint8_t kFlagRequiredMask = 0xF0U;
[[nodiscard]] inline Void::Result::Error
make_rpc_error(RpcStatusCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case RpcStatusCode::Ok:
case RpcStatusCode::Internal:
kind = ErrorKind::internal;
break;
case RpcStatusCode::Cancelled:
kind = ErrorKind::cancelled;
break;
case RpcStatusCode::InvalidArgument:
case RpcStatusCode::PermissionDenied:
case RpcStatusCode::Unauthenticated:
kind = ErrorKind::invalid_argument;
break;
case RpcStatusCode::DeadlineExceeded:
kind = ErrorKind::timeout;
break;
case RpcStatusCode::NotFound:
kind = ErrorKind::not_found;
break;
case RpcStatusCode::ResourceExhausted:
kind = ErrorKind::exhausted;
break;
case RpcStatusCode::FailedPrecondition:
case RpcStatusCode::UnknownOutcome:
kind = ErrorKind::conflict;
break;
case RpcStatusCode::Unimplemented:
case RpcStatusCode::IncompatibleVersion:
kind = ErrorKind::unsupported;
break;
case RpcStatusCode::Unavailable:
kind = ErrorKind::overloaded;
break;
case RpcStatusCode::DataLoss:
case RpcStatusCode::ProtocolError:
kind = ErrorKind::corrupt;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kRpcErrorDomain,
static_cast<std::int32_t>(code)}};
}
[[nodiscard]] inline RpcStatusCode
rpc_status_from_error(const Void::Result::Error& err) noexcept
{
if (err.code().domain == Void::Result::kRpcErrorDomain) {
return static_cast<RpcStatusCode>(err.code().value);
}
switch (err.kind()) {
case Void::Result::ErrorKind::cancelled:
return RpcStatusCode::Cancelled;
case Void::Result::ErrorKind::invalid_argument:
return RpcStatusCode::InvalidArgument;
case Void::Result::ErrorKind::timeout:
return RpcStatusCode::DeadlineExceeded;
case Void::Result::ErrorKind::not_found:
return RpcStatusCode::NotFound;
case Void::Result::ErrorKind::exhausted:
return RpcStatusCode::ResourceExhausted;
case Void::Result::ErrorKind::conflict:
return RpcStatusCode::FailedPrecondition;
case Void::Result::ErrorKind::unsupported:
return RpcStatusCode::Unimplemented;
case Void::Result::ErrorKind::overloaded:
return RpcStatusCode::Unavailable;
case Void::Result::ErrorKind::corrupt:
return RpcStatusCode::ProtocolError;
default:
return RpcStatusCode::Internal;
}
}
struct MethodId {
std::uint64_t service{0};
std::uint32_t method{0};
[[nodiscard]] auto
operator<=>(const MethodId&) const noexcept = default;
};
struct CallId {
std::array<std::byte, 16> bytes{};
[[nodiscard]] auto
operator<=>(const CallId&) const noexcept = default;
[[nodiscard]] static CallId generate();
};
struct MetadataEntry {
std::string key{};
std::string value{};
[[nodiscard]] bool
operator==(const MetadataEntry&) const noexcept = default;
};
/// Immutable authenticated principal descriptor provided by AuthHook.
struct PrincipalView {
bool authenticated{false};
std::string subject{};
std::vector<std::string> roles{};
std::map<std::string, std::string, std::less<>> attributes{};
};
struct MethodDescriptor {
MethodId id{};
std::string service_name{};
std::string method_name{};
std::uint32_t schema_version{1};
bool replay_safe{false};
};
struct RpcLimits {
std::size_t max_header_bytes{16ULL * 1024};
std::size_t max_metadata_entries{64};
std::size_t max_payload_bytes{4ULL * 1024 * 1024};
std::size_t max_client_calls{1024};
std::size_t max_server_executing{256};
std::size_t max_server_queued_bytes{64ULL * 1024 * 1024};
std::chrono::milliseconds max_server_timeout{
std::chrono::seconds{30}};
};
struct RpcStatus {
RpcStatusCode code{RpcStatusCode::Ok};
std::string message{};
[[nodiscard]] bool ok() const noexcept
{
return code == RpcStatusCode::Ok;
}
};
} // namespace Void::RPC
+135
View File
@@ -0,0 +1,135 @@
#pragma once
#include <Void/Scheduler/Types.hpp>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
struct CivilMinute {
std::int32_t year{1970};
std::uint32_t month{1}; // 1..12
std::uint32_t day{1}; // 1..31
std::uint32_t hour{0}; // 0..23
std::uint32_t minute{0}; // 0..59
std::uint32_t weekday{4}; // 0=Sunday .. 6=Saturday
};
/// Convert civil UTC components to minutes since 1970-01-01T00:00Z.
[[nodiscard]] std::int64_t
civil_to_epoch_minute(std::int32_t year, std::uint32_t month,
std::uint32_t day, std::uint32_t hour,
std::uint32_t minute) noexcept;
/// Convert minutes since 1970-01-01T00:00Z to civil components + weekday.
[[nodiscard]] CivilMinute
epoch_minute_to_civil(std::int64_t epoch_minute) noexcept;
/// Explicit DST transition rule for deterministic timezone resolution
/// without relying on ambient OS tzdata behavior.
struct DstTransitionRule {
std::string name{};
std::int32_t standard_offset_minutes{0};
std::int32_t dst_offset_minutes{0};
/// Spring-forward gap window in local wall minutes `[start, end)`.
std::optional<std::int64_t> gap_start_local_min{};
std::optional<std::int64_t> gap_end_local_min{};
/// Fall-back fold window in local wall minutes `[start, end)`.
/// Minutes in `[start, end)` happen twice: fold 0 at `dst_offset`,
/// fold 1 at `standard_offset`.
std::optional<std::int64_t> fold_start_local_min{};
std::optional<std::int64_t> fold_end_local_min{};
};
struct ResolvedSlot {
std::int64_t utc_ms{0};
std::uint8_t fold_index{0};
};
/// Explicit timezone registry. Recognizes `"UTC"`, `"Z"`, fixed numeric
/// offsets (`+HH:MM`, `-HH:MM`, `UTC+HH:MM`, `UTC-HH:MM`), and explicitly
/// registered `DstTransitionRule` zones. Unknown zones fail with
/// `UnsupportedTimezone` (never silent UTC fallback).
class TimezoneRegistry final
{
public:
TimezoneRegistry() = default;
void register_dst_zone(DstTransitionRule rule);
[[nodiscard]] Result<void>
validate_timezone(std::string_view tz) const;
[[nodiscard]] Result<std::vector<ResolvedSlot>>
resolve_local_minute(std::string_view tz,
std::int64_t local_epoch_minute,
DstGapPolicy gap_policy,
DstFoldPolicy fold_policy) const;
/// Approximate local epoch minute range covering `[utc_min_lo,
/// utc_min_hi]` for `tz`.
[[nodiscard]] Result<std::pair<std::int64_t, std::int64_t>>
local_minute_bounds(std::string_view tz,
std::int64_t utc_min_lo,
std::int64_t utc_min_hi) const;
private:
std::map<std::string, DstTransitionRule, std::less<>> m_dst_zones{};
};
struct MaterializedSlots {
std::vector<ResolvedSlot> slots{};
std::int64_t next_cursor_utc_ms{0};
bool more_pending{false};
};
/// 5-field cron-like calendar expression (`minute hour day month weekday`)
/// supporting `*`, lists, ranges, and steps. Both day-of-month and weekday
/// constraints apply.
class CalendarExpression final
{
public:
[[nodiscard]] static Result<CalendarExpression>
parse(std::string_view expression);
[[nodiscard]] bool matches(const CivilMinute& cm) const noexcept;
/// Next matching local epoch minute strictly >= `from_local_min`,
/// capped by `max_local_min`.
[[nodiscard]] std::optional<std::int64_t>
next_matching_minute(std::int64_t from_local_min,
std::int64_t max_local_min) const noexcept;
/// Latest matching local epoch minute <= `from_local_min` and
/// >= `min_local_min`. Allows O(1) coalescing across millions of
/// missed minutes.
[[nodiscard]] std::optional<std::int64_t>
prev_matching_minute(std::int64_t from_local_min,
std::int64_t min_local_min) const noexcept;
[[nodiscard]] Result<MaterializedSlots>
materialize_range(const CalendarSpec& spec,
const TimezoneRegistry& tz_registry,
std::int64_t after_utc_ms,
std::int64_t up_to_utc_ms,
MisfirePolicy misfire,
std::size_t max_catch_up) const;
private:
std::uint64_t m_minutes{0}; // bits 0..59
std::uint32_t m_hours{0}; // bits 0..23
std::uint32_t m_days{0}; // bits 1..31
std::uint32_t m_months{0}; // bits 1..12
std::uint32_t m_weekdays{0}; // bits 0..6 (0 = Sunday)
};
} // namespace Void::Scheduler
+100
View File
@@ -0,0 +1,100 @@
#pragma once
#include <Void/Scheduler/Calendar.hpp>
#include <Void/Scheduler/Store.hpp>
#include <Void/Scheduler/Types.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
struct SchedulerOptions {
std::string owner_id{"scheduler-default"};
std::shared_ptr<JobStore> store{};
const Void::Time::MonotonicClock* monotonic_clock{
&Void::Time::SystemMonotonicClock::instance()};
const Void::Time::CivilClock* civil_clock{
&Void::Time::SystemCivilClock::instance()};
TimezoneRegistry timezones{};
SchedulerLimits limits{};
RandomU64Fn rng{};
ObservationHook observer{};
};
/// Pure, thread-free timer/calendar job scheduler with pluggable durable
/// persistence (`InMemoryJobStore` or `SchedulerStorage::StorageJobStore`).
class Scheduler final
{
public:
[[nodiscard]] static Result<Scheduler>
create(SchedulerOptions options = {});
Scheduler(Scheduler&&) noexcept;
Scheduler& operator=(Scheduler&&) noexcept;
Scheduler(const Scheduler&) = delete;
Scheduler& operator=(const Scheduler&) = delete;
~Scheduler() noexcept;
[[nodiscard]] Result<void> register_handler(std::string handler_id,
HandlerFn handler);
[[nodiscard]] Result<std::uint64_t>
add_job(JobSpec spec,
Void::Async::OperationOptions options = {});
/// Increment revision and atomically record an old-revision
/// invalidation watermark. Failed updates leave prior policy intact.
[[nodiscard]] Result<std::uint64_t>
update_job(JobSpec spec,
Void::Async::OperationOptions options = {});
/// Write a job tombstone, stop new admission, and signal stop to
/// active handlers for the job.
[[nodiscard]] Result<void>
remove_job(std::string_view job_id,
Void::Async::OperationOptions options = {});
/// Run one bounded scheduling pass: materialize due occurrences
/// under misfire/catch-up/retention limits and dispatch ready
/// occurrences outside scheduler/store locks. Returns count of
/// occurrences executed in this pass.
[[nodiscard]] Result<std::size_t>
tick(Void::Async::OperationOptions options = {});
/// Execute at most one ready occurrence from the monotonic min-heap
/// outside scheduler/store locks.
[[nodiscard]] Result<bool>
dispatch_one(Void::Async::OperationOptions options = {});
/// Stop materialization/dispatch, signal stop to active handlers,
/// and wait up to `options.deadline` for live handlers to exit.
/// Never erases running records or abandons active frames.
[[nodiscard]] Result<ShutdownReport>
close_and_join(Void::Async::OperationOptions options = {});
[[nodiscard]] Result<std::vector<JobRecord>> list_jobs() const;
[[nodiscard]] Result<std::vector<OccurrenceRecord>>
list_occurrences() const;
[[nodiscard]] Result<void>
acknowledge_dead(const OccurrenceId& id);
[[nodiscard]] Result<std::size_t>
prune_completed(std::size_t max_count = 256);
[[nodiscard]] Result<std::size_t>
reclaim_invalidated(std::size_t max_count = 256);
[[nodiscard]] Result<StoreStats> stats() const;
private:
struct State;
explicit Scheduler(std::shared_ptr<State> state) noexcept;
std::shared_ptr<State> m_state;
};
} // namespace Void::Scheduler
+105
View File
@@ -0,0 +1,105 @@
#pragma once
#include <Void/Scheduler/Types.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
/// Persistence port for Scheduler state transitions.
/// Implementations guarantee atomic conditional commits (in-memory mutex
/// or `Void::Storage::Engine` conditional batches).
class JobStore
{
public:
virtual ~JobStore() = default;
[[nodiscard]] virtual Result<void>
acquire_ownership(std::string_view owner_id) = 0;
[[nodiscard]] virtual Result<void> release_ownership() = 0;
[[nodiscard]] virtual Result<void> put_job(const JobRecord& job) = 0;
[[nodiscard]] virtual Result<void>
update_job(const JobRecord& updated,
std::uint64_t expected_revision) = 0;
[[nodiscard]] virtual Result<void>
tombstone_job(std::string_view job_id) = 0;
[[nodiscard]] virtual Result<std::vector<JobRecord>>
load_jobs() const = 0;
[[nodiscard]] virtual Result<std::vector<OccurrenceRecord>>
load_occurrences() const = 0;
/// Atomically insert new occurrences (enforcing unique
/// `(job, revision, intended_utc_ms, fold_index)` dedup and
/// retention cap) AND advance the job's cursor/sequence.
[[nodiscard]] virtual Result<std::size_t> materialize_occurrences(
std::string_view job_id, std::uint64_t expected_revision,
std::int64_t new_cursor_utc_ms,
std::int64_t new_cursor_monotonic_ns, bool cursor_initialized,
bool one_shot_materialized, std::uint64_t next_sequence,
const std::vector<OccurrenceRecord>& records) = 0;
/// Atomically verify job is not tombstoned, check old-revision
/// invalidation watermark, and transition `Pending -> Running`
/// bumping `attempt`.
[[nodiscard]] virtual Result<OccurrenceRecord>
claim_occurrence(const OccurrenceId& id,
std::uint32_t expected_attempt) = 0;
/// Atomically transition `Running -> Completed` and optionally
/// advance a FixedDelay job's monotonic cursor.
[[nodiscard]] virtual Result<void> complete_occurrence(
const OccurrenceId& id, std::uint32_t attempt,
std::int64_t completed_utc_ms,
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
std::nullopt) = 0;
/// Atomically transition `Running -> Pending` (retry) or
/// `Running -> Dead` (exhausted).
[[nodiscard]] virtual Result<void> fail_occurrence(
const OccurrenceId& id, std::uint32_t attempt,
std::int64_t next_due_monotonic_ns,
std::int64_t next_due_utc_ms, bool mark_dead,
std::string diagnostic_category) = 0;
/// Return a `Running` occurrence to `Pending` during host shutdown
/// without consuming a retry attempt.
[[nodiscard]] virtual Result<void>
requeue_on_shutdown(const OccurrenceId& id,
std::uint32_t attempt) = 0;
/// Startup recovery: return every `Running` record to `Pending`
/// preserving its exact `OccurrenceId` and attempt counter.
[[nodiscard]] virtual Result<std::size_t>
recover_running_occurrences() = 0;
[[nodiscard]] virtual Result<void>
acknowledge_dead(const OccurrenceId& id) = 0;
[[nodiscard]] virtual Result<std::size_t>
prune_completed(std::int64_t before_utc_ms,
std::size_t max_count) = 0;
[[nodiscard]] virtual Result<std::size_t>
reclaim_invalidated(std::size_t max_count) = 0;
[[nodiscard]] virtual Result<StoreStats> stats() const = 0;
};
/// Default in-memory `JobStore` implementation requiring zero `Storage`
/// dependency.
[[nodiscard]] std::shared_ptr<JobStore>
make_in_memory_job_store(SchedulerLimits limits = {});
} // namespace Void::Scheduler
+339
View File
@@ -0,0 +1,339 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class SchedulerErrorCode : std::int32_t {
None = 0,
InvalidArgument = 1,
InvalidRule = 2,
UnsupportedTimezone = 3,
NotFound = 4,
Conflict = 5,
Overloaded = 6,
RetentionFull = 7,
PersistenceError = 8,
UnknownOutcome = 9,
HandlerFailed = 10,
Cancelled = 11,
Closed = 12,
SelfJoin = 13,
OwnershipLocked = 14,
CorruptRecord = 15,
};
[[nodiscard]] inline Error make_scheduler_error(SchedulerErrorCode code,
std::string message)
{
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case SchedulerErrorCode::None:
case SchedulerErrorCode::HandlerFailed:
kind = ErrorKind::internal;
break;
case SchedulerErrorCode::InvalidArgument:
case SchedulerErrorCode::InvalidRule:
kind = ErrorKind::invalid_argument;
break;
case SchedulerErrorCode::UnsupportedTimezone:
kind = ErrorKind::unsupported;
break;
case SchedulerErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case SchedulerErrorCode::Conflict:
case SchedulerErrorCode::UnknownOutcome:
case SchedulerErrorCode::SelfJoin:
case SchedulerErrorCode::OwnershipLocked:
kind = ErrorKind::conflict;
break;
case SchedulerErrorCode::Overloaded:
kind = ErrorKind::overloaded;
break;
case SchedulerErrorCode::RetentionFull:
kind = ErrorKind::exhausted;
break;
case SchedulerErrorCode::PersistenceError:
kind = ErrorKind::io;
break;
case SchedulerErrorCode::CorruptRecord:
kind = ErrorKind::corrupt;
break;
case SchedulerErrorCode::Cancelled:
case SchedulerErrorCode::Closed:
kind = ErrorKind::cancelled;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kSchedulerErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct OccurrenceId {
std::string job_id{};
std::uint64_t revision{0};
std::uint64_t sequence{0};
[[nodiscard]] auto
operator<=>(const OccurrenceId&) const noexcept = default;
[[nodiscard]] std::string to_idempotency_key() const
{
return job_id + "#" + std::to_string(revision) + "#" +
std::to_string(sequence);
}
};
enum class MisfirePolicy : std::uint8_t {
Skip = 0,
CoalesceLatest = 1,
CatchUpBounded = 2,
};
enum class OverlapPolicy : std::uint8_t {
Forbid = 0,
QueueOne = 1,
AllowBounded = 2,
};
enum class DstGapPolicy : std::uint8_t {
Skip = 0,
NextValid = 1,
};
enum class DstFoldPolicy : std::uint8_t {
First = 0,
Second = 1,
Twice = 2,
};
enum class ScheduleKind : std::uint8_t {
OneShot = 0,
FixedDelay = 1,
FixedRate = 2,
Calendar = 3,
};
struct RetryPolicy {
std::uint32_t max_attempts{5};
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
std::chrono::milliseconds max_delay{std::chrono::minutes{5}};
std::uint32_t multiplier{2};
};
struct CalendarSpec {
std::string expression{};
std::string timezone{"UTC"};
std::uint32_t tz_data_version{1};
DstGapPolicy gap_policy{DstGapPolicy::Skip};
DstFoldPolicy fold_policy{DstFoldPolicy::First};
};
struct Schedule {
ScheduleKind kind{ScheduleKind::OneShot};
std::int64_t start_utc_ms{0};
std::optional<Void::Time::MonotonicClock::time_point>
due_monotonic{};
std::chrono::milliseconds interval{0};
CalendarSpec calendar{};
[[nodiscard]] static Schedule
one_shot_monotonic(Void::Time::MonotonicClock::time_point due)
{
Schedule s{};
s.kind = ScheduleKind::OneShot;
s.due_monotonic = due;
return s;
}
[[nodiscard]] static Schedule one_shot_utc(std::int64_t utc_ms)
{
Schedule s{};
s.kind = ScheduleKind::OneShot;
s.start_utc_ms = utc_ms;
return s;
}
[[nodiscard]] static Schedule fixed_delay(
std::chrono::milliseconds delay,
std::optional<Void::Time::MonotonicClock::time_point>
first_due = std::nullopt)
{
Schedule s{};
s.kind = ScheduleKind::FixedDelay;
s.interval = delay;
s.due_monotonic = first_due;
return s;
}
[[nodiscard]] static Schedule fixed_rate(
std::chrono::milliseconds period,
std::optional<Void::Time::MonotonicClock::time_point>
first_due = std::nullopt)
{
Schedule s{};
s.kind = ScheduleKind::FixedRate;
s.interval = period;
s.due_monotonic = first_due;
return s;
}
[[nodiscard]] static Schedule calendar_schedule(CalendarSpec spec)
{
Schedule s{};
s.kind = ScheduleKind::Calendar;
s.calendar = std::move(spec);
return s;
}
};
struct JobSpec {
std::string id{};
Schedule schedule{};
std::string handler_id{};
std::uint32_t payload_schema{1};
std::vector<std::byte> payload{};
MisfirePolicy misfire{MisfirePolicy::CoalesceLatest};
OverlapPolicy overlap{OverlapPolicy::Forbid};
std::uint32_t max_concurrent{1};
RetryPolicy retry{};
};
enum class OccurrenceStatus : std::uint8_t {
Pending = 0,
Running = 1,
Completed = 2,
Dead = 3,
Cancelled = 4,
};
struct JobRecord {
std::uint32_t format_version{1};
JobSpec spec{};
std::uint64_t revision{1};
/// Unstarted occurrences with `revision < invalidated_before_revision`
/// are logically cancelled and cannot be claimed.
std::uint64_t invalidated_before_revision{1};
bool tombstoned{false};
std::int64_t cursor_utc_ms{0};
std::int64_t cursor_monotonic_ns{0};
bool cursor_initialized{false};
bool one_shot_materialized{false};
std::uint64_t next_sequence{1};
};
struct OccurrenceRecord {
std::uint32_t format_version{1};
OccurrenceId id{};
std::int64_t intended_utc_ms{0};
std::int64_t due_monotonic_ns{0};
std::uint8_t fold_index{0};
OccurrenceStatus status{OccurrenceStatus::Pending};
std::uint32_t attempt{0};
std::string handler_id{};
std::uint32_t payload_schema{1};
std::vector<std::byte> payload{};
std::string diagnostic_category{};
std::int64_t completed_utc_ms{0};
bool dead_acknowledged{false};
};
struct SchedulerLimits {
std::size_t max_jobs{10000};
std::size_t max_retained_occurrences{100000};
std::size_t max_payload_bytes{64ULL * 1024};
std::size_t max_loaded_payload_bytes{16ULL * 1024 * 1024};
std::size_t max_ready_dispatches{256};
std::size_t max_active_handlers{32};
std::size_t max_catch_up_per_job_per_pass{100};
std::size_t max_retries_per_turn{64};
std::size_t max_durable_batch_bytes{1024ULL * 1024};
std::chrono::milliseconds completed_retention{
std::chrono::hours{24 * 7}};
};
struct ShutdownReport {
bool complete{true};
std::vector<OccurrenceId> live_occurrences{};
};
struct StoreStats {
std::size_t jobs{0};
std::size_t pending{0};
std::size_t running{0};
std::size_t completed{0};
std::size_t dead{0};
std::size_t cancelled{0};
std::size_t total_retained{0};
bool retention_saturated{false};
};
enum class ObservationKind : std::uint8_t {
Materialize = 0,
Dispatch = 1,
Complete = 2,
Retry = 3,
DeadLetter = 4,
RetentionPause = 5,
Recover = 6,
};
struct ObservationEvent {
ObservationKind kind{ObservationKind::Dispatch};
std::size_t count{1};
std::int64_t lag_ms{0};
};
using ObservationHook = std::function<void(const ObservationEvent&)>;
using RandomU64Fn = std::function<std::uint64_t()>;
struct OccurrenceContext {
OccurrenceId id{};
std::uint32_t attempt{1};
std::uint32_t payload_schema{1};
std::int64_t intended_utc_ms{0};
std::uint8_t fold_index{0};
};
using HandlerFn = std::function<Result<void>(
const OccurrenceContext&, std::span<const std::byte>,
Void::Async::OperationOptions)>;
[[nodiscard]] inline std::int64_t
to_ns(Void::Time::MonotonicClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(
tp.time_since_epoch())
.count();
}
[[nodiscard]] inline std::int64_t
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch())
.count();
}
} // namespace Void::Scheduler
@@ -0,0 +1,111 @@
#pragma once
#include <Void/Scheduler/Store.hpp>
#include <Void/Storage/Engine.hpp>
#include <memory>
#include <string>
namespace Void::SchedulerStorage
{
struct StorageJobStoreOptions {
Void::Scheduler::SchedulerLimits limits{};
/// Key prefix namespace within the shared `Void::Storage::Engine`.
std::string key_prefix{"sched:v1:"};
/// Set true only when explicitly recovering after a process crash
/// where the previous owner exited without calling
/// `release_ownership()` (the underlying `Storage::Engine` OS lock
/// guarantees single-process directory ownership).
bool recover_stale_owner{false};
};
/// Durable `Void::Scheduler::JobStore` backed by `Void::Storage::Engine`
/// conditional `Batch` writes (`Durability::Sync`, 1 MiB batch cap,
/// exclusive logical owner lock, unique civil-slot dedup index, and
/// `UnknownOutcome` propagation).
class StorageJobStore final : public Void::Scheduler::JobStore
{
public:
StorageJobStore(Void::Storage::Engine& engine,
StorageJobStoreOptions options = {});
[[nodiscard]] Void::Scheduler::Result<void>
acquire_ownership(std::string_view owner_id) override;
[[nodiscard]] Void::Scheduler::Result<void>
release_ownership() override;
[[nodiscard]] Void::Scheduler::Result<void>
put_job(const Void::Scheduler::JobRecord& job) override;
[[nodiscard]] Void::Scheduler::Result<void>
update_job(const Void::Scheduler::JobRecord& updated,
std::uint64_t expected_revision) override;
[[nodiscard]] Void::Scheduler::Result<void>
tombstone_job(std::string_view job_id) override;
[[nodiscard]] Void::Scheduler::Result<
std::vector<Void::Scheduler::JobRecord>>
load_jobs() const override;
[[nodiscard]] Void::Scheduler::Result<
std::vector<Void::Scheduler::OccurrenceRecord>>
load_occurrences() const override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
materialize_occurrences(
std::string_view job_id, std::uint64_t expected_revision,
std::int64_t new_cursor_utc_ms,
std::int64_t new_cursor_monotonic_ns,
bool cursor_initialized, bool one_shot_materialized,
std::uint64_t next_sequence,
const std::vector<Void::Scheduler::OccurrenceRecord>&
records) override;
[[nodiscard]] Void::Scheduler::Result<
Void::Scheduler::OccurrenceRecord>
claim_occurrence(const Void::Scheduler::OccurrenceId& id,
std::uint32_t expected_attempt) override;
[[nodiscard]] Void::Scheduler::Result<void> complete_occurrence(
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
std::int64_t completed_utc_ms,
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
std::nullopt) override;
[[nodiscard]] Void::Scheduler::Result<void> fail_occurrence(
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
std::int64_t next_due_monotonic_ns,
std::int64_t next_due_utc_ms, bool mark_dead,
std::string diagnostic_category) override;
[[nodiscard]] Void::Scheduler::Result<void>
requeue_on_shutdown(const Void::Scheduler::OccurrenceId& id,
std::uint32_t attempt) override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
recover_running_occurrences() override;
[[nodiscard]] Void::Scheduler::Result<void>
acknowledge_dead(const Void::Scheduler::OccurrenceId& id) override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
prune_completed(std::int64_t before_utc_ms,
std::size_t max_count) override;
[[nodiscard]] Void::Scheduler::Result<std::size_t>
reclaim_invalidated(std::size_t max_count) override;
[[nodiscard]] Void::Scheduler::Result<Void::Scheduler::StoreStats>
stats() const override;
private:
Void::Storage::Engine* m_engine{nullptr};
StorageJobStoreOptions m_options{};
std::string m_owner_id{};
};
} // namespace Void::SchedulerStorage
+895
View File
@@ -0,0 +1,895 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/ShortUrl/ShortUrl.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::ShortUrl::V2
{
inline constexpr std::uint32_t kServiceVersionV2{2};
inline constexpr std::uint32_t kRecordSchemaVersion{1};
enum class V2ErrorCode : std::int32_t {
None = 0,
InvalidRequest = 1,
InvalidUrl = 2,
InvalidKey = 3,
InvalidExpiry = 4,
Conflict = 5,
NotFound = 6,
Expired = 7,
Revoked = 8,
Unsupported = 9,
Unauthorized = 10,
RateLimited = 11,
QuotaExceeded = 12,
IdentityExpired = 13,
StorageError = 14,
UnknownOutcome = 15,
ProviderError = 16,
Timeout = 17,
Unavailable = 18,
ResponseTooLarge = 19,
Internal = 20,
};
[[nodiscard]] inline Void::Result::Error
make_shorturl_error(V2ErrorCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case V2ErrorCode::None:
case V2ErrorCode::Internal:
case V2ErrorCode::ProviderError:
kind = ErrorKind::internal;
break;
case V2ErrorCode::InvalidRequest:
case V2ErrorCode::InvalidUrl:
case V2ErrorCode::InvalidKey:
case V2ErrorCode::InvalidExpiry:
case V2ErrorCode::Unauthorized:
kind = ErrorKind::invalid_argument;
break;
case V2ErrorCode::NotFound:
kind = ErrorKind::not_found;
break;
case V2ErrorCode::Conflict:
case V2ErrorCode::Expired:
case V2ErrorCode::Revoked:
case V2ErrorCode::IdentityExpired:
case V2ErrorCode::UnknownOutcome:
kind = ErrorKind::conflict;
break;
case V2ErrorCode::Unsupported:
kind = ErrorKind::unsupported;
break;
case V2ErrorCode::RateLimited:
case V2ErrorCode::Unavailable:
kind = ErrorKind::overloaded;
break;
case V2ErrorCode::QuotaExceeded:
case V2ErrorCode::ResponseTooLarge:
kind = ErrorKind::exhausted;
break;
case V2ErrorCode::StorageError:
kind = ErrorKind::io;
break;
case V2ErrorCode::Timeout:
kind = ErrorKind::timeout;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kShortUrlErrorDomain,
static_cast<std::int32_t>(code)}};
}
[[nodiscard]] inline V2ErrorCode
v2_error_code_from(const Void::Result::Error& err) noexcept
{
if (err.code().domain == Void::Result::kShortUrlErrorDomain) {
return static_cast<V2ErrorCode>(err.code().value);
}
switch (err.kind()) {
case Void::Result::ErrorKind::invalid_argument:
return V2ErrorCode::InvalidRequest;
case Void::Result::ErrorKind::not_found:
return V2ErrorCode::NotFound;
case Void::Result::ErrorKind::conflict:
return V2ErrorCode::Conflict;
case Void::Result::ErrorKind::timeout:
return V2ErrorCode::Timeout;
case Void::Result::ErrorKind::overloaded:
return V2ErrorCode::Unavailable;
case Void::Result::ErrorKind::unsupported:
return V2ErrorCode::Unsupported;
case Void::Result::ErrorKind::exhausted:
return V2ErrorCode::QuotaExceeded;
case Void::Result::ErrorKind::io:
return V2ErrorCode::StorageError;
default:
return V2ErrorCode::Internal;
}
}
[[nodiscard]] inline V1::ErrorCode
to_v1_error_code(V2ErrorCode code) noexcept
{
switch (code) {
case V2ErrorCode::None: return V1::ErrorCode::none;
case V2ErrorCode::InvalidRequest:
case V2ErrorCode::InvalidKey:
case V2ErrorCode::InvalidExpiry:
case V2ErrorCode::IdentityExpired:
return V1::ErrorCode::invalid_request;
case V2ErrorCode::InvalidUrl: return V1::ErrorCode::invalid_url;
case V2ErrorCode::Unsupported: return V1::ErrorCode::unsupported;
case V2ErrorCode::NotFound: return V1::ErrorCode::not_found;
case V2ErrorCode::Expired: return V1::ErrorCode::expired;
case V2ErrorCode::Revoked: return V1::ErrorCode::revoked;
case V2ErrorCode::Conflict: return V1::ErrorCode::conflict;
case V2ErrorCode::Unauthorized: return V1::ErrorCode::unauthorized;
case V2ErrorCode::RateLimited: return V1::ErrorCode::rate_limited;
case V2ErrorCode::Timeout: return V1::ErrorCode::timeout;
case V2ErrorCode::Unavailable:
case V2ErrorCode::QuotaExceeded:
return V1::ErrorCode::unavailable;
case V2ErrorCode::StorageError: return V1::ErrorCode::storage;
case V2ErrorCode::ResponseTooLarge:
return V1::ErrorCode::response_too_large;
case V2ErrorCode::ProviderError:
case V2ErrorCode::UnknownOutcome:
return V1::ErrorCode::provider_error;
case V2ErrorCode::Internal: return V1::ErrorCode::internal_error;
}
return V1::ErrorCode::internal_error;
}
enum class LinkState : std::uint8_t {
Active = 1,
Revoked = 2,
};
struct LinkRecord {
std::string key{};
std::string target_url{};
std::int64_t created_at_unix_seconds{0};
std::int64_t expires_at_unix_seconds{0}; // 0 = permanent
LinkState state{LinkState::Active};
std::string operation_id{};
std::uint32_t schema_version{kRecordSchemaVersion};
};
struct IdempotencyRecord {
std::string operation_id{};
std::string key{};
std::string target_url{};
std::int64_t created_at_unix_seconds{0};
std::int64_t retain_until_unix_seconds{0};
};
struct Link {
std::string key{};
std::string short_url{};
std::string target_url{};
std::int64_t expires_at_unix_seconds{0};
std::uint32_t retry_after_seconds{0};
};
struct CreateLink {
std::string target_url{};
std::string custom_key{};
std::int64_t expires_at_unix_seconds{0};
};
struct ShortenOptions {
std::string operation_id{};
std::chrono::seconds idempotency_retention{std::chrono::hours{24}};
};
struct LocalProviderLimits {
std::size_t max_url_bytes{8192};
std::size_t max_key_bytes{64};
std::size_t generated_key_length{16};
std::size_t max_collision_retries{8};
std::size_t max_entries{100'000};
std::size_t max_retained_identities{10'000};
std::size_t max_concurrent_ops{128};
};
using HostPolicy = std::function<bool(std::string_view host)>;
/// Validate target URL: absolute http/https, non-empty host, no userinfo,
/// no control chars, bounded length, and optional host policy check.
[[nodiscard]] inline Void::Result::Result<void>
validate_target_url(std::string_view url,
std::size_t max_url_bytes = 8192,
const HostPolicy& host_policy = {})
{
if (url.empty() || url.size() > max_url_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL empty or exceeds length limit")};
}
for (const unsigned char ch : url) {
if (ch <= 0x20 || ch >= 0x7F) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL contains control or whitespace "
"character")};
}
}
std::size_t rest_pos = 0;
if (url.starts_with("https://")) {
rest_pos = 8U;
} else if (url.starts_with("http://")) {
rest_pos = 7U;
} else {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target URL scheme must be http or https")};
}
const std::string_view after_scheme = url.substr(rest_pos);
const std::size_t auth_end = after_scheme.find_first_of("/?#");
const std::string_view authority = after_scheme.substr(0, auth_end);
if (authority.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl, "ShortUrl: missing URL authority")};
}
if (authority.find('@') != std::string_view::npos) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: userinfo in target URL is forbidden")};
}
std::string_view host = authority;
if (host.front() == '[') {
const std::size_t close_b = host.find(']');
if (close_b == std::string_view::npos || close_b == 1U) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: malformed IPv6 host in target URL")};
}
host = host.substr(1U, close_b - 1U);
} else if (const std::size_t colon = host.find(':');
colon != std::string_view::npos) {
const std::string_view port_sv = host.substr(colon + 1U);
if (port_sv.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: empty port in target URL")};
}
for (const char c : port_sv) {
if (c < '0' || c > '9') {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: non-numeric port in target URL")};
}
}
host = host.substr(0, colon);
}
if (host.empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl, "ShortUrl: empty host")};
}
if (host_policy && !host_policy(host)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidUrl,
"ShortUrl: target host rejected by policy")};
}
return {};
}
/// Validate custom key: 1..max_key_bytes ASCII [A-Za-z0-9_-], rejecting
/// reserved route names.
[[nodiscard]] inline Void::Result::Result<void>
validate_custom_key(std::string_view key,
std::size_t max_key_bytes = 64)
{
if (key.empty() || key.size() > max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key length must be 1..64")};
}
for (const unsigned char ch : key) {
const bool ok = (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch == '-' || ch == '_';
if (!ok) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key contains invalid character")};
}
}
static const std::set<std::string_view> kReserved{
"health", "metrics", "admin", "api", "shorten",
"resolve", "revoke", "v1", "v2", "static",
"assets", "status", "robots", "favicon"};
std::string lower;
lower.reserve(key.size());
for (const char ch : key) {
lower.push_back(static_cast<char>(
ch >= 'A' && ch <= 'Z' ? (ch - 'A' + 'a') : ch));
}
if (kReserved.contains(lower)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey,
"ShortUrl: custom key matches reserved route name")};
}
return {};
}
class RandomBytesPort
{
public:
virtual ~RandomBytesPort() = default;
[[nodiscard]] virtual Void::Result::Result<void>
fill(std::span<std::byte> out) = 0;
};
class SystemRandomBytesPort final : public RandomBytesPort
{
public:
[[nodiscard]] Void::Result::Result<void>
fill(std::span<std::byte> out) override
{
std::random_device rd;
std::size_t i = 0;
while (i < out.size()) {
const unsigned int v = rd();
for (int b = 0; b < 4 && i < out.size(); ++b, ++i) {
out[i] = static_cast<std::byte>((v >> (b * 8)) & 0xFFU);
}
}
return {};
}
};
enum class InsertStatus : std::uint8_t {
Inserted,
IdempotentReplay,
Conflict,
IdentityExpired,
QuotaExceeded,
};
struct InsertOutcome {
InsertStatus status{InsertStatus::Inserted};
LinkRecord record{};
};
class LinkRepositoryPort
{
public:
virtual ~LinkRepositoryPort() = default;
[[nodiscard]] virtual bool is_durable() const noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<InsertOutcome>
insert_conditional(const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds,
std::size_t max_entries,
std::size_t max_retained_identities) = 0;
[[nodiscard]] virtual Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const = 0;
[[nodiscard]] virtual Void::Result::Result<void>
revoke(std::string_view key,
std::int64_t now_unix_seconds) = 0;
};
/// Explicitly nondurable in-memory repository for unit tests and semantic
/// verification. Preserves conditional insert, tombstones, and idempotency.
class InMemoryLinkRepository final : public LinkRepositoryPort
{
public:
[[nodiscard]] bool is_durable() const noexcept override
{
return false;
}
[[nodiscard]] Void::Result::Result<InsertOutcome>
insert_conditional(const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds,
std::size_t max_entries,
std::size_t max_retained_identities) override
{
std::lock_guard lock{m_mutex};
if (idem.has_value() && !idem->operation_id.empty()) {
if (const auto iit = m_idempotency.find(idem->operation_id);
iit != m_idempotency.end()) {
if (iit->second.retain_until_unix_seconds <=
now_unix_seconds) {
return InsertOutcome{InsertStatus::IdentityExpired,
{}};
}
if (const auto lit = m_links.find(iit->second.key);
lit != m_links.end()) {
return InsertOutcome{
InsertStatus::IdempotentReplay, lit->second};
}
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (m_idempotency.size() >= max_retained_identities) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
}
if (m_links.contains(record.key)) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (m_links.size() >= max_entries) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
m_links.emplace(record.key, record);
if (idem.has_value() && !idem->operation_id.empty()) {
m_idempotency.emplace(idem->operation_id, *idem);
}
return InsertOutcome{InsertStatus::Inserted, record};
}
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const override
{
std::lock_guard lock{m_mutex};
if (const auto it = m_links.find(key); it != m_links.end()) {
return std::optional<LinkRecord>{it->second};
}
return std::optional<LinkRecord>{};
}
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key, std::int64_t) override
{
std::lock_guard lock{m_mutex};
const auto it = m_links.find(key);
if (it == m_links.end()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound,
"ShortUrl: cannot revoke unknown key")};
}
it->second.state = LinkState::Revoked;
return {};
}
private:
mutable std::mutex m_mutex;
std::map<std::string, LinkRecord, std::less<>> m_links;
std::map<std::string, IdempotencyRecord, std::less<>> m_idempotency;
};
/// Abstract V2 provider interface outside the frozen V1 ABI.
class Provider
{
public:
virtual ~Provider() = default;
[[nodiscard]] virtual std::string_view
provider_id() const noexcept = 0;
[[nodiscard]] virtual V1::Health health() const = 0;
[[nodiscard]] virtual bool supports_resolve() const noexcept = 0;
[[nodiscard]] virtual Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) = 0;
[[nodiscard]] virtual Void::Result::Result<Link>
resolve(std::string_view key) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
revoke(std::string_view key) = 0;
};
struct LocalProviderOptions {
std::string public_base_url{"https://sho.rt"};
std::string provider_id{"void.local"};
LocalProviderLimits limits{};
HostPolicy host_policy{};
};
/// Native local ShortUrl V2 provider composing LinkRepositoryPort,
/// CivilClock, and RandomBytesPort with rejection-sampled base62 keys.
class LocalProvider final : public Provider
{
public:
using Options = LocalProviderOptions;
LocalProvider(std::shared_ptr<LinkRepositoryPort> repository,
Options options = Options{},
const Void::Time::CivilClock& clock =
Void::Time::SystemCivilClock::instance(),
std::shared_ptr<RandomBytesPort> rng =
std::make_shared<SystemRandomBytesPort>())
: m_repo(std::move(repository)), m_options(std::move(options)),
m_clock(&clock), m_rng(std::move(rng))
{
while (m_options.public_base_url.size() > 1U &&
m_options.public_base_url.back() == '/') {
m_options.public_base_url.pop_back();
}
}
[[nodiscard]] std::string_view
provider_id() const noexcept override
{
return m_options.provider_id;
}
[[nodiscard]] V1::Health health() const override
{
if (m_stopping.load(std::memory_order_acquire) || !m_repo) {
return {V1::HealthStatus::unhealthy,
"provider unavailable"};
}
return {V1::HealthStatus::healthy,
m_repo->is_durable() ? "durable local provider"
: "nondurable memory provider"};
}
[[nodiscard]] bool supports_resolve() const noexcept override
{
return true;
}
void shutdown() noexcept
{
m_stopping.store(true, std::memory_order_release);
}
[[nodiscard]] Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (auto u = validate_target_url(request.target_url,
m_options.limits.max_url_bytes,
m_options.host_policy);
!u.has_value()) {
return std::unexpected{std::move(u.error())};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
if (request.expires_at_unix_seconds < 0 ||
(request.expires_at_unix_seconds > 0 &&
request.expires_at_unix_seconds <= now_s)) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidExpiry,
"ShortUrl: expiry must be 0 (permanent) or in the "
"future")};
}
const bool custom = !request.custom_key.empty();
if (custom) {
if (auto k = validate_custom_key(
request.custom_key, m_options.limits.max_key_bytes);
!k.has_value()) {
return std::unexpected{std::move(k.error())};
}
}
const std::size_t attempts =
custom ? 1U : m_options.limits.max_collision_retries;
for (std::size_t attempt = 0; attempt < attempts; ++attempt) {
std::string key;
if (custom) {
key = request.custom_key;
} else {
auto gen = generate_base62_key(
m_options.limits.generated_key_length);
if (!gen.has_value()) {
return std::unexpected{std::move(gen.error())};
}
key = std::move(*gen);
}
LinkRecord rec;
rec.key = key;
rec.target_url = request.target_url;
rec.created_at_unix_seconds = now_s;
rec.expires_at_unix_seconds =
request.expires_at_unix_seconds;
rec.state = LinkState::Active;
rec.operation_id = options.operation_id;
rec.schema_version = kRecordSchemaVersion;
std::optional<IdempotencyRecord> idem;
if (!options.operation_id.empty()) {
idem = IdempotencyRecord{
.operation_id = options.operation_id,
.key = key,
.target_url = request.target_url,
.created_at_unix_seconds = now_s,
.retain_until_unix_seconds =
now_s + options.idempotency_retention.count(),
};
}
auto ins = m_repo->insert_conditional(
rec, idem, now_s, m_options.limits.max_entries,
m_options.limits.max_retained_identities);
if (!ins.has_value()) {
return std::unexpected{std::move(ins.error())};
}
switch (ins->status) {
case InsertStatus::Inserted:
case InsertStatus::IdempotentReplay:
return make_link(ins->record);
case InsertStatus::Conflict:
if (custom) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Conflict,
"ShortUrl: custom key already exists")};
}
continue; // retry random key
case InsertStatus::IdentityExpired:
return std::unexpected{make_shorturl_error(
V2ErrorCode::IdentityExpired,
"ShortUrl: operation_id retention expired")};
case InsertStatus::QuotaExceeded:
return std::unexpected{make_shorturl_error(
V2ErrorCode::QuotaExceeded,
"ShortUrl: repository quota or retention "
"exhausted")};
}
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Conflict,
"ShortUrl: exhausted random key collision retries")};
}
[[nodiscard]] Void::Result::Result<Link>
resolve(std::string_view key) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
}
auto rec = m_repo->get(key);
if (!rec.has_value()) {
return std::unexpected{std::move(rec.error())};
}
if (!rec->has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound, "ShortUrl: key not found")};
}
const LinkRecord& r = **rec;
if (r.state == LinkState::Revoked) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Revoked, "ShortUrl: link revoked")};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
if (r.expires_at_unix_seconds > 0 &&
r.expires_at_unix_seconds <= now_s) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Expired, "ShortUrl: link expired")};
}
return make_link(r);
}
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key) override
{
auto slot = try_admit();
if (!slot.has_value()) {
return std::unexpected{std::move(slot.error())};
}
if (key.empty() || key.size() > m_options.limits.max_key_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidKey, "ShortUrl: invalid key")};
}
const std::int64_t now_s =
std::chrono::duration_cast<std::chrono::seconds>(
m_clock->now().time_since_epoch())
.count();
return m_repo->revoke(key, now_s);
}
private:
struct OpSlot {
std::atomic<std::size_t>* active{nullptr};
~OpSlot() noexcept
{
if (active != nullptr) {
active->fetch_sub(1, std::memory_order_acq_rel);
}
}
OpSlot(std::atomic<std::size_t>* a) noexcept : active(a) {}
OpSlot(OpSlot&& o) noexcept
: active(std::exchange(o.active, nullptr))
{
}
OpSlot(const OpSlot&) = delete;
OpSlot& operator=(const OpSlot&) = delete;
};
[[nodiscard]] Void::Result::Result<OpSlot> try_admit()
{
if (m_stopping.load(std::memory_order_acquire) || !m_repo ||
!m_rng) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
"ShortUrl: provider shut down or unconfigured")};
}
std::size_t cur = m_active_ops.load(std::memory_order_relaxed);
for (;;) {
if (cur >= m_options.limits.max_concurrent_ops) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::RateLimited,
"ShortUrl: max concurrent operations reached")};
}
if (m_active_ops.compare_exchange_weak(
cur, cur + 1U, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
return OpSlot{&m_active_ops};
}
}
}
[[nodiscard]] Void::Result::Result<std::string>
generate_base62_key(std::size_t len) const
{
static constexpr char kAlphabet[63] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"
"wxyz";
constexpr unsigned char kCutoff = 62U * 4U; // 248 (uniform)
std::string out;
out.reserve(len);
std::array<std::byte, 64> buf{};
while (out.size() < len) {
auto r = m_rng->fill(buf);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
for (const std::byte b : buf) {
const auto u = static_cast<unsigned char>(b);
if (u < kCutoff) {
out.push_back(kAlphabet[u % 62U]);
if (out.size() == len) {
break;
}
}
}
}
return out;
}
[[nodiscard]] Link make_link(const LinkRecord& r) const
{
return Link{
.key = r.key,
.short_url =
std::format("{}/{}", m_options.public_base_url, r.key),
.target_url = r.target_url,
.expires_at_unix_seconds = r.expires_at_unix_seconds,
};
}
std::shared_ptr<LinkRepositoryPort> m_repo;
Options m_options;
const Void::Time::CivilClock* m_clock;
std::shared_ptr<RandomBytesPort> m_rng;
std::atomic<bool> m_stopping{false};
std::atomic<std::size_t> m_active_ops{0};
};
/// Adapter implementing frozen `Void::ShortUrl::V1::IShortener` on top of
/// any V2 `Provider` without changing V1 layout or virtual table order.
class V1Adapter final : public V1::IShortener
{
public:
explicit V1Adapter(std::shared_ptr<Provider> provider)
: m_provider(std::move(provider))
{
}
[[nodiscard]] std::string_view
provider_id() const noexcept override
{
return m_provider ? m_provider->provider_id()
: std::string_view{"unconfigured"};
}
[[nodiscard]] V1::Health health() const override
{
return m_provider ? m_provider->health()
: V1::Health{V1::HealthStatus::unhealthy,
"null provider"};
}
[[nodiscard]] V1::ShortenResult
shorten(const V1::ShortenRequest& request) override
{
if (!m_provider) {
return {.error = {V1::ErrorCode::unavailable,
"null provider"}};
}
auto res = m_provider->shorten(CreateLink{
.target_url = request.target_url,
.custom_key = request.custom_key,
.expires_at_unix_seconds = request.expires_at_unix_seconds,
});
if (!res.has_value()) {
const auto code = v2_error_code_from(res.error());
return {.error = {to_v1_error_code(code),
std::string{res.error().message()}}};
}
return {
.short_url = std::move(res->short_url),
.key = std::move(res->key),
.expires_at_unix_seconds = res->expires_at_unix_seconds,
.error = {},
};
}
[[nodiscard]] bool supports_resolve() const noexcept override
{
return m_provider != nullptr && m_provider->supports_resolve();
}
[[nodiscard]] V1::ResolveResult
resolve(const V1::ResolveRequest& request) override
{
if (!m_provider) {
return {.error = {V1::ErrorCode::unavailable,
"null provider"}};
}
auto res = m_provider->resolve(request.key);
if (!res.has_value()) {
const auto code = v2_error_code_from(res.error());
return {.error = {to_v1_error_code(code),
std::string{res.error().message()}}};
}
return {
.target_url = std::move(res->target_url),
.expires_at_unix_seconds = res->expires_at_unix_seconds,
.error = {},
};
}
private:
std::shared_ptr<Provider> m_provider;
};
} // namespace Void::ShortUrl::V2
@@ -0,0 +1,67 @@
#pragma once
#include <Void/Net/Http.hpp>
#include <Void/ShortUrl/V2.hpp>
#include <chrono>
#include <cstdint>
#include <string>
#include <vector>
namespace Void::ShortUrl::V2
{
struct RemoteCapabilities {
bool supports_custom_key{true};
bool supports_expiry{true};
bool supports_resolve{true};
bool supports_revoke{true};
};
struct RemoteProviderOptions {
std::string base_url{};
std::string provider_id{"void.remote"};
RemoteCapabilities capabilities{};
Void::Net::HttpClientOptions http_options{
.verify_tls = true,
.max_body_size = 1024ULL * 1024,
};
std::chrono::seconds timeout{std::chrono::seconds{10}};
std::uint64_t max_response_bytes{1024ULL * 1024};
std::vector<Void::Net::Header> headers{};
};
/// Generic remote ShortUrl V2 provider over `Void::Net::HttpClient`.
/// Checks capability flags before network mutation, enforces response size
/// and deadline bounds, preserves Retry-After, and maps lost-reply
/// transport failures after send to `V2ErrorCode::UnknownOutcome`.
class RemoteProvider final : public Provider
{
public:
explicit RemoteProvider(RemoteProviderOptions options);
[[nodiscard]] std::string_view
provider_id() const noexcept override;
[[nodiscard]] V1::Health health() const override;
[[nodiscard]] bool supports_resolve() const noexcept override;
[[nodiscard]] Void::Result::Result<Link>
shorten(const CreateLink& request,
const ShortenOptions& options = {}) override;
[[nodiscard]] Void::Result::Result<Link>
resolve(std::string_view key) override;
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key) override;
/// Retry-After seconds from the most recent rate-limited/unavailable
/// remote response (0 if absent).
[[nodiscard]] std::uint32_t last_retry_after_seconds() const noexcept;
private:
RemoteProviderOptions m_options;
Void::Net::HttpClient m_client;
std::atomic<std::uint32_t> m_last_retry_after{0};
};
} // namespace Void::ShortUrl::V2
@@ -0,0 +1,58 @@
#pragma once
#include <Void/ShortUrl/V2.hpp>
#include <Void/Storage/Engine.hpp>
#include <cstdint>
#include <memory>
#include <mutex>
namespace Void::ShortUrl::V2
{
/// CSPRNG byte source backed by `Void::Security` (libsodium).
class SecurityRandomBytesPort final : public RandomBytesPort
{
public:
[[nodiscard]] Void::Result::Result<void>
fill(std::span<std::byte> out) override;
};
/// Durable `LinkRepositoryPort` backed by `Void::Storage::Engine`
/// conditional `Batch` writes, preserving tombstones, V2 idempotency
/// records, and quotas across crash/restart boundaries.
class StorageLinkRepository final : public LinkRepositoryPort
{
public:
explicit StorageLinkRepository(
std::shared_ptr<Void::Storage::Engine> engine,
std::uint64_t disk_quota_bytes = 1024ULL * 1024 * 1024);
[[nodiscard]] bool is_durable() const noexcept override
{
return true;
}
[[nodiscard]] Void::Result::Result<InsertOutcome>
insert_conditional(const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds,
std::size_t max_entries,
std::size_t max_retained_identities) override;
[[nodiscard]] Void::Result::Result<std::optional<LinkRecord>>
get(std::string_view key) const override;
[[nodiscard]] Void::Result::Result<void>
revoke(std::string_view key,
std::int64_t now_unix_seconds) override;
private:
mutable std::mutex m_write_mutex;
std::shared_ptr<Void::Storage::Engine> m_engine;
std::uint64_t m_disk_quota_bytes;
};
} // namespace Void::ShortUrl::V2
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace Void::FileSystem
{
enum class DirectoryEventKind : std::uint8_t {
Created,
Modified,
Deleted,
Renamed,
AttributeChanged,
RescanRequired,
};
struct DirectoryEvent {
DirectoryEventKind kind{DirectoryEventKind::Modified};
std::filesystem::path path{};
std::filesystem::path old_path{};
bool is_directory{false};
std::string detail{};
};
/// Predicate queried for every discovered/modified path. Returning true skips
/// watching (for directories) and suppresses event delivery for that path.
using IgnorePredicate =
std::function<bool(const std::filesystem::path& path, bool is_directory)>;
struct DirectoryWatcherOptions {
IgnorePredicate ignore{};
std::size_t max_watches{65536};
std::size_t max_queued_events{4096};
std::chrono::milliseconds rename_pair_window{std::chrono::milliseconds{50}};
};
/// Kernel-event (Linux inotify) recursive directory watcher with auto-watch
/// attachment on new subdirectories, rename pairing, ignore filtering, and
/// explicit RescanRequired signaling on queue overflow or watch exhaustion.
class DirectoryWatcher final
{
public:
~DirectoryWatcher() noexcept;
DirectoryWatcher(const DirectoryWatcher&) = delete;
DirectoryWatcher& operator=(const DirectoryWatcher&) = delete;
DirectoryWatcher(DirectoryWatcher&&) noexcept;
DirectoryWatcher& operator=(DirectoryWatcher&&) noexcept;
[[nodiscard]] static Void::Result::Result<DirectoryWatcher,
Void::Result::Error>
create(const std::filesystem::path& root,
DirectoryWatcherOptions options = {});
[[nodiscard]] Void::Result::Result<std::vector<DirectoryEvent>,
Void::Result::Error>
poll(std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Re-walk `root()` and rebuild all inotify watches from scratch.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> rescan();
/// Wake any thread blocked inside poll().
void wake() noexcept;
/// Enqueue a RescanRequired event and wake waiters (deterministic test hook).
void simulate_overflow_for_test();
[[nodiscard]] const std::filesystem::path& root() const noexcept;
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] int native_handle() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> impl_{};
explicit DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::FileSystem
+592
View File
@@ -24,10 +24,17 @@
#ifndef _WIN32
#include <fcntl.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#if defined(__linux__)
#include <sys/random.h>
#if __has_include(<linux/fs.h>)
#include <linux/fs.h>
#endif
#endif
#endif
@@ -548,4 +555,589 @@ namespace detail
return {};
}
// ── VL-010: File Locks, Atomic Symlink Swap, Reflink Copy, Timestamps ────────
enum class LockMode : std::uint8_t {
Shared,
Exclusive,
};
/// RAII advisory file lock backed by POSIX flock(2).
class FileLock final
{
public:
FileLock() noexcept = default;
~FileLock() noexcept { unlock(); }
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
FileLock(FileLock&& other) noexcept
: fd_(std::move(other.fd_))
, mode_(other.mode_)
{
}
FileLock& operator=(FileLock&& other) noexcept
{
if (this != &other) {
unlock();
fd_ = std::move(other.fd_);
mode_ = other.mode_;
}
return *this;
}
[[nodiscard]] bool locked() const noexcept { return fd_.valid(); }
[[nodiscard]] LockMode mode() const noexcept { return mode_; }
[[nodiscard]] int native_handle() const noexcept { return fd_.get(); }
void unlock() noexcept
{
#ifndef _WIN32
if (fd_.valid()) {
while (::flock(fd_.get(), LOCK_UN) != 0 && errno == EINTR) {
}
fd_.reset();
}
#endif
}
[[nodiscard]] static Void::Result::Result<FileLock, Void::Result::Error>
lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
auto res = acquire(path, mode, false);
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
if (!res->has_value()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::internal,
"FileSystem::FileLock::lock: unexpected empty result")};
}
return std::move(**res);
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
try_lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
return acquire(path, mode, true);
}
private:
explicit FileLock(Void::System::OwnedFd fd, LockMode mode) noexcept
: fd_(std::move(fd))
, mode_(mode)
{
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
acquire(const std::filesystem::path& path,
LockMode mode,
bool nonblocking)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::FileLock: empty path")};
}
int raw = ::open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666);
if (raw < 0 && mode == LockMode::Shared &&
(errno == EACCES || errno == EROFS)) {
raw = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
}
if (raw < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: cannot open '{}'",
path.string()),
err)};
}
Void::System::OwnedFd fd{raw};
const int op = (mode == LockMode::Shared ? LOCK_SH : LOCK_EX) |
(nonblocking ? LOCK_NB : 0);
for (;;) {
if (::flock(fd.get(), op) == 0) {
return std::optional<FileLock>{
FileLock{std::move(fd), mode}};
}
const int err = errno;
if (err == EINTR) {
continue;
}
if (nonblocking && (err == EWOULDBLOCK || err == EAGAIN)) {
return std::optional<FileLock>{std::nullopt};
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: flock failed for '{}'",
path.string()),
err)};
}
#else
(void)path;
(void)mode;
(void)nonblocking;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::FileLock: unsupported platform")};
#endif
}
Void::System::OwnedFd fd_{};
LockMode mode_{LockMode::Exclusive};
};
/// Atomically create or replace symlink at `link_path` pointing to `target`
/// (symlinkat temp -> renameat -> optional parent dir fsync).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_symlink_swap(
const std::filesystem::path& link_path,
const std::filesystem::path& target,
ReplaceDurability durability = ReplaceDurability::durable_sync)
{
#ifndef _WIN32
if (link_path.empty() || !link_path.has_filename() || target.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: empty link or target path")};
}
const std::string target_name = link_path.filename().string();
if (target_name == "." || target_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: invalid link filename")};
}
const std::filesystem::path parent =
link_path.parent_path().empty() ? std::filesystem::path{"."}
: link_path.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
std::string tmp_name;
bool created = false;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_lnk_{:016x}", target_name, detail::next_temp_entropy());
if (::symlinkat(target.c_str(), dir_fd.get(), tmp_name.c_str()) == 0) {
created = true;
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"FileSystem::atomic_symlink_swap: symlinkat failed in '{}'",
parent.string()),
last_err)};
}
}
if (!created) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::atomic_symlink_swap: exhausted temporary link names",
last_err)};
}
bool cleanup = true;
struct CleanupGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~CleanupGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} cleanup_guard{dir_fd.get(), &tmp_name, &cleanup};
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
target_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: renameat failed for '{}'",
link_path.string()),
err)};
}
cleanup = false;
if (durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::atomic_symlink_swap: parent dir fsync failed for '{}'",
link_path.string()),
err)};
}
}
return {};
#else
(void)link_path;
(void)target;
(void)durability;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::atomic_symlink_swap: unsupported platform")};
#endif
}
enum class CopyMethod : std::uint8_t {
Reflink,
PrivateCopy,
};
struct CopyResult {
std::uint64_t bytes{0};
CopyMethod method{CopyMethod::PrivateCopy};
};
struct CopyOptions {
bool overwrite{true};
bool preserve_permissions{true};
ReplaceDurability durability{ReplaceDurability::atomic_visibility};
};
/// Copy a regular file using CoW reflink (`ioctl(FICLONE)`) with atomic
/// staging and private-copy fallback. Explicitly never creates hardlinks.
[[nodiscard]] inline Void::Result::Result<CopyResult, Void::Result::Error>
reflink_copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
CopyOptions options = {})
{
#ifndef _WIN32
if (src.empty() || dst.empty() || !dst.has_filename()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid source or destination path")};
}
const std::string dst_name = dst.filename().string();
if (dst_name == "." || dst_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid destination filename")};
}
const int raw_src = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
if (raw_src < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open '{}'",
src.string()),
err)};
}
Void::System::OwnedFd src_fd{raw_src};
struct stat src_st {};
if (::fstat(src_fd.get(), &src_st) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: fstat failed on '{}'",
src.string()),
err)};
}
if (!S_ISREG(src_st.st_mode)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("FileSystem::reflink_copy_file: '{}' is not a regular file",
src.string()))};
}
const std::filesystem::path parent =
dst.parent_path().empty() ? std::filesystem::path{"."}
: dst.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
const mode_t create_mode = options.preserve_permissions
? static_cast<mode_t>(src_st.st_mode & 0777)
: static_cast<mode_t>(0644);
std::string tmp_name;
Void::System::OwnedFd tmp_fd;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_cp_{:016x}", dst_name, detail::next_temp_entropy());
const int fd = ::openat(dir_fd.get(),
tmp_name.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
create_mode);
if (fd >= 0) {
tmp_fd.reset(fd);
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format("FileSystem::reflink_copy_file: create temp in '{}'",
parent.string()),
last_err)};
}
}
if (!tmp_fd.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::reflink_copy_file: exhausted temp names",
last_err)};
}
bool cleanup_tmp = true;
struct TempGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~TempGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_tmp};
CopyResult result;
result.bytes = static_cast<std::uint64_t>(src_st.st_size);
bool cloned = false;
#if defined(__linux__) && defined(FICLONE)
for (;;) {
if (::ioctl(tmp_fd.get(), FICLONE, src_fd.get()) == 0) {
cloned = true;
result.method = CopyMethod::Reflink;
break;
}
if (errno == EINTR) {
continue;
}
const int err = errno;
if (err == EOPNOTSUPP || err == EXDEV || err == EINVAL ||
err == ENOTTY || err == ENOSYS || err == EBADF || err == ETXTBSY
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
|| err == ENOTSUP
#endif
) {
break;
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: FICLONE failed for '{}'",
dst.string()),
err)};
}
#endif
if (!cloned) {
result.method = CopyMethod::PrivateCopy;
std::vector<char> buf(64ULL * 1024ULL);
std::uint64_t copied = 0;
for (;;) {
const ssize_t r = ::read(src_fd.get(), buf.data(), buf.size());
if (r > 0) {
std::size_t off = 0;
const auto ur = static_cast<std::size_t>(r);
while (off < ur) {
const ssize_t w =
::write(tmp_fd.get(), buf.data() + off, ur - off);
if (w < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: write failed for '{}'",
dst.string()),
err)};
}
off += static_cast<std::size_t>(w);
}
copied += ur;
} else if (r == 0) {
break;
} else {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: read failed on '{}'",
src.string()),
err)};
}
}
result.bytes = copied;
}
if (options.preserve_permissions) {
(void)::fchmod(tmp_fd.get(), create_mode);
}
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::sync_failed,
std::format("FileSystem::reflink_copy_file: fsync failed for '{}'",
dst.string()),
err)};
}
}
if (auto closed = tmp_fd.close(); !closed.has_value()) {
return std::unexpected{std::move(closed.error())};
}
if (options.overwrite) {
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: rename failed for '{}'",
dst.string()),
err)};
}
} else {
if (::linkat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str(),
0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: publish failed for '{}'",
dst.string()),
err)};
}
(void)::unlinkat(dir_fd.get(), tmp_name.c_str(), 0);
}
cleanup_tmp = false;
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::reflink_copy_file: parent fsync failed for '{}'",
dst.string()),
err)};
}
}
return result;
#else
(void)src;
(void)dst;
(void)options;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::reflink_copy_file: unsupported platform")};
#endif
}
/// Set access and modification timestamps without dereferencing symlinks.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_timestamps_nofollow(const std::filesystem::path& path,
std::int64_t atime_sec,
std::int32_t atime_nsec,
std::int64_t mtime_sec,
std::int32_t mtime_nsec)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: empty path")};
}
auto valid_nsec = [](std::int32_t ns) noexcept {
return (ns >= 0 && ns < 1'000'000'000) || ns == UTIME_NOW ||
ns == UTIME_OMIT;
};
if (!valid_nsec(atime_nsec) || !valid_nsec(mtime_nsec)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: nanoseconds out of range")};
}
struct timespec ts[2]{};
ts[0].tv_sec = static_cast<time_t>(atime_sec);
ts[0].tv_nsec = static_cast<long>(atime_nsec);
ts[1].tv_sec = static_cast<time_t>(mtime_sec);
ts[1].tv_nsec = static_cast<long>(mtime_nsec);
if (::utimensat(AT_FDCWD, path.c_str(), ts, AT_SYMLINK_NOFOLLOW) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::set_timestamps_nofollow: utimensat failed for '{}'",
path.string()),
err)};
}
return {};
#else
(void)path;
(void)atime_sec;
(void)atime_nsec;
(void)mtime_sec;
(void)mtime_nsec;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::set_timestamps_nofollow: unsupported platform")};
#endif
}
/// Set canonical modification and access timestamps (default UNIX epoch 0)
/// without following symlinks (`utimensat(..., AT_SYMLINK_NOFOLLOW)`).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::int64_t unix_seconds = 0,
std::int32_t nanoseconds = 0)
{
return set_timestamps_nofollow(
path, unix_seconds, nanoseconds, unix_seconds, nanoseconds);
}
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::chrono::sys_seconds tp)
{
return set_canonical_mtime(path, tp.time_since_epoch().count(), 0);
}
} // namespace Void::FileSystem
+7
View File
@@ -116,6 +116,7 @@ public:
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] bool process_group_alive() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
@@ -201,4 +202,10 @@ private:
const std::vector<std::string>& arguments,
bool close_extra_fds);
/// Opt the current process into Linux PR_SET_CHILD_SUBREAPER so orphaned
/// descendant processes in spawned process groups reparent to this process
/// and can be reaped directly via waitpid(-pgid, ...).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
enable_subreaper() noexcept;
} // namespace Void::Process
+185 -5
View File
@@ -1,10 +1,190 @@
#pragma once
namespace Void::Testing {
#include <Void/Testing/Config.hpp>
#include <Void/Testing/Detail/Registry.hpp>
// Aliases to void so users can omit return statements safely
// and avoid compiler warnings/errors. Perfectly matches std::function<void()>.
using Test = void;
using DisabledTest = void;
#include <initializer_list>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::Testing
{
// Aliases to void so users can omit return statements safely
// and avoid compiler warnings/errors. Perfectly matches
// std::function<void()>.
using Test = void;
using DisabledTest = void;
namespace Detail
{
[[nodiscard]] inline std::string
normalize_suite_label(std::string_view raw)
{
if (raw.size() >= 2 && raw.front() == '"' && raw.back() == '"') {
raw = raw.substr(1, raw.size() - 2);
}
return std::string{raw};
}
class NativeRegistrar final
{
public:
NativeRegistrar(void (*fn)(), std::string_view suite,
const char* file, int line,
std::string_view name,
std::initializer_list<const char*> tags = {},
bool disabled = false,
std::string_view skip_reason = {})
{
std::vector<std::string> tag_vec;
tag_vec.reserve(tags.size());
for (const char* t : tags) {
if (t != nullptr) {
tag_vec.emplace_back(t);
}
}
Registry::instance().add(TestCase{
.run = fn,
.name = std::string{name},
.suite = normalize_suite_label(suite),
.file = file != nullptr ? file : "",
.line = line,
.disabled = disabled,
.skip_reason = std::string{skip_reason},
.tags = std::move(tag_vec),
});
}
};
template <typename FixtureT> class NativeFixtureRegistrar final
{
public:
NativeFixtureRegistrar(void (*fn)(FixtureT&),
std::string_view suite,
const char* file, int line,
std::string_view name,
std::initializer_list<const char*> tags = {},
bool disabled = false,
std::string_view skip_reason = {})
{
std::vector<std::string> tag_vec;
tag_vec.reserve(tags.size());
for (const char* t : tags) {
if (t != nullptr) {
tag_vec.emplace_back(t);
}
}
Registry::instance().add(TestCase{
.run =
[fn]() {
FixtureT fixture{};
if constexpr (requires { fixture.setup(); }) {
fixture.setup();
}
try {
fn(fixture);
} catch (...) {
if constexpr (requires {
fixture.teardown();
}) {
fixture.teardown();
}
throw;
}
if constexpr (requires { fixture.teardown(); }) {
fixture.teardown();
}
},
.name = std::string{name},
.suite = normalize_suite_label(suite),
.file = file != nullptr ? file : "",
.line = line,
.disabled = disabled,
.skip_reason = std::string{skip_reason},
.tags = std::move(tag_vec),
});
}
};
} // namespace Detail
} // namespace Void::Testing
#define VOID_TESTING_DETAIL_CAT_IMPL(a, b) a##b
#define VOID_TESTING_DETAIL_CAT(a, b) VOID_TESTING_DETAIL_CAT_IMPL(a, b)
#ifdef __COUNTER__
#define VOID_TESTING_DETAIL_NEXT_ID __COUNTER__
#else
#define VOID_TESTING_DETAIL_NEXT_ID __LINE__
#endif
#define VOID_TESTING_DETAIL_DEFINE_TEST(suite_expr, test_name, disabled_flag, \
skip_msg, uid, ...) \
static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)(); \
namespace \
{ \
[[maybe_unused]] const ::Void::Testing::Detail::NativeRegistrar \
VOID_TESTING_DETAIL_CAT(_void_native_test_reg_, uid){ \
&VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid), \
(suite_expr), \
__FILE__, \
__LINE__, \
#test_name, \
{__VA_ARGS__}, \
(disabled_flag), \
(skip_msg)}; \
} \
static void VOID_TESTING_DETAIL_CAT(_void_native_test_fn_, uid)()
#define VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, test_name, \
disabled_flag, skip_msg, uid) \
static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \
fixture_type&); \
namespace \
{ \
[[maybe_unused]] const ::Void::Testing::Detail::NativeFixtureRegistrar< \
fixture_type> \
VOID_TESTING_DETAIL_CAT(_void_native_fx_reg_, uid){ \
&VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid), \
#fixture_type, \
__FILE__, \
__LINE__, \
#test_name, \
{}, \
(disabled_flag), \
(skip_msg)}; \
} \
static void VOID_TESTING_DETAIL_CAT(_void_native_fx_fn_, uid)( \
[[maybe_unused]] fixture_type& fixture)
/// Declare a self-registering test case with zero CMake scanner dependency.
/// Symbols are internal-linkage and counter-disambiguated so files sharing the
/// same basename in different subdirectories link cleanly together.
#define VOID_TEST(suite, name) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID)
/// Same as VOID_TEST, taking tags (string literals) after `name`.
#define VOID_TEST_TAGGED(suite, name, ...) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID, __VA_ARGS__)
/// Declare a skipped/disabled self-registering test case.
#define VOID_TEST_DISABLED(suite, name, reason) \
VOID_TESTING_DETAIL_DEFINE_TEST(#suite, name, true, (reason), \
VOID_TESTING_DETAIL_NEXT_ID)
/// Declare a self-registering fixture test. The fixture instance is bound as
/// `fixture` inside the test body, with optional setup()/teardown() hooks.
#define VOID_TEST_FIXTURE(fixture_type, name) \
VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, false, "", \
VOID_TESTING_DETAIL_NEXT_ID)
#define VOID_TEST_FIXTURE_DISABLED(fixture_type, name, reason) \
VOID_TESTING_DETAIL_DEFINE_FIXTURE_TEST(fixture_type, name, true, (reason), \
VOID_TESTING_DETAIL_NEXT_ID)
+202 -9
View File
@@ -1,11 +1,15 @@
#pragma once
#include <Void/TestingMock/Matcher.hpp>
#include <Void/TestingMock/Session.hpp>
#include <concepts>
#include <cstddef>
#include <format>
#include <functional>
#include <limits>
#include <memory>
#include <optional>
#include <source_location>
#include <string>
#include <string_view>
@@ -24,8 +28,8 @@ namespace Void::TestingMock::Detail
using MatcherTuple =
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
/// Move-only function — supports unique_ptr-capturing lambdas
/// and other move-only callables.
/// Move-only function — supports unique_ptr-capturing lambdas,
/// move-only arguments, and move-only return values.
using Action = std::move_only_function<R(Args...)>;
Expectation(MatcherTuple matchers, std::source_location loc)
@@ -34,52 +38,200 @@ namespace Void::TestingMock::Detail
}
template <typename U = R>
requires(!std::is_void_v<U> && std::same_as<U, R>)
requires(!std::is_void_v<U> && std::same_as<U, R> &&
std::copy_constructible<U>)
Expectation& returns(U value)
{
m_once_action = false;
m_action = [val = std::move(value)](Args...) mutable -> R {
return val;
};
return *this;
}
/// Return a move-only (or copyable) value once, moving it out on
/// the reserved invocation. Automatically sets times(1).
template <typename U = R>
requires(!std::is_void_v<U> && std::convertible_to<U, R>)
Expectation& returns_once(U&& value)
{
m_once_action = true;
m_action = [val = std::forward<U>(value)](Args...) mutable -> R {
return std::move(val);
};
return times(1);
}
template <typename F>
requires std::invocable<F&, Args...>
Expectation& invokes(F action)
{
m_once_action = false;
m_action = std::move(action);
return *this;
}
/// Transfer a one-shot move-only callable to the single reserved
/// invocation. Automatically sets times(1).
template <typename F>
requires std::invocable<F&, Args...>
Expectation& invokes_once(F action)
{
m_once_action = true;
m_action = std::move(action);
return times(1);
}
Expectation& times(int n)
{
m_prohibited = (n == 0);
m_min_calls = n;
m_max_calls = n;
sync_sequence_bounds();
return *this;
}
Expectation& once() { return times(1); }
bool matches(Args... args) const
/// Explicit prohibition checked before ordinary expectations.
Expectation& never()
{
m_prohibited = true;
m_min_calls = 0;
m_max_calls = 0;
sync_sequence_bounds();
return *this;
}
Expectation& at_least(int n)
{
m_prohibited = false;
m_min_calls = n;
m_max_calls = std::numeric_limits<int>::max();
sync_sequence_bounds();
return *this;
}
Expectation& at_most(int n)
{
m_prohibited = (n == 0);
m_min_calls = 0;
m_max_calls = n;
sync_sequence_bounds();
return *this;
}
Expectation& between(int min_calls, int max_calls)
{
m_prohibited = (min_calls == 0 && max_calls == 0);
m_min_calls = min_calls;
m_max_calls = max_calls;
sync_sequence_bounds();
return *this;
}
Expectation& in_sequence(Sequence& seq)
{
m_seq_handle = seq.add_step(m_min_calls, m_max_calls);
return *this;
}
[[nodiscard]] bool valid_bounds() const noexcept
{
return m_min_calls >= 0 && m_max_calls >= 0 &&
m_min_calls <= m_max_calls;
}
[[nodiscard]] std::size_t max_matcher_depth() const noexcept
{
return max_depth_impl(std::index_sequence_for<Args...>{});
}
[[nodiscard]] bool is_prohibited() const noexcept
{
return m_prohibited;
}
[[nodiscard]] bool is_once_action() const noexcept
{
return m_once_action;
}
/// Inspect arguments by const reference without copying/moving.
[[nodiscard]] bool matches(const Args&... args) const
{
return match_impl(args..., std::index_sequence_for<Args...>{});
}
R execute(Args... args)
[[nodiscard]] bool sequence_eligible() const
{
if (!m_seq_handle.has_value() ||
m_seq_handle->seq == nullptr) {
return true;
}
return m_seq_handle->seq->is_eligible(m_seq_handle->index);
}
/// Attempt to reserve one call slot (and sequence position if any).
/// Must be called under the MockFunction reservation lock.
[[nodiscard]] bool try_reserve()
{
if (m_prohibited || m_call_count >= m_max_calls) {
return false;
}
if (m_seq_handle.has_value() && m_seq_handle->seq != nullptr) {
if (!m_seq_handle->seq->try_reserve(m_seq_handle->index)) {
return false;
}
}
++m_call_count;
return true;
}
/// Transfer one-shot action out upon reservation.
[[nodiscard]] Action take_once_action() noexcept
{
return std::move(m_action);
}
R execute(Args&&... args)
{
if (!m_action) {
if constexpr (std::is_same_v<R, void>) {
return;
} else {
} else if constexpr (std::is_default_constructible_v<R>) {
return R{};
} else {
throw InvocationAbortException(
"TestingMock: expectation matched without an "
"action for non-default-constructible return type");
}
}
return m_action(args...);
return m_action(std::forward<Args>(args)...);
}
static R execute_action(Action& action, Args&&... args)
{
if (!action) {
if constexpr (std::is_same_v<R, void>) {
return;
} else if constexpr (std::is_default_constructible_v<R>) {
return R{};
} else {
throw InvocationAbortException(
"TestingMock: expectation matched without an "
"action for non-default-constructible return type");
}
}
return action(std::forward<Args>(args)...);
}
void record_call() { ++m_call_count; }
bool is_saturated() const { return m_call_count >= m_max_calls; }
[[nodiscard]] bool is_saturated() const noexcept
{
return m_call_count >= m_max_calls;
}
void verify(std::string_view func_name)
{
@@ -91,6 +243,25 @@ namespace Void::TestingMock::Detail
}
}
void collect_verification(std::string_view func_name,
Verification& out) const
{
if (m_call_count < m_min_calls) {
out.unmet.push_back(std::format(
"unsatisfied expectation on {}: {} — {}/{} calls ({}:{})",
func_name, describe_matchers(), m_call_count,
m_min_calls, m_location.file_name(),
m_location.line()));
}
if (m_call_count > m_max_calls) {
out.excess.push_back(std::format(
"excess calls on {}: {} — {}/{} calls ({}:{})",
func_name, describe_matchers(), m_call_count,
m_max_calls, m_location.file_name(),
m_location.line()));
}
}
// -------- accessors used by failure-message construction --------
[[nodiscard]] int call_count() const noexcept
@@ -98,6 +269,8 @@ namespace Void::TestingMock::Detail
return m_call_count;
}
[[nodiscard]] int min_calls() const noexcept { return m_min_calls; }
[[nodiscard]] int max_calls() const noexcept { return m_max_calls; }
[[nodiscard]] std::source_location location() const noexcept
@@ -119,13 +292,33 @@ namespace Void::TestingMock::Detail
int m_min_calls{1};
int m_max_calls{1};
int m_call_count{0};
bool m_prohibited{false};
bool m_once_action{false};
std::optional<Sequence::StepHandle> m_seq_handle{};
void sync_sequence_bounds()
{
if (m_seq_handle.has_value() && m_seq_handle->seq != nullptr) {
m_seq_handle->seq->update_step_bounds(
m_seq_handle->index, m_min_calls, m_max_calls);
}
}
template <std::size_t... Is>
bool match_impl(Args... args, std::index_sequence<Is...>) const
bool match_impl(const Args&... args,
std::index_sequence<Is...>) const
{
return (std::get<Is>(m_matchers).matches(args) && ...);
}
template <std::size_t... Is>
std::size_t max_depth_impl(std::index_sequence<Is...>) const noexcept
{
std::size_t d = 0;
((d = std::max(d, std::get<Is>(m_matchers).depth())), ...);
return d;
}
template <std::size_t... Is>
std::string describe_impl(std::index_sequence<Is...>) const
{
+349 -5
View File
@@ -3,15 +3,20 @@
#include <Void/Testing/Assert.hpp>
#include <concepts>
#include <cstddef>
#include <format>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::TestingMock
{
inline constexpr std::size_t kMaxMatcherDepth = 32;
template <typename T> class Matcher
{
public:
@@ -19,6 +24,10 @@ namespace Void::TestingMock
virtual ~Matcher() = default;
virtual bool matches(const T& value) const = 0;
virtual std::string describe() const = 0;
[[nodiscard]] virtual std::size_t depth() const noexcept
{
return 1;
}
};
// ---------------------------------------------------------------------
@@ -42,6 +51,29 @@ namespace Void::TestingMock
}
};
template <typename T> class NeMatcher : public Matcher<T>
{
T m_unexpected;
public:
explicit NeMatcher(T unexpected)
: m_unexpected(std::move(unexpected))
{
}
bool matches(const T& v) const override
{
return v != m_unexpected;
}
std::string describe() const override
{
return std::format("Ne({})",
Void::Testing::Detail::repr(m_unexpected));
}
};
template <typename T> class AnyMatcher : public Matcher<T>
{
public:
@@ -171,6 +203,29 @@ namespace Void::TestingMock
}
};
template <typename T> class EndsWithMatcher : public Matcher<T>
{
std::string m_suffix;
public:
explicit EndsWithMatcher(std::string suffix)
: m_suffix(std::move(suffix))
{
}
bool matches(const T& v) const override
{
const std::string_view sv{v};
return sv.ends_with(m_suffix);
}
std::string describe() const override
{
return std::format("EndsWith(\"{}\")", m_suffix);
}
};
template <typename T> class ContainsMatcher : public Matcher<T>
{
std::string m_needle;
@@ -194,6 +249,155 @@ namespace Void::TestingMock
}
};
template <typename T> class IsNullMatcher : public Matcher<T>
{
public:
bool matches(const T& v) const override { return v == nullptr; }
std::string describe() const override { return "IsNull()"; }
};
template <typename T> class NotNullMatcher : public Matcher<T>
{
public:
bool matches(const T& v) const override { return v != nullptr; }
std::string describe() const override { return "NotNull()"; }
};
template <typename T> class NotMatcher : public Matcher<T>
{
std::shared_ptr<const Matcher<T>> m_inner;
std::size_t m_depth{2};
public:
explicit NotMatcher(std::shared_ptr<const Matcher<T>> inner)
: m_inner(std::move(inner)),
m_depth(m_inner ? (m_inner->depth() + 1U) : 1U)
{
}
bool matches(const T& v) const override
{
return m_inner ? !m_inner->matches(v) : false;
}
std::string describe() const override
{
if (m_depth > kMaxMatcherDepth) {
return "Not(<depth-limit>)";
}
return std::format("Not({})",
m_inner ? m_inner->describe() : "<null>");
}
[[nodiscard]] std::size_t depth() const noexcept override
{
return m_depth;
}
};
template <typename T> class AllOfMatcher : public Matcher<T>
{
std::vector<std::shared_ptr<const Matcher<T>>> m_matchers;
std::size_t m_depth{2};
public:
explicit AllOfMatcher(
std::vector<std::shared_ptr<const Matcher<T>>> matchers)
: m_matchers(std::move(matchers))
{
std::size_t max_child = 0;
for (const auto& m : m_matchers) {
if (m && m->depth() > max_child) {
max_child = m->depth();
}
}
m_depth = max_child + 1U;
}
bool matches(const T& v) const override
{
for (const auto& m : m_matchers) {
if (!m || !m->matches(v)) {
return false;
}
}
return true;
}
std::string describe() const override
{
if (m_depth > kMaxMatcherDepth) {
return "AllOf(<depth-limit>)";
}
std::string out{"AllOf("};
for (std::size_t i = 0; i < m_matchers.size(); ++i) {
if (i > 0) out += ", ";
out += m_matchers[i] ? m_matchers[i]->describe() : "<null>";
}
out += ")";
return out;
}
[[nodiscard]] std::size_t depth() const noexcept override
{
return m_depth;
}
};
template <typename T> class AnyOfMatcher : public Matcher<T>
{
std::vector<std::shared_ptr<const Matcher<T>>> m_matchers;
std::size_t m_depth{2};
public:
explicit AnyOfMatcher(
std::vector<std::shared_ptr<const Matcher<T>>> matchers)
: m_matchers(std::move(matchers))
{
std::size_t max_child = 0;
for (const auto& m : m_matchers) {
if (m && m->depth() > max_child) {
max_child = m->depth();
}
}
m_depth = max_child + 1U;
}
bool matches(const T& v) const override
{
for (const auto& m : m_matchers) {
if (m && m->matches(v)) {
return true;
}
}
return false;
}
std::string describe() const override
{
if (m_depth > kMaxMatcherDepth) {
return "AnyOf(<depth-limit>)";
}
std::string out{"AnyOf("};
for (std::size_t i = 0; i < m_matchers.size(); ++i) {
if (i > 0) out += ", ";
out += m_matchers[i] ? m_matchers[i]->describe() : "<null>";
}
out += ")";
return out;
}
[[nodiscard]] std::size_t depth() const noexcept override
{
return m_depth;
}
};
// ---------------------------------------------------------------------
// Factory functions
// ---------------------------------------------------------------------
@@ -203,6 +407,11 @@ namespace Void::TestingMock
return std::make_unique<EqMatcher<T>>(std::move(v));
}
template <typename T> auto Ne(T v)
{
return std::make_unique<NeMatcher<T>>(std::move(v));
}
template <typename T> auto _() { return std::make_unique<AnyMatcher<T>>(); }
template <typename T> auto Lt(T v)
@@ -243,37 +452,172 @@ namespace Void::TestingMock
return std::make_unique<StartsWithMatcher<T>>(std::move(prefix));
}
template <typename T = std::string> auto EndsWith(std::string suffix)
{
return std::make_unique<EndsWithMatcher<T>>(std::move(suffix));
}
template <typename T = std::string> auto Contains(std::string needle)
{
return std::make_unique<ContainsMatcher<T>>(std::move(needle));
}
template <typename T> auto IsNull()
{
return std::make_unique<IsNullMatcher<T>>();
}
template <typename T> auto NotNull()
{
return std::make_unique<NotNullMatcher<T>>();
}
template <typename T, typename Derived>
requires std::derived_from<Derived, Matcher<T>>
std::unique_ptr<Matcher<T>> Not(std::unique_ptr<Derived> inner)
{
return std::make_unique<NotMatcher<T>>(
std::shared_ptr<const Matcher<T>>(std::move(inner)));
}
template <typename Derived>
auto Not(std::unique_ptr<Derived> inner)
{
// Extract T from Matcher<T> via helper overload below if needed.
return std::unique_ptr<Derived>{std::move(inner)};
}
namespace Detail
{
template <typename T> struct MatcherValueType;
template <typename T> struct MatcherValueType<Matcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<EqMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<NeMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<AnyMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<LtMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<LeMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<GtMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<GeMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<RangeMatcher<T>> {
using type = T;
};
template <typename T, typename Fn>
struct MatcherValueType<PredMatcher<T, Fn>> {
using type = T;
};
template <typename T> struct MatcherValueType<StartsWithMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<EndsWithMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<ContainsMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<IsNullMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<NotNullMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<NotMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<AllOfMatcher<T>> {
using type = T;
};
template <typename T> struct MatcherValueType<AnyOfMatcher<T>> {
using type = T;
};
} // namespace Detail
template <typename M>
requires requires { typename Detail::MatcherValueType<M>::type; }
auto NotOf(std::unique_ptr<M> inner)
{
using T = typename Detail::MatcherValueType<M>::type;
return std::make_unique<NotMatcher<T>>(
std::shared_ptr<const Matcher<T>>(std::move(inner)));
}
template <typename T, typename... Ms>
std::unique_ptr<Matcher<T>> AllOf(std::unique_ptr<Ms>... matchers)
{
std::vector<std::shared_ptr<const Matcher<T>>> vec;
vec.reserve(sizeof...(Ms));
(vec.emplace_back(std::shared_ptr<const Matcher<T>>(std::move(matchers))),
...);
return std::make_unique<AllOfMatcher<T>>(std::move(vec));
}
template <typename T, typename... Ms>
std::unique_ptr<Matcher<T>> AnyOf(std::unique_ptr<Ms>... matchers)
{
std::vector<std::shared_ptr<const Matcher<T>>> vec;
vec.reserve(sizeof...(Ms));
(vec.emplace_back(std::shared_ptr<const Matcher<T>>(std::move(matchers))),
...);
return std::make_unique<AnyOfMatcher<T>>(std::move(vec));
}
// ---------------------------------------------------------------------
// MatcherHolder — owns a Matcher<T> or wraps an exact value as Eq
// MatcherHolder — owns a shared immutable Matcher<T> or exact Eq value
// ---------------------------------------------------------------------
template <typename T> class MatcherHolder
{
std::unique_ptr<Matcher<T>> m_matcher;
std::shared_ptr<const Matcher<T>> m_matcher;
public:
MatcherHolder() : m_matcher(std::make_unique<AnyMatcher<T>>()) {}
MatcherHolder() : m_matcher(std::make_shared<AnyMatcher<T>>()) {}
MatcherHolder(std::unique_ptr<Matcher<T>> m)
template <typename Derived>
requires std::derived_from<Derived, Matcher<T>>
MatcherHolder(std::unique_ptr<Derived> m)
: m_matcher(std::shared_ptr<const Matcher<T>>(std::move(m)))
{
}
MatcherHolder(std::shared_ptr<const Matcher<T>> m)
: m_matcher(std::move(m))
{
}
template <typename U = T>
requires(std::same_as<std::decay_t<U>, T> &&
std::equality_comparable<T> && std::movable<T>)
MatcherHolder(T exact_value)
: m_matcher(
std::make_unique<EqMatcher<T>>(std::move(exact_value)))
std::make_shared<EqMatcher<T>>(std::move(exact_value)))
{
}
bool matches(const T& v) const { return m_matcher->matches(v); }
std::string describe() const { return m_matcher->describe(); }
[[nodiscard]] std::size_t depth() const noexcept
{
return m_matcher ? m_matcher->depth() : 0;
}
};
} // namespace Void::TestingMock
+347 -15
View File
@@ -3,12 +3,18 @@
#include <Void/Testing/Assert.hpp>
#include <Void/TestingMock/Expectation.hpp>
#include <Void/TestingMock/Mock.hpp>
#include <Void/TestingMock/Session.hpp>
#include <condition_variable>
#include <cstddef>
#include <exception>
#include <format>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::TestingMock
@@ -17,7 +23,8 @@ namespace Void::TestingMock
template <typename> class MockFunction;
template <typename R, typename... Args>
class MockFunction<R(Args...)> : public Detail::MockFunctionBase
class MockFunction<R(Args...)> : public Detail::MockFunctionBase,
public Detail::SessionParticipant
{
using Expectation = Detail::Expectation<R(Args...)>;
@@ -39,13 +46,84 @@ namespace Void::TestingMock
owner.register_function(this);
}
~MockFunction() override { verify(); }
/// Session-backed constructor — registers dynamically with
/// `session` via RAII RegistrationToken and uses action-outside-lock
/// reservation with bounded structured diagnostics.
MockFunction(MockSession& session,
std::string name = "unnamed_mock")
: m_name(std::move(name)), m_session_state(session.state()),
m_token(session.register_participant(*this))
{
}
~MockFunction() override
{
if (m_session_state) {
m_token.unregister();
} else {
verify();
}
}
MockFunction(const MockFunction&) = delete;
MockFunction& operator=(const MockFunction&) = delete;
MockFunction(MockFunction&&) = delete;
MockFunction& operator=(MockFunction&&) = delete;
/// Checked expectation registration for session-backed mocks:
/// rejects mutations after `freeze()` and enforces `MockLimits`.
template <typename... MArgs>
[[nodiscard]] Void::Result::Result<Expectation*>
try_expect(std::source_location loc, MArgs&&... matchers)
{
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
if (m_session_state->frozen || m_session_state->closed) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidState,
"TestingMock: cannot register expectation on "
"frozen or closed session")};
}
if (sizeof...(MArgs) >
m_session_state->limits.max_matchers) {
return std::unexpected{make_mock_error(
MockErrorCode::LimitExceeded,
"TestingMock: matcher count exceeds MockLimits")};
}
if (m_session_state->expectation_count >=
m_session_state->limits.max_expectations) {
return std::unexpected{make_mock_error(
MockErrorCode::LimitExceeded,
"TestingMock: expectation count exceeds "
"MockLimits")};
}
++m_session_state->expectation_count;
}
auto exp = std::make_shared<Expectation>(
typename Expectation::MatcherTuple{
MatcherHolder<std::decay_t<Args>>(
std::forward<MArgs>(matchers))...},
loc);
if (exp->max_matcher_depth() > kMaxMatcherDepth) {
return std::unexpected{make_mock_error(
MockErrorCode::LimitExceeded,
"TestingMock: matcher nesting depth exceeds 32")};
}
std::lock_guard lock{m_mutex};
m_expectations.push_back(exp);
return exp.get();
}
template <typename... MArgs>
[[nodiscard]] Void::Result::Result<Expectation*>
try_expect(MArgs&&... matchers)
{
return try_expect(std::source_location::current(),
std::forward<MArgs>(matchers)...);
}
template <typename... MArgs>
Expectation& expect(std::source_location loc, MArgs&&... matchers)
{
@@ -54,6 +132,11 @@ namespace Void::TestingMock
MatcherHolder<std::decay_t<Args>>(
std::forward<MArgs>(matchers))...},
loc);
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
++m_session_state->expectation_count;
}
std::lock_guard lock{m_mutex};
m_expectations.push_back(exp);
return *exp;
}
@@ -67,37 +150,276 @@ namespace Void::TestingMock
R operator()(Args... args)
{
std::lock_guard lock{m_mutex};
for (auto& exp : m_expectations) {
if (!exp->is_saturated() && exp->matches(args...)) {
exp->record_call();
return exp->execute(args...);
// 1. Check session concurrency/admission & increment in-flight.
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
if (m_session_state->closed) {
m_session_state->append_bounded(
m_session_state->report.unmatched,
std::format("call to {}({}) after session closed",
m_name, render_args(args...)));
return handle_unmatched_return("session closed");
}
if (m_session_state->frozen &&
m_session_state->concurrency ==
Concurrency::SingleThread &&
std::this_thread::get_id() !=
m_session_state->owner_thread) {
const std::string err = std::format(
"concurrent cross-thread call to {}({}) under "
"Concurrency::SingleThread",
m_name, render_args(args...));
m_session_state->append_bounded(
m_session_state->report.threading_errors, err);
return handle_unmatched_return(err);
}
++m_session_state->in_flight_calls;
}
struct InFlightGuard {
MockFunction* self;
bool local_admitted{false};
~InFlightGuard() noexcept
{
if (local_admitted) {
std::lock_guard lock{self->m_mutex};
if (self->m_local_in_flight > 0) {
--self->m_local_in_flight;
}
if (self->m_local_in_flight == 0) {
self->m_local_cv.notify_all();
}
}
if (self->m_session_state) {
std::lock_guard slock{
self->m_session_state->mutex};
if (self->m_session_state->in_flight_calls >
0) {
--self->m_session_state->in_flight_calls;
}
if (self->m_session_state->in_flight_calls ==
0) {
self->m_session_state->cv.notify_all();
}
}
}
} guard{this, false};
// 2. Snapshot candidate expectations under short lock.
std::vector<std::shared_ptr<Expectation>> candidates;
{
std::lock_guard lock{m_mutex};
if (m_stopped) {
const std::string err = std::format(
"call to {}({}) after mock unregistered", m_name,
render_args(args...));
record_unmatched_diagnostic(err);
return handle_unmatched_return(err);
}
++m_local_in_flight;
guard.local_admitted = true;
candidates = m_expectations;
}
// 3. Evaluate explicit prohibitions (never()) FIRST outside
// lock so zero-count prohibitions cannot be silently skipped.
for (const auto& exp : candidates) {
if (!exp->is_prohibited()) {
continue;
}
bool matched = false;
try {
matched = exp->matches(args...);
} catch (const std::exception& e) {
record_matcher_failure(e.what(), args...);
return handle_unmatched_return(e.what());
} catch (...) {
record_matcher_failure("unknown matcher exception",
args...);
return handle_unmatched_return("matcher exception");
}
if (matched) {
const std::string msg = std::format(
"prohibited call (never()) matched on {}({}): {}",
m_name, render_args(args...),
exp->describe_matchers());
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->append_bounded(
m_session_state->report.prohibited, msg);
m_session_state->record_event_locked(msg);
} else {
Void::Testing::fail(msg);
}
return handle_unmatched_return(msg);
}
}
Void::Testing::fail(build_unmatched_message(args...));
if constexpr (!std::is_same_v<R, void>) {
return R{};
// 4. Evaluate ordinary matchers outside lock, then reacquire
// lock to reserve the winning unsaturated candidate. Retry
// remaining candidates if another thread saturated it first.
std::shared_ptr<Expectation> reserved;
typename Expectation::Action once_action;
bool use_once_action = false;
for (const auto& exp : candidates) {
if (exp->is_prohibited()) {
continue;
}
bool matched = false;
try {
matched = exp->matches(args...);
} catch (const std::exception& e) {
record_matcher_failure(e.what(), args...);
return handle_unmatched_return(e.what());
} catch (...) {
record_matcher_failure("unknown matcher exception",
args...);
return handle_unmatched_return("matcher exception");
}
if (!matched) {
continue;
}
std::lock_guard lock{m_mutex};
if (exp->try_reserve()) {
reserved = exp;
if (exp->is_once_action()) {
once_action = exp->take_once_action();
use_once_action = true;
}
break;
}
}
if (!reserved) {
std::string msg;
{
std::lock_guard lock{m_mutex};
msg = build_unmatched_message_locked(args...);
}
record_unmatched_diagnostic(msg);
return handle_unmatched_return(msg);
}
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->record_event_locked(std::format(
"{}({}) -> matched {}", m_name, render_args(args...),
reserved->describe_matchers()));
}
// 5. Execute action strictly OUTSIDE locks so reentrant and
// concurrent actions never deadlock on MockFunction::m_mutex.
Detail::ActionDepthGuard depth_guard;
if (use_once_action) {
return Expectation::execute_action(
once_action, std::forward<Args>(args)...);
}
return reserved->execute(std::forward<Args>(args)...);
}
void verify() override
{
for (auto& exp : m_expectations) {
std::vector<std::shared_ptr<Expectation>> snap;
{
std::lock_guard lock{m_mutex};
snap = std::move(m_expectations);
m_expectations.clear();
}
for (auto& exp : snap) {
exp->verify(m_name);
}
m_expectations.clear();
}
// -------- SessionParticipant implementation --------
[[nodiscard]] Void::Result::Result<void>
validate_for_freeze() const override
{
std::lock_guard lock{m_mutex};
for (const auto& exp : m_expectations) {
if (!exp->valid_bounds()) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidRange,
std::format("TestingMock: invalid call bounds "
"(min={} > max={}) on {}",
exp->min_calls(), exp->max_calls(),
m_name))};
}
}
return {};
}
void collect_verification(Verification& out) override
{
std::lock_guard lock{m_mutex};
for (const auto& exp : m_expectations) {
exp->collect_verification(m_name, out);
}
}
void stop_admission_and_join() noexcept override
{
std::unique_lock lock{m_mutex};
m_stopped = true;
m_local_cv.wait(lock, [this] { return m_local_in_flight == 0; });
}
private:
std::string m_name;
mutable std::mutex m_mutex;
std::condition_variable m_local_cv;
std::vector<std::shared_ptr<Expectation>> m_expectations;
std::mutex m_mutex;
std::size_t m_local_in_flight{0};
bool m_stopped{false};
std::shared_ptr<Detail::SessionState> m_session_state{};
RegistrationToken m_token{};
void record_unmatched_diagnostic(const std::string& msg)
{
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->append_bounded(
m_session_state->report.unmatched, msg);
m_session_state->record_event_locked(msg);
} else {
Void::Testing::fail(msg);
}
}
void record_matcher_failure(std::string_view what,
const Args&... args)
{
const std::string msg = std::format(
"matcher threw on {}({}): {}", m_name, render_args(args...),
what);
if (m_session_state) {
std::lock_guard slock{m_session_state->mutex};
m_session_state->append_bounded(
m_session_state->report.matcher_errors, msg);
m_session_state->record_event_locked(msg);
} else {
Void::Testing::fail(msg);
}
}
R handle_unmatched_return(const std::string& msg)
{
if constexpr (std::is_same_v<R, void>) {
return;
} else if constexpr (std::is_default_constructible_v<R>) {
return R{};
} else {
throw InvocationAbortException(msg);
}
}
/// Build a multi-line error message that names the actual
/// arguments and lists every registered expectation with its
/// matcher tuple and call counts.
std::string build_unmatched_message(const Args&... args) const
std::string
build_unmatched_message_locked(const Args&... args) const
{
std::string msg =
std::format("no expectation matched call to {}({})", m_name,
@@ -115,6 +437,16 @@ namespace Void::TestingMock
return msg;
}
template <typename T>
static std::string render_one_arg(const T& a)
{
if constexpr (requires { Void::Testing::Detail::repr(a); }) {
return Void::Testing::Detail::repr(a);
} else {
return "<non-printable>";
}
}
static std::string render_args(const Args&... args)
{
std::string out;
@@ -123,7 +455,7 @@ namespace Void::TestingMock
if (!first) {
out += ", ";
}
out += Void::Testing::Detail::repr(a);
out += render_one_arg(a);
first = false;
};
(append(args), ...);
+531
View File
@@ -0,0 +1,531 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace Void::TestingMock
{
enum class MockErrorCode : std::int32_t {
None = 0,
InvalidState = 1,
LimitExceeded = 2,
InvalidRange = 3,
WouldDeadlock = 4,
ThreadingViolation = 5,
MatcherFailure = 6,
ProhibitedCall = 7,
UnmatchedCall = 8,
};
[[nodiscard]] inline Void::Result::Error
make_mock_error(MockErrorCode code, std::string message)
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case MockErrorCode::None:
kind = ErrorKind::internal;
break;
case MockErrorCode::InvalidState:
case MockErrorCode::InvalidRange:
case MockErrorCode::WouldDeadlock:
case MockErrorCode::ThreadingViolation:
kind = ErrorKind::invalid_argument;
break;
case MockErrorCode::LimitExceeded:
kind = ErrorKind::exhausted;
break;
case MockErrorCode::MatcherFailure:
case MockErrorCode::ProhibitedCall:
case MockErrorCode::UnmatchedCall:
kind = ErrorKind::conflict;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kTestingMockErrorDomain,
static_cast<std::int32_t>(code)}};
}
enum class Concurrency : std::uint8_t {
SingleThread,
ConcurrentActions,
};
struct MockLimits {
std::size_t max_expectations{1024};
std::size_t max_matchers{64};
std::size_t max_events{4096};
std::size_t max_diagnostic_bytes{4ULL * 1024 * 1024};
std::size_t max_arg_render_bytes{4ULL * 1024};
};
/// Thrown when an unmatched or prohibited invocation occurs on a mock with
/// a non-default-constructible return type, after recording the failure.
class InvocationAbortException : public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};
/// Explicit call-order group shared across one or more expectations.
/// Independent of global expectation registration order.
class Sequence final
{
public:
Sequence() = default;
Sequence(const Sequence&) = delete;
Sequence& operator=(const Sequence&) = delete;
struct StepHandle {
Sequence* seq{nullptr};
std::size_t index{0};
};
StepHandle add_step(int min_calls, int max_calls)
{
std::lock_guard lock{m_mutex};
const std::size_t idx = m_steps.size();
m_steps.push_back(Step{min_calls, max_calls, 0});
return StepHandle{this, idx};
}
void update_step_bounds(std::size_t index, int min_calls,
int max_calls)
{
std::lock_guard lock{m_mutex};
if (index < m_steps.size()) {
m_steps[index].min_calls = min_calls;
m_steps[index].max_calls = max_calls;
}
}
[[nodiscard]] bool is_eligible(std::size_t index) const
{
std::lock_guard lock{m_mutex};
if (index < m_cursor || index >= m_steps.size()) {
return false;
}
for (std::size_t j = m_cursor; j < index; ++j) {
if (m_steps[j].reserved < m_steps[j].min_calls) {
return false;
}
}
return m_steps[index].reserved < m_steps[index].max_calls;
}
[[nodiscard]] bool try_reserve(std::size_t index)
{
std::lock_guard lock{m_mutex};
if (index < m_cursor || index >= m_steps.size()) {
return false;
}
for (std::size_t j = m_cursor; j < index; ++j) {
if (m_steps[j].reserved < m_steps[j].min_calls) {
return false;
}
}
if (m_steps[index].reserved >= m_steps[index].max_calls) {
return false;
}
m_cursor = index;
++m_steps[index].reserved;
if (m_steps[index].reserved >= m_steps[index].max_calls) {
m_cursor = index + 1U;
}
return true;
}
[[nodiscard]] std::size_t cursor() const
{
std::lock_guard lock{m_mutex};
return m_cursor;
}
private:
struct Step {
int min_calls{1};
int max_calls{1};
int reserved{0};
};
mutable std::mutex m_mutex;
std::vector<Step> m_steps;
std::size_t m_cursor{0};
};
struct Verification {
std::vector<std::string> unmet{};
std::vector<std::string> excess{};
std::vector<std::string> unmatched{};
std::vector<std::string> prohibited{};
std::vector<std::string> matcher_errors{};
std::vector<std::string> threading_errors{};
std::vector<std::string> events{};
std::uint64_t total_events{0};
bool events_truncated{false};
[[nodiscard]] bool ok() const noexcept
{
return unmet.empty() && excess.empty() && unmatched.empty() &&
prohibited.empty() && matcher_errors.empty() &&
threading_errors.empty();
}
[[nodiscard]] std::string format() const
{
if (ok()) {
return std::format("MockSession OK ({} events)",
total_events);
}
std::string out = "MockSession verification failed:";
auto append_group = [&](std::string_view label,
const std::vector<std::string>& items) {
for (const auto& s : items) {
out += std::format("\n [{}] {}", label, s);
}
};
append_group("unmet", unmet);
append_group("excess", excess);
append_group("unmatched", unmatched);
append_group("prohibited", prohibited);
append_group("matcher", matcher_errors);
append_group("threading", threading_errors);
if (events_truncated) {
out += std::format("\n (event log truncated; {} total)",
total_events);
}
return out;
}
};
namespace Detail
{
inline thread_local std::size_t g_active_mock_action_depth = 0;
struct ActionDepthGuard {
ActionDepthGuard() noexcept { ++g_active_mock_action_depth; }
~ActionDepthGuard() noexcept { --g_active_mock_action_depth; }
};
class SessionParticipant
{
public:
virtual ~SessionParticipant() = default;
[[nodiscard]] virtual Void::Result::Result<void>
validate_for_freeze() const = 0;
virtual void collect_verification(Verification& out) = 0;
virtual void stop_admission_and_join() noexcept = 0;
};
struct SessionState {
MockLimits limits{};
mutable std::mutex mutex{};
std::condition_variable cv{};
bool frozen{false};
bool closed{false};
Concurrency concurrency{Concurrency::SingleThread};
std::thread::id owner_thread{std::this_thread::get_id()};
std::size_t expectation_count{0};
std::size_t in_flight_calls{0};
std::size_t diagnostic_bytes{0};
std::uint64_t next_reg_id{1};
struct RegisteredEntry {
std::uint64_t id{0};
SessionParticipant* participant{nullptr};
};
std::vector<RegisteredEntry> participants{};
Verification report{};
bool verified{false};
void append_bounded(std::vector<std::string>& vec,
std::string msg)
{
if (msg.size() > limits.max_arg_render_bytes &&
limits.max_arg_render_bytes > 16) {
msg.resize(limits.max_arg_render_bytes - 3U);
msg += "...";
}
if (diagnostic_bytes + msg.size() <=
limits.max_diagnostic_bytes) {
diagnostic_bytes += msg.size();
vec.push_back(std::move(msg));
} else {
report.events_truncated = true;
}
}
void record_event_locked(std::string ev)
{
++report.total_events;
if (limits.max_events == 0) {
report.events_truncated = true;
return;
}
if (report.events.size() < limits.max_events &&
diagnostic_bytes + ev.size() <=
limits.max_diagnostic_bytes) {
diagnostic_bytes += ev.size();
report.events.push_back(std::move(ev));
} else {
report.events_truncated = true;
// Keep bounded last sample when truncated.
if (!report.events.empty()) {
report.events.back() = std::move(ev);
}
}
}
};
} // namespace Detail
/// Move-only RAII registration handle for dynamic mocks attached to a
/// MockSession. Unregistering stops new admission and waits for in-flight
/// calls before returning so destroyed dynamic mocks cannot dangle.
class RegistrationToken final
{
public:
RegistrationToken() noexcept = default;
RegistrationToken(std::shared_ptr<Detail::SessionState> state,
std::uint64_t id,
Detail::SessionParticipant* participant) noexcept
: m_state(std::move(state)), m_id(id),
m_participant(participant)
{
}
~RegistrationToken() noexcept { unregister(); }
RegistrationToken(RegistrationToken&& other) noexcept
: m_state(std::move(other.m_state)),
m_id(std::exchange(other.m_id, 0)),
m_participant(std::exchange(other.m_participant, nullptr))
{
}
RegistrationToken& operator=(RegistrationToken&& other) noexcept
{
if (this != &other) {
unregister();
m_state = std::move(other.m_state);
m_id = std::exchange(other.m_id, 0);
m_participant = std::exchange(other.m_participant, nullptr);
}
return *this;
}
RegistrationToken(const RegistrationToken&) = delete;
RegistrationToken& operator=(const RegistrationToken&) = delete;
[[nodiscard]] bool active() const noexcept
{
return m_state != nullptr && m_id != 0;
}
void unregister() noexcept
{
if (!m_state || m_id == 0) {
return;
}
Detail::SessionParticipant* p =
std::exchange(m_participant, nullptr);
const std::uint64_t id = std::exchange(m_id, 0);
auto state = std::move(m_state);
if (p != nullptr) {
p->stop_admission_and_join();
}
std::lock_guard lock{state->mutex};
std::erase_if(state->participants,
[id](const auto& e) { return e.id == id; });
}
private:
std::shared_ptr<Detail::SessionState> m_state{};
std::uint64_t m_id{0};
Detail::SessionParticipant* m_participant{nullptr};
};
/// Explicit mock lifecycle controller owning limits, freeze state,
/// concurrency policy, dynamic registration tokens, and idempotent
/// structured verification.
class MockSession final
{
public:
explicit MockSession(MockLimits limits = {})
: m_state(std::make_shared<Detail::SessionState>())
{
m_state->limits = limits;
m_state->owner_thread = std::this_thread::get_id();
}
~MockSession() noexcept
{
if (m_state && Detail::g_active_mock_action_depth == 0) {
(void)verify_and_close();
}
}
MockSession(const MockSession&) = delete;
MockSession& operator=(const MockSession&) = delete;
MockSession(MockSession&&) noexcept = default;
MockSession& operator=(MockSession&&) noexcept = default;
[[nodiscard]] const MockLimits& limits() const noexcept
{
return m_state->limits;
}
[[nodiscard]] bool is_frozen() const
{
std::lock_guard lock{m_state->mutex};
return m_state->frozen;
}
[[nodiscard]] bool is_closed() const
{
std::lock_guard lock{m_state->mutex};
return m_state->closed;
}
[[nodiscard]] RegistrationToken
register_participant(Detail::SessionParticipant& participant)
{
std::lock_guard lock{m_state->mutex};
const std::uint64_t id = m_state->next_reg_id++;
m_state->participants.push_back({id, &participant});
return RegistrationToken{m_state, id, &participant};
}
/// Freeze expectation registration and lock in the concurrency mode.
[[nodiscard]] Void::Result::Result<void>
freeze(Concurrency mode = Concurrency::SingleThread)
{
std::vector<Detail::SessionParticipant*> snapshot;
{
std::lock_guard lock{m_state->mutex};
if (m_state->closed) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidState,
"TestingMock::MockSession: session already closed")};
}
if (m_state->frozen) {
return std::unexpected{make_mock_error(
MockErrorCode::InvalidState,
"TestingMock::MockSession: session already frozen")};
}
for (const auto& e : m_state->participants) {
if (e.participant != nullptr) {
snapshot.push_back(e.participant);
}
}
}
for (auto* p : snapshot) {
auto vr = p->validate_for_freeze();
if (!vr.has_value()) {
return vr;
}
}
{
std::lock_guard lock{m_state->mutex};
m_state->frozen = true;
m_state->concurrency = mode;
m_state->owner_thread = std::this_thread::get_id();
}
return {};
}
/// Stop admission, wait for active calls to finish, and return an
/// idempotent structured Verification report.
[[nodiscard]] Void::Result::Result<Verification> verify_and_close()
{
if (Detail::g_active_mock_action_depth > 0) {
return std::unexpected{make_mock_error(
MockErrorCode::WouldDeadlock,
"TestingMock::MockSession::verify_and_close cannot be "
"called synchronously from inside an active mock "
"action")};
}
std::vector<Detail::SessionParticipant*> snapshot;
{
std::unique_lock lock{m_state->mutex};
if (m_state->verified) {
return m_state->report;
}
m_state->closed = true;
m_state->frozen = true;
for (const auto& e : m_state->participants) {
if (e.participant != nullptr) {
snapshot.push_back(e.participant);
}
}
}
for (auto* p : snapshot) {
p->stop_admission_and_join();
}
std::unique_lock lock{m_state->mutex};
m_state->cv.wait(
lock, [&] { return m_state->in_flight_calls == 0; });
if (!m_state->verified) {
for (auto* p : snapshot) {
p->collect_verification(m_state->report);
}
m_state->verified = true;
}
return m_state->report;
}
[[nodiscard]] const std::shared_ptr<Detail::SessionState>&
state() const noexcept
{
return m_state;
}
private:
std::shared_ptr<Detail::SessionState> m_state;
};
[[nodiscard]] inline Void::Result::Result<void>
freeze(MockSession& session,
Concurrency mode = Concurrency::SingleThread)
{
return session.freeze(mode);
}
[[nodiscard]] inline Void::Result::Result<Verification>
verify_and_close(MockSession& session)
{
return session.verify_and_close();
}
} // namespace Void::TestingMock
+94 -23
View File
@@ -438,6 +438,54 @@ namespace Void::Semver
using Clause = std::vector<Comparator>;
std::vector<Clause> m_alternatives;
struct PartialVersion {
Version version{};
int components{0};
};
[[nodiscard]] static std::optional<PartialVersion>
parse_partial(std::string_view token)
{
if (token.empty()) {
return std::nullopt;
}
if (token.find('-') != std::string_view::npos ||
token.find('+') != std::string_view::npos) {
const auto full = parse_strict(token);
if (!full) {
return std::nullopt;
}
return PartialVersion{*full, 3};
}
const auto first_dot = token.find('.');
if (first_dot == std::string_view::npos) {
unsigned major = 0;
if (!Detail::parse_component(token, major)) {
return std::nullopt;
}
return PartialVersion{
Version{.major = major, .minor = 0, .patch = 0}, 1};
}
const auto second_dot = token.find('.', first_dot + 1);
if (second_dot == std::string_view::npos) {
unsigned major = 0;
unsigned minor = 0;
if (!Detail::parse_component(token.substr(0, first_dot),
major) ||
!Detail::parse_component(token.substr(first_dot + 1),
minor)) {
return std::nullopt;
}
return PartialVersion{
Version{.major = major, .minor = minor, .patch = 0}, 2};
}
const auto full = parse_strict(token);
if (!full) {
return std::nullopt;
}
return PartialVersion{*full, 3};
}
[[nodiscard]] static bool append_token(Clause& clause,
std::string_view token)
{
@@ -447,53 +495,76 @@ namespace Void::Semver
if (token.starts_with('^') || token.starts_with('~')) {
const char kind = token.front();
token.remove_prefix(1);
const auto lower = parse_strict(token);
if (!lower) {
const auto partial = parse_partial(token);
if (!partial) {
return false;
}
const Version& lower = partial->version;
Version upper;
if (kind == '~') {
if (lower->minor ==
if (partial->components == 1) {
if (lower.major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else {
if (lower.minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major,
.minor = lower.minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
}
} else if (partial->components == 1) {
if (lower.major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major,
.minor = lower->minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->major > 0) {
if (lower->major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower->major + 1,
upper = Version{.major = lower.major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower->minor > 0) {
if (lower->minor ==
} else if (lower.major > 0) {
if (lower.major ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = lower.major + 1,
.minor = 0,
.patch = 0,
.pre_release = {},
.build = {}};
} else if (lower.minor > 0) {
if (lower.minor ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = 0,
.minor = lower->minor + 1,
.minor = lower.minor + 1,
.patch = 0,
.pre_release = {},
.build = {}};
} else {
if (lower->patch ==
if (lower.patch ==
std::numeric_limits<unsigned>::max()) {
return false;
}
upper = Version{.major = 0,
.minor = 0,
.patch = lower->patch + 1,
.patch = lower.patch + 1,
.pre_release = {},
.build = {}};
}
clause.push_back({Operation::GreaterEqual, *lower});
clause.push_back({Operation::GreaterEqual, lower});
clause.push_back({Operation::Less, std::move(upper)});
return true;
}
@@ -518,11 +589,11 @@ namespace Void::Semver
} else if (token.starts_with('=')) {
token.remove_prefix(1);
}
const auto version = parse_strict(token);
if (!version) {
const auto partial = parse_partial(token);
if (!partial) {
return false;
}
clause.push_back({operation, *version});
clause.push_back({operation, partial->version});
return true;
}
+148 -30
View File
@@ -1,10 +1,13 @@
#include <Void/Archive/Archive.hpp>
#include "BuiltinTar.hpp"
#include <array>
#include <atomic>
#include <cerrno>
#include <cstring>
#include <format>
#include <limits>
#include <memory>
#include <optional>
#include <set>
@@ -13,8 +16,10 @@
#include <system_error>
#include <utility>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h>
#include <archive_entry.h>
#endif
#ifndef _WIN32
#include <fcntl.h>
@@ -28,6 +33,7 @@ namespace Void::Archive
{
namespace
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using ArchiveHandle =
std::unique_ptr<archive, decltype(&archive_read_free)>;
@@ -39,6 +45,7 @@ namespace Void::Archive
"Archive::extract: {}: {}", operation,
message == nullptr ? "unknown archive error" : message)};
}
#endif
[[nodiscard]] std::optional<std::filesystem::path>
safe_relative_path(std::string_view rawPath, bool directory)
@@ -225,12 +232,14 @@ namespace Void::Archive
return {};
}
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, int rootDescriptor,
const std::filesystem::path &relative,
const std::filesystem::path &displayRoot,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted, bool executable)
extract_regular_stream(int rootDescriptor,
const std::filesystem::path &relative,
const std::filesystem::path &displayRoot,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted,
bool executable, ReadFn &&read_fn)
{
auto openedParent = open_parent_directory(
rootDescriptor, relative.parent_path(), displayRoot);
@@ -286,15 +295,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0;
for (;;) {
const auto count =
archive_read_data(reader, buffer.data(), buffer.size());
if (count == 0) {
auto chunk = read_fn(std::span{buffer});
if (!chunk.has_value()) {
return fail(chunk.error().message());
}
if (*chunk == 0) {
break;
}
if (count < 0) {
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
const auto amount = static_cast<std::uint64_t>(*chunk);
if (amount > options.maxFileBytes - fileBytes ||
amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -303,11 +311,11 @@ namespace Void::Archive
}
std::size_t written = 0;
while (written < static_cast<std::size_t>(count)) {
while (written < *chunk) {
const auto result = ::write(
descriptor.get(),
reinterpret_cast<const char *>(buffer.data()) + written,
static_cast<std::size_t>(count) - written);
*chunk - written);
if (result < 0 && errno == EINTR) {
continue;
}
@@ -448,10 +456,12 @@ namespace Void::Archive
return {};
}
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, const std::filesystem::path &path,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted)
extract_regular_stream(const std::filesystem::path &path,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted,
ReadFn &&read_fn)
{
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
@@ -486,15 +496,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0;
for (;;) {
const auto count =
archive_read_data(reader, buffer.data(), buffer.size());
if (count == 0) {
auto chunk = read_fn(std::span{buffer});
if (!chunk.has_value()) {
return fail(chunk.error().message());
}
if (*chunk == 0) {
break;
}
if (count < 0) {
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
const auto amount = static_cast<std::uint64_t>(*chunk);
if (amount > options.maxFileBytes - fileBytes ||
amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -502,7 +511,7 @@ namespace Void::Archive
"Archive::extract: extracted size exceeds policy");
}
output.write(reinterpret_cast<const char *>(buffer.data()),
count);
static_cast<std::streamsize>(*chunk));
if (!output) {
return fail("Archive::extract: write failed");
}
@@ -544,11 +553,13 @@ namespace Void::Archive
}
#endif
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
ArchiveHandle reader{archive_read_new(), &archive_read_free};
if (!reader) {
return Void::Result::fail(
"Archive::extract: cannot allocate archive reader");
}
archive_read_support_filter_gzip(reader.get());
archive_read_support_filter_zstd(reader.get());
archive_read_support_filter_none(reader.get());
archive_read_support_format_tar(reader.get());
@@ -633,14 +644,23 @@ namespace Void::Archive
return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy");
}
auto read_libarchive_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
const auto count =
archive_read_data(reader.get(), dst.data(), dst.size());
if (count < 0) {
return std::unexpected{archive_error(reader.get(), "read entry")};
}
return static_cast<std::size_t>(count);
};
#ifndef _WIN32
const bool executable = (archive_entry_perm(entry) & 0111) != 0;
auto extracted =
extract_regular(reader.get(), root->get(), *relative,
destination, options, result.bytes, executable);
auto extracted = extract_regular_stream(
root->get(), *relative, destination, options, result.bytes,
executable, read_libarchive_chunk);
#else
auto extracted =
extract_regular(reader.get(), output, options, result.bytes);
auto extracted = extract_regular_stream(
output, options, result.bytes, read_libarchive_chunk);
#endif
if (!extracted) {
return std::unexpected{extracted.error()};
@@ -648,5 +668,103 @@ namespace Void::Archive
result.bytes += *extracted;
}
return result;
#else
auto source = FileByteSource::open(archivePath);
if (!source.has_value()) {
return std::unexpected{std::move(source.error())};
}
ReadLimits limits;
limits.max_entries = options.maxEntries;
limits.max_file_bytes = options.maxFileBytes;
limits.max_total_bytes = options.maxTotalBytes;
limits.max_compressed_bytes = std::numeric_limits<std::uint64_t>::max();
Detail::BuiltinTarStream stream{
*source, limits, {}, std::nullopt,
Void::Time::SystemMonotonicClock::instance()};
if (auto opened = stream.open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
ExtractionResult result;
std::set<std::filesystem::path> seen;
for (;;) {
auto next = stream.next_entry();
if (!next.has_value()) {
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
break;
}
if (++result.entries > options.maxEntries) {
return Void::Result::fail(
"Archive::extract: entry count exceeds policy");
}
const auto &entry = **next;
if (entry.type == EntryType::Hardlink ||
entry.type == EntryType::Symlink || !entry.linkname.empty()) {
return Void::Result::fail(
"Archive::extract: links are not allowed");
}
if (entry.type != EntryType::Directory &&
entry.type != EntryType::RegularFile) {
return Void::Result::fail(
"Archive::extract: special files are not allowed");
}
const bool is_dir = (entry.type == EntryType::Directory);
auto relative = safe_relative_path(entry.path, is_dir);
if (!relative || !seen.insert(*relative).second) {
return Void::Result::fail(std::format(
"Archive::extract: unsafe or duplicate path '{}'",
entry.path));
}
#ifdef _WIN32
if (auto parents = safe_parents(root, relative->parent_path());
!parents) {
return std::unexpected{parents.error()};
}
const auto output = root / *relative;
#endif
if (is_dir) {
#ifndef _WIN32
auto created =
create_directory_entry(root->get(), *relative, destination,
options.overwriteExisting);
#else
auto created =
create_directory_entry(output, options.overwriteExisting);
#endif
if (!created) {
return std::unexpected{created.error()};
}
continue;
}
if (entry.declared_size > options.maxFileBytes ||
entry.declared_size > options.maxTotalBytes - result.bytes) {
return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy");
}
auto read_builtin_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
return stream.read_entry_data(dst);
};
#ifndef _WIN32
const bool executable = (entry.mode & 0111U) != 0U;
auto extracted = extract_regular_stream(
root->get(), *relative, destination, options, result.bytes,
executable, read_builtin_chunk);
#else
auto extracted = extract_regular_stream(
output, options, result.bytes, read_builtin_chunk);
#endif
if (!extracted) {
return std::unexpected{extracted.error()};
}
result.bytes += *extracted;
}
return result;
#endif
}
} // namespace Void::Archive
+867
View File
@@ -0,0 +1,867 @@
#include "BuiltinTar.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <cstring>
#include <format>
#include <string_view>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::Archive::Detail
{
namespace
{
constexpr std::size_t kTarBlockSize = 512;
[[nodiscard]] bool is_zero_block(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
for (const std::byte b : block) {
if (b != std::byte{0}) {
return false;
}
}
return true;
}
inline void write_octal(std::span<std::byte> field, std::uint64_t value) noexcept
{
if (field.size() < 2) {
return;
}
field.back() = std::byte{0};
std::size_t pos = field.size() - 1;
while (pos > 0) {
--pos;
field[pos] = static_cast<std::byte>('0' + (value & 7ULL));
value >>= 3ULL;
}
}
[[nodiscard]] Void::Result::Result<std::uint64_t>
parse_octal(std::span<const std::byte> field, const char* name)
{
const auto* p = reinterpret_cast<const unsigned char*>(field.data());
std::size_t n = field.size();
if (n > 0 && (p[0] & 0x80U) != 0U) {
// POSIX / GNU big-endian base-256 unsigned extension.
if ((p[0] & 0x40U) != 0U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: negative base-256 field '{}'",
name))};
}
std::uint64_t v = static_cast<std::uint64_t>(p[0] & 0x3FU);
for (std::size_t i = 1; i < n; ++i) {
if (v > (std::numeric_limits<std::uint64_t>::max() >> 8U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: overflowing field '{}'",
name))};
}
v = (v << 8U) | static_cast<std::uint64_t>(p[i]);
}
return v;
}
std::size_t i = 0;
while (i < n && (p[i] == ' ' || p[i] == '\0')) {
++i;
}
if (i == n) {
return std::uint64_t{0};
}
std::uint64_t out = 0;
bool saw_digit = false;
for (; i < n; ++i) {
if (p[i] == '\0' || p[i] == ' ') {
break;
}
if (p[i] < '0' || p[i] > '7') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: invalid octal character in '{}'",
name))};
}
if (out > (std::numeric_limits<std::uint64_t>::max() >> 3U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: octal overflow in '{}'", name))};
}
out = (out << 3U) | static_cast<std::uint64_t>(p[i] - '0');
saw_digit = true;
}
if (!saw_digit) {
return std::uint64_t{0};
}
return out;
}
[[nodiscard]] std::string_view
c_field(std::span<const std::byte> field) noexcept
{
const char* s = reinterpret_cast<const char*>(field.data());
std::size_t len = 0;
while (len < field.size() && s[len] != '\0') {
++len;
}
return {s, len};
}
[[nodiscard]] std::uint32_t
compute_checksum_unsigned(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::uint32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::uint32_t>(' ');
} else {
sum += static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(block[i]));
}
}
return sum;
}
[[nodiscard]] std::int32_t
compute_checksum_signed(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::int32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::int32_t>(' ');
} else {
sum += static_cast<std::int32_t>(
static_cast<signed char>(
std::to_integer<unsigned char>(block[i])));
}
}
return sum;
}
void build_ustar_header(std::array<std::byte, kTarBlockSize>& hdr,
std::string_view wire_name, char typeflag,
std::uint32_t mode, std::uint32_t uid,
std::uint32_t gid, std::uint64_t size,
std::uint64_t mtime) noexcept
{
hdr.fill(std::byte{0});
// Split into prefix (<=155) + name (<=100) only when needed and valid;
// callers handling paths >255 emit PAX 'x' before this header.
std::string_view prefix{};
std::string_view name = wire_name;
if (wire_name.size() > 100) {
const std::size_t min_split =
wire_name.size() > 100 ? wire_name.size() - 101 : 0;
const std::size_t max_split = std::min<std::size_t>(155, wire_name.size() - 1);
std::size_t chosen = std::string_view::npos;
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_name.size() && wire_name[pos] == '/') {
const std::string_view cand_prefix = wire_name.substr(0, pos);
const std::string_view cand_name = wire_name.substr(pos + 1);
if (!cand_prefix.empty() && cand_prefix.size() <= 155 &&
!cand_name.empty() && cand_name.size() <= 100) {
chosen = pos;
break;
}
}
if (pos == 0) {
break;
}
}
if (chosen != std::string_view::npos) {
prefix = wire_name.substr(0, chosen);
name = wire_name.substr(chosen + 1);
} else {
name = wire_name.substr(0, 100);
}
}
std::memcpy(hdr.data() + 0, name.data(), std::min<std::size_t>(name.size(), 100));
write_octal(std::span{hdr}.subspan(100, 8), mode & 07777U);
write_octal(std::span{hdr}.subspan(108, 8), uid);
write_octal(std::span{hdr}.subspan(116, 8), gid);
// Clamp size field to 11 octal digits when PAX overrides size.
const std::uint64_t ustar_size =
size <= 077777777777ULL ? size : 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), ustar_size);
write_octal(std::span{hdr}.subspan(136, 12), mtime);
std::fill(hdr.begin() + 148, hdr.begin() + 156, std::byte{' '});
hdr[156] = static_cast<std::byte>(typeflag);
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = std::byte{'0'};
hdr[264] = std::byte{'0'};
write_octal(std::span{hdr}.subspan(329, 8), 0);
write_octal(std::span{hdr}.subspan(337, 8), 0);
if (!prefix.empty()) {
std::memcpy(hdr.data() + 345, prefix.data(),
std::min<std::size_t>(prefix.size(), 155));
}
const std::uint32_t sum = compute_checksum_unsigned(hdr);
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = std::byte{' '};
}
[[nodiscard]] std::string
make_pax_record(std::string_view key, std::string_view value)
{
const std::size_t rest_len = 1U + key.size() + 1U + value.size() + 1U;
std::size_t total = rest_len + 1U;
for (;;) {
const std::string digits = std::to_string(total);
const std::size_t next = digits.size() + rest_len;
if (next == total) {
break;
}
total = next;
}
return std::format("{} {}={}\n", total, key, value);
}
[[nodiscard]] Void::Result::Result<void>
write_padding(ByteSink& sink, std::uint64_t written)
{
const std::size_t rem = static_cast<std::size_t>(written % kTarBlockSize);
if (rem == 0) {
return {};
}
std::array<std::byte, kTarBlockSize> zeros{};
return sink.write(std::span{zeros}.subspan(0, kTarBlockSize - rem));
}
[[nodiscard]] bool
can_fit_ustar_path(std::string_view wire_path) noexcept
{
if (wire_path.size() <= 100) {
return true;
}
if (wire_path.size() > 256) {
return false;
}
const std::size_t min_split = wire_path.size() - 101;
const std::size_t max_split = std::min<std::size_t>(155, wire_path.size() - 1);
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_path.size() && wire_path[pos] == '/') {
const std::size_t p_len = pos;
const std::size_t n_len = wire_path.size() - (pos + 1);
if (p_len >= 1 && p_len <= 155 && n_len >= 1 && n_len <= 100) {
return true;
}
}
if (pos == 0) {
break;
}
}
return false;
}
[[nodiscard]] Void::Result::Result<void>
parse_pax_records(std::string_view payload, std::string& path_out,
std::string& link_out,
std::optional<std::uint64_t>& size_out,
std::size_t max_path_bytes)
{
std::size_t pos = 0;
while (pos < payload.size()) {
const std::size_t sp = payload.find(' ', pos);
if (sp == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: malformed PAX record length")};
}
std::size_t rec_len = 0;
const auto lr = std::from_chars(payload.data() + pos,
payload.data() + sp, rec_len);
if (lr.ec != std::errc{} || lr.ptr != payload.data() + sp ||
rec_len == 0 || pos + rec_len > payload.size() ||
sp >= pos + rec_len) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX extended header record length")};
}
const std::string_view rec =
payload.substr(sp + 1, pos + rec_len - (sp + 1));
if (rec.empty() || rec.back() != '\n') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing trailing newline")};
}
const std::string_view kv = rec.substr(0, rec.size() - 1);
const std::size_t eq = kv.find('=');
if (eq == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing '='")};
}
const std::string_view key = kv.substr(0, eq);
const std::string_view val = kv.substr(eq + 1);
if (key == "path") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX path exceeds configured limit")};
}
path_out.assign(val);
} else if (key == "linkpath") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX linkpath exceeds configured limit")};
}
link_out.assign(val);
} else if (key == "size") {
std::uint64_t parsed_size = 0;
const auto sr = std::from_chars(
val.data(), val.data() + val.size(), parsed_size);
if (sr.ec != std::errc{} ||
sr.ptr != val.data() + val.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX size field")};
}
size_out = parsed_size;
}
pos += rec_len;
}
return {};
}
} // namespace
Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options)
{
const std::uint64_t mtime =
options.reproducible
? static_cast<std::uint64_t>(std::max<std::int64_t>(
0, options.canonical_mtime))
: static_cast<std::uint64_t>(std::max<std::int64_t>(
0,
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count()));
const std::uint32_t uid =
options.reproducible ? options.canonical_uid : 0U;
const std::uint32_t gid =
options.reproducible ? options.canonical_gid : 0U;
std::array<std::byte, kTarBlockSize> hdr{};
std::vector<std::byte> io_buf(options.limits.transfer_buffer_bytes);
for (const auto& item : items) {
if (options.stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::create_archive: cancelled")};
}
const std::string wire_path =
item.is_directory ? (item.path + "/") : item.path;
const bool need_pax_path = !can_fit_ustar_path(wire_path);
const bool need_pax_size = item.size > 077777777777ULL;
if (need_pax_path || need_pax_size) {
std::string pax;
if (need_pax_path) {
pax += make_pax_record("path", wire_path);
}
if (need_pax_size) {
pax += make_pax_record("size", std::to_string(item.size));
}
std::string pax_name = "PaxHeaders.0/";
const std::size_t suffix_take = std::min<std::size_t>(
100U - pax_name.size(), item.path.size());
pax_name.append(item.path.substr(0, suffix_take));
build_ustar_header(hdr, pax_name, 'x', 0644U, 0U, 0U,
pax.size(), 0ULL);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
const auto pax_bytes =
std::as_bytes(std::span{pax.data(), pax.size()});
if (auto w = sink.write(pax_bytes); !w.has_value()) {
return w;
}
if (auto p = write_padding(sink, pax.size()); !p.has_value()) {
return p;
}
}
build_ustar_header(hdr, wire_path, item.is_directory ? '5' : '0',
item.mode, uid, gid, item.size, mtime);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
if (!item.is_directory) {
if (item.source_fd >= 0) {
#ifndef _WIN32
std::uint64_t remaining = item.size;
while (remaining > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(remaining, io_buf.size()));
const ssize_t r =
::read(item.source_fd, io_buf.data(), want);
if (r < 0 && errno == EINTR) {
continue;
}
if (r <= 0) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::io_error,
"Archive::create_archive: source file shrunk "
"or read failed")};
}
if (auto w = sink.write(std::span<const std::byte>{
io_buf.data(), static_cast<std::size_t>(r)});
!w.has_value()) {
return w;
}
remaining -= static_cast<std::uint64_t>(r);
}
#endif
} else if (!item.inline_content.empty()) {
if (auto w = sink.write(item.inline_content);
!w.has_value()) {
return w;
}
}
if (auto p = write_padding(sink, item.size); !p.has_value()) {
return p;
}
}
}
// Standard two 512-byte zero EOF blocks.
std::array<std::byte, kTarBlockSize * 2> eof_blocks{};
return sink.write(eof_blocks);
}
BuiltinTarStream::BuiltinTarStream(
ByteSource& source, const ReadLimits& limits, std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock)
: m_source(&source), m_limits(limits), m_stop(std::move(stop)),
m_deadline(deadline), m_clock(&clock)
{
}
Void::Result::Result<void> BuiltinTarStream::check_stop_deadline() const
{
if (m_stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::Reader: operation cancelled")};
}
if (m_deadline.has_value() && m_clock->now() >= *m_deadline) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::timeout,
"Archive::Reader: deadline expired")};
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_exact_or_eof(std::span<std::byte> dst)
{
std::size_t filled = 0;
if (m_prefetch_off < m_prefetch.size()) {
const std::size_t take =
std::min(dst.size(), m_prefetch.size() - m_prefetch_off);
std::memcpy(dst.data(), m_prefetch.data() + m_prefetch_off, take);
m_prefetch_off += take;
filled += take;
if (m_prefetch_off == m_prefetch.size()) {
m_prefetch.clear();
m_prefetch_off = 0;
}
}
while (filled < dst.size()) {
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return std::unexpected{std::move(chk.error())};
}
const std::size_t want = dst.size() - filled;
auto r = m_source->read(dst.subspan(filled, want));
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
if (*r == 0) {
break;
}
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes - m_total_compressed) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: compressed input exceeds limit")};
}
m_total_compressed += n;
filled += *r;
}
return filled;
}
Void::Result::Result<void>
BuiltinTarStream::read_exact_required(std::span<std::byte> dst,
const char* context)
{
auto n = read_exact_or_eof(dst);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
if (*n != dst.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive::Reader: unexpected EOF while reading {}",
context))};
}
return {};
}
Void::Result::Result<void>
BuiltinTarStream::discard_bytes(std::uint64_t count,
const char* context)
{
std::array<std::byte, 4096> scratch{};
std::uint64_t rem = count;
while (rem > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(rem, scratch.size()));
if (auto r = read_exact_required(std::span{scratch}.subspan(0, want),
context);
!r.has_value()) {
return r;
}
rem -= want;
}
return {};
}
Void::Result::Result<void> BuiltinTarStream::open()
{
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return chk;
}
m_prefetch.resize(std::min<std::size_t>(512U,
m_limits.transfer_buffer_bytes));
auto r = m_source->read(m_prefetch);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
m_prefetch.resize(*r);
m_prefetch_off = 0;
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: input exceeds compressed limit")};
}
m_total_compressed = n;
if (*r == 0) {
m_reached_eof = true;
return {};
}
// Reject compressed streams cleanly when LibArchive is unavailable.
if (m_prefetch.size() >= 2 &&
m_prefetch[0] == std::byte{0x1F} &&
m_prefetch[1] == std::byte{0x8B}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: gzip archives require LibArchive backend")};
}
if (m_prefetch.size() >= 4 &&
m_prefetch[0] == std::byte{0x28} &&
m_prefetch[1] == std::byte{0xB5} &&
m_prefetch[2] == std::byte{0x2F} &&
m_prefetch[3] == std::byte{0xFD}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: zstd archives require LibArchive backend")};
}
return {};
}
Void::Result::Result<std::optional<BuiltinTarEntry>>
BuiltinTarStream::next_entry()
{
if (m_reached_eof) {
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (m_has_active_entry) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::conflict,
"Archive::Reader: active entry must be drained or skipped")};
}
std::string next_pax_path;
std::string next_pax_link;
std::optional<std::uint64_t> next_pax_size;
std::string global_pax_path;
std::string global_pax_link;
std::optional<std::uint64_t> global_pax_size;
std::string gnu_long_name;
std::string gnu_long_link;
std::array<std::byte, kTarBlockSize> hdr{};
for (;;) {
auto nread = read_exact_or_eof(hdr);
if (!nread.has_value()) {
return std::unexpected{std::move(nread.error())};
}
if (*nread == 0) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (*nread != kTarBlockSize) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: truncated tar header block")};
}
if (is_zero_block(hdr)) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
auto recorded_sum = parse_octal(std::span{hdr}.subspan(148, 8),
"chksum");
if (!recorded_sum.has_value()) {
return std::unexpected{std::move(recorded_sum.error())};
}
const std::uint32_t usum = compute_checksum_unsigned(hdr);
const std::int32_t ssum = compute_checksum_signed(hdr);
if (*recorded_sum != usum &&
static_cast<std::int64_t>(*recorded_sum) !=
static_cast<std::int64_t>(ssum)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: tar header checksum mismatch")};
}
auto parsed_mode =
parse_octal(std::span{hdr}.subspan(100, 8), "mode");
if (!parsed_mode.has_value()) {
return std::unexpected{std::move(parsed_mode.error())};
}
auto parsed_size =
parse_octal(std::span{hdr}.subspan(124, 12), "size");
if (!parsed_size.has_value()) {
return std::unexpected{std::move(parsed_size.error())};
}
const char typeflag = static_cast<char>(std::to_integer<unsigned char>(hdr[156]));
if (typeflag == 'x' || typeflag == 'g' || typeflag == 'L' ||
typeflag == 'K') {
if (*parsed_size > m_limits.max_metadata_bytes ||
*parsed_size >
m_limits.max_metadata_bytes - m_metadata_budget_used) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: tar extended header exceeds metadata "
"limit")};
}
m_metadata_budget_used += static_cast<std::size_t>(*parsed_size);
std::string payload(static_cast<std::size_t>(*parsed_size), '\0');
if (!payload.empty()) {
if (auto rr = read_exact_required(
std::as_writable_bytes(std::span{payload}),
"extended tar header");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
}
const std::size_t pad =
static_cast<std::size_t>((kTarBlockSize - (*parsed_size % kTarBlockSize)) % kTarBlockSize);
if (pad > 0) {
if (auto dr = discard_bytes(pad, "extended header padding");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (typeflag == 'x') {
if (auto pr = parse_pax_records(
payload, next_pax_path, next_pax_link,
next_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else if (typeflag == 'g') {
if (auto pr = parse_pax_records(
payload, global_pax_path, global_pax_link,
global_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else {
while (!payload.empty() && payload.back() == '\0') {
payload.pop_back();
}
if (payload.size() > m_limits.max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: GNU long name exceeds limit")};
}
if (typeflag == 'L') {
gnu_long_name = std::move(payload);
} else {
gnu_long_link = std::move(payload);
}
}
continue;
}
const std::string_view magic_view =
c_field(std::span{hdr}.subspan(257, 6));
std::string path;
if (!next_pax_path.empty()) {
path = std::move(next_pax_path);
} else if (!gnu_long_name.empty()) {
path = std::move(gnu_long_name);
} else if (!global_pax_path.empty()) {
path = global_pax_path;
} else {
const std::string_view name =
c_field(std::span{hdr}.subspan(0, 100));
const std::string_view prefix =
magic_view.starts_with("ustar")
? c_field(std::span{hdr}.subspan(345, 155))
: std::string_view{};
if (!prefix.empty()) {
path = std::string{prefix} + "/" + std::string{name};
} else {
path.assign(name);
}
}
std::string link;
if (!next_pax_link.empty()) {
link = std::move(next_pax_link);
} else if (!gnu_long_link.empty()) {
link = std::move(gnu_long_link);
} else if (!global_pax_link.empty()) {
link = global_pax_link;
} else {
link.assign(c_field(std::span{hdr}.subspan(157, 100)));
}
const std::uint64_t entry_size =
next_pax_size.has_value()
? *next_pax_size
: (global_pax_size.has_value() ? *global_pax_size
: *parsed_size);
EntryType etype = EntryType::Other;
if (typeflag == '1') {
etype = EntryType::Hardlink;
} else if (typeflag == '2') {
etype = EntryType::Symlink;
} else if (typeflag == '5') {
etype = EntryType::Directory;
} else if (typeflag == '0' || typeflag == '\0') {
if (typeflag == '\0' && !magic_view.starts_with("ustar") &&
entry_size == 0 && path.ends_with('/')) {
etype = EntryType::Directory;
} else {
etype = EntryType::RegularFile;
}
}
BuiltinTarEntry out{};
out.path = std::move(path);
out.linkname = std::move(link);
out.type = etype;
out.mode = static_cast<std::uint32_t>(*parsed_mode & 07777ULL);
out.declared_size =
(etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_size = (etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_remaining = m_entry_size;
m_has_active_entry = (etype == EntryType::RegularFile);
// Non-regular entries with declared non-zero payload must advance
// over padding if any (standard tar has 0 size for dirs/links).
if (!m_has_active_entry && entry_size > 0) {
const std::uint64_t pad =
(kTarBlockSize - (entry_size % kTarBlockSize)) % kTarBlockSize;
if (auto dr = discard_bytes(entry_size + pad,
"non-regular entry payload");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
return std::optional<BuiltinTarEntry>{std::move(out)};
}
}
Void::Result::Result<void> BuiltinTarStream::finish_active_entry_padding()
{
m_has_active_entry = false;
const std::uint64_t pad =
(kTarBlockSize - (m_entry_size % kTarBlockSize)) % kTarBlockSize;
m_entry_size = 0;
m_entry_remaining = 0;
if (pad > 0) {
return discard_bytes(pad, "tar entry block padding");
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_entry_data(std::span<std::byte> dst)
{
if (!m_has_active_entry) {
return std::size_t{0};
}
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return std::size_t{0};
}
if (dst.empty()) {
return std::size_t{0};
}
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(dst.size(), m_entry_remaining));
if (auto rr = read_exact_required(dst.subspan(0, want),
"tar entry data");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
m_entry_remaining -= want;
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
}
return want;
}
Void::Result::Result<std::uint64_t> BuiltinTarStream::skip_entry_data()
{
if (!m_has_active_entry) {
return std::uint64_t{0};
}
const std::uint64_t skipped = m_entry_remaining;
const std::uint64_t rem = m_entry_remaining;
m_entry_remaining = 0;
if (rem > 0) {
if (auto dr = discard_bytes(rem, "tar entry data");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return skipped;
}
} // namespace Void::Archive::Detail
+93
View File
@@ -0,0 +1,93 @@
#pragma once
#include <Void/Archive/Types.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
namespace Void::Archive::Detail
{
struct BuiltinCreateItem {
std::string path{};
bool is_directory{false};
std::uint32_t mode{0644};
std::uint64_t size{0};
std::span<const std::byte> inline_content{};
int source_fd{-1};
};
[[nodiscard]] Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options);
struct BuiltinTarEntry {
std::string path{};
std::string linkname{};
EntryType type{EntryType::RegularFile};
std::uint64_t declared_size{0};
std::uint32_t mode{0644};
};
class BuiltinTarStream
{
public:
BuiltinTarStream(
ByteSource& source, const ReadLimits& limits,
std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock);
[[nodiscard]] Void::Result::Result<void> open();
[[nodiscard]] Void::Result::Result<std::optional<BuiltinTarEntry>>
next_entry();
[[nodiscard]] Void::Result::Result<std::size_t>
read_entry_data(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry_data();
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept
{
return m_total_compressed;
}
private:
[[nodiscard]] Void::Result::Result<void> check_stop_deadline() const;
[[nodiscard]] Void::Result::Result<std::size_t>
read_exact_or_eof(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<void>
read_exact_required(std::span<std::byte> dst,
const char* context);
[[nodiscard]] Void::Result::Result<void>
discard_bytes(std::uint64_t count, const char* context);
[[nodiscard]] Void::Result::Result<void>
finish_active_entry_padding();
ByteSource* m_source{nullptr};
ReadLimits m_limits{};
std::stop_token m_stop{};
std::optional<Void::Time::MonotonicClock::time_point> m_deadline{};
const Void::Time::MonotonicClock* m_clock{
&Void::Time::SystemMonotonicClock::instance()};
std::vector<std::byte> m_prefetch{};
std::size_t m_prefetch_off{0};
std::uint64_t m_total_compressed{0};
bool m_reached_eof{false};
bool m_has_active_entry{false};
std::uint64_t m_entry_size{0};
std::uint64_t m_entry_remaining{0};
std::size_t m_metadata_budget_used{0};
};
} // namespace Void::Archive::Detail
+326 -21
View File
@@ -1,6 +1,8 @@
#include <Void/Archive/Archive.hpp>
#include <Void/System/Process.hpp>
#include "BuiltinTar.hpp"
#include <algorithm>
#include <array>
#include <atomic>
@@ -18,8 +20,10 @@
#include <utility>
#include <vector>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h>
#include <archive_entry.h>
#endif
#ifndef _WIN32
#include <dirent.h>
@@ -51,12 +55,14 @@ namespace Void::Archive
constexpr std::string_view kInventoryFilename = "inventory.txt";
constexpr std::string_view kTreeSubdir = "tree";
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using ArchiveReadPtr =
std::unique_ptr<archive, decltype(&archive_read_free)>;
using ArchiveWritePtr =
std::unique_ptr<archive, decltype(&archive_write_free)>;
using ArchiveEntryPtr =
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
#endif
class OwnedFd
{
@@ -129,6 +135,7 @@ namespace Void::Archive
std::error_code{err, std::generic_category()});
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
[[nodiscard]] Void::Result::Error
make_libarchive_error(archive* a, std::string_view op,
ArchiveErrorCode fallback =
@@ -140,6 +147,7 @@ namespace Void::Archive
return make_archive_error(fallback,
std::format("Archive: {}: {}", op, detail));
}
#endif
[[nodiscard]] bool is_safe_single_component(
std::string_view name, std::size_t max_bytes = 255) noexcept
@@ -894,6 +902,15 @@ namespace Void::Archive
}
} // namespace
bool has_libarchive_backend() noexcept
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
return true;
#else
return false;
#endif
}
std::string sanitize_diagnostic_path(std::string_view raw) noexcept
{
std::string out;
@@ -1088,10 +1105,14 @@ namespace Void::Archive
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
ArchiveReadPtr handle{nullptr, &archive_read_free};
std::vector<std::byte> read_buf{};
PathTracker tracker;
std::optional<Void::Result::Error> source_error{};
#endif
std::unique_ptr<Detail::BuiltinTarStream> builtin_stream{};
bool using_builtin{false};
PathTracker tracker;
bool has_active_file{false};
bool reached_eof{false};
bool poisoned{false};
@@ -1101,7 +1122,10 @@ namespace Void::Archive
std::uint64_t total_compressed{0};
explicit Impl(const ReadLimits& lim)
: limits(lim), read_buf(lim.transfer_buffer_bytes),
: limits(lim),
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
read_buf(lim.transfer_buffer_bytes),
#endif
tracker(lim.max_metadata_bytes)
{
}
@@ -1121,6 +1145,7 @@ namespace Void::Archive
return {};
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
static la_ssize_t libarchive_read_cb(archive* a, void* client_data,
const void** buffer)
{
@@ -1150,6 +1175,7 @@ namespace Void::Archive
*buffer = self->read_buf.data();
return static_cast<la_ssize_t>(n);
}
#endif
};
Reader::Reader(std::unique_ptr<Impl> impl) noexcept
@@ -1178,6 +1204,7 @@ namespace Void::Archive
return std::unexpected{std::move(chk.error())};
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
impl->handle =
ArchiveReadPtr{archive_read_new(), &archive_read_free};
if (!impl->handle) {
@@ -1185,6 +1212,7 @@ namespace Void::Archive
ArchiveErrorCode::io_error,
"Archive::Reader: cannot allocate libarchive reader")};
}
(void)archive_read_support_filter_gzip(impl->handle.get());
(void)archive_read_support_filter_zstd(impl->handle.get());
(void)archive_read_support_filter_none(impl->handle.get());
(void)archive_read_support_format_tar(impl->handle.get());
@@ -1199,6 +1227,16 @@ namespace Void::Archive
impl->handle.get(), "open archive",
ArchiveErrorCode::unsupported_format)};
}
impl->using_builtin = false;
#else
impl->builtin_stream = std::make_unique<Detail::BuiltinTarStream>(
source, limits, stop, deadline, clock);
if (auto opened = impl->builtin_stream->open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
impl->total_compressed = impl->builtin_stream->total_compressed_bytes();
impl->using_builtin = true;
#endif
return Reader{std::move(impl)};
}
@@ -1242,6 +1280,91 @@ namespace Void::Archive
return std::unexpected{std::move(chk.error())};
}
if (m_impl->using_builtin) {
auto next = m_impl->builtin_stream->next_entry();
m_impl->total_compressed =
m_impl->builtin_stream->total_compressed_bytes();
if (!next.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
m_impl->reached_eof = true;
return std::optional<EntryInfo>{std::nullopt};
}
if (m_impl->entries_seen >= m_impl->limits.max_entries) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: entry count exceeds limit")};
}
++m_impl->entries_seen;
const auto& raw = **next;
if (raw.path.empty()) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
"Archive::Reader: entry has no pathname")};
}
if (raw.type == EntryType::Hardlink ||
raw.type == EntryType::Symlink || !raw.linkname.empty()) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
std::format("Archive::Reader: links are not allowed ('{}')",
sanitize_diagnostic_path(raw.path)))};
}
if (raw.type != EntryType::Directory &&
raw.type != EntryType::RegularFile) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsafe_entry,
std::format("Archive::Reader: special files are not allowed "
"('{}')",
sanitize_diagnostic_path(raw.path)))};
}
const bool is_dir = (raw.type == EntryType::Directory);
auto vp = validate_archive_path(raw.path, is_dir, m_impl->limits);
if (!vp.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(vp.error())};
}
if (auto rec = m_impl->tracker.record(*vp, is_dir);
!rec.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(rec.error())};
}
std::uint64_t declared_size = 0;
bool executable = false;
if (!is_dir) {
declared_size = raw.declared_size;
if (declared_size > m_impl->limits.max_file_bytes ||
declared_size > m_impl->limits.max_total_bytes -
m_impl->total_decompressed) {
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: declared entry size exceeds policy")};
}
executable = (raw.mode & 0111U) != 0U;
m_impl->has_active_file = true;
m_impl->entry_bytes_read = 0;
}
return std::optional<EntryInfo>{EntryInfo{
.path = std::move(vp->normalized),
.type = is_dir ? EntryType::Directory : EntryType::RegularFile,
.declared_size = declared_size,
.safe_mode = is_dir ? 0755U : (executable ? 0755U : 0644U),
.executable = executable,
.accepted = true,
}};
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
archive_entry* entry = nullptr;
const int status =
archive_read_next_header(m_impl->handle.get(), &entry);
@@ -1335,6 +1458,12 @@ namespace Void::Archive
.executable = executable,
.accepted = true,
}};
#else
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: libarchive backend unavailable")};
#endif
}
Void::Result::Result<std::size_t>
@@ -1358,21 +1487,46 @@ namespace Void::Archive
const std::size_t to_read =
std::min(dst.size(), m_impl->limits.transfer_buffer_bytes);
const la_ssize_t n =
archive_read_data(m_impl->handle.get(), dst.data(), to_read);
if (n == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
if (n < 0) {
m_impl->poisoned = true;
if (m_impl->source_error.has_value()) {
return std::unexpected{std::move(*m_impl->source_error)};
std::size_t read_bytes = 0;
if (m_impl->using_builtin) {
auto r =
m_impl->builtin_stream->read_entry_data(dst.subspan(0, to_read));
m_impl->total_compressed =
m_impl->builtin_stream->total_compressed_bytes();
if (!r.has_value()) {
m_impl->poisoned = true;
return std::unexpected{std::move(r.error())};
}
return std::unexpected{
make_libarchive_error(m_impl->handle.get(), "read entry data")};
read_bytes = *r;
if (read_bytes == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
} else {
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
const la_ssize_t n =
archive_read_data(m_impl->handle.get(), dst.data(), to_read);
if (n == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
if (n < 0) {
m_impl->poisoned = true;
if (m_impl->source_error.has_value()) {
return std::unexpected{std::move(*m_impl->source_error)};
}
return std::unexpected{make_libarchive_error(
m_impl->handle.get(), "read entry data")};
}
read_bytes = static_cast<std::size_t>(n);
#else
m_impl->poisoned = true;
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: libarchive backend unavailable")};
#endif
}
const auto amount = static_cast<std::uint64_t>(n);
const auto amount = static_cast<std::uint64_t>(read_bytes);
if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read ||
amount > m_impl->limits.max_total_bytes -
m_impl->total_decompressed) {
@@ -1383,7 +1537,7 @@ namespace Void::Archive
}
m_impl->entry_bytes_read += amount;
m_impl->total_decompressed += amount;
return static_cast<std::size_t>(n);
return read_bytes;
}
Void::Result::Result<std::uint64_t> Reader::skip_entry()
@@ -1462,6 +1616,7 @@ namespace Void::Archive
}
// Opt-in forensic listing: reports rejected entries without writing.
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
struct ForensicState {
ByteSource* source{nullptr};
ReadLimits limits{};
@@ -1477,6 +1632,7 @@ namespace Void::Archive
ArchiveErrorCode::io_error,
"Archive::list_entries: cannot allocate reader")};
}
(void)archive_read_support_filter_gzip(handle.get());
(void)archive_read_support_filter_zstd(handle.get());
(void)archive_read_support_filter_none(handle.get());
(void)archive_read_support_format_tar(handle.get());
@@ -1592,6 +1748,88 @@ namespace Void::Archive
(void)archive_read_data_skip(handle.get());
}
return out;
#else
Detail::BuiltinTarStream stream{
source, limits, {}, std::nullopt,
Void::Time::SystemMonotonicClock::instance()};
if (auto opened = stream.open(); !opened.has_value()) {
return std::unexpected{std::move(opened.error())};
}
std::vector<EntryInfo> out;
PathTracker tracker{limits.max_metadata_bytes};
std::size_t metadata_bytes = 0;
for (;;) {
auto next = stream.next_entry();
if (!next.has_value()) {
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
break;
}
if (out.size() >= limits.max_entries) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::list_entries: entry count exceeds limit")};
}
const auto& raw = **next;
const std::string sanitized =
raw.path.empty() ? "<missing>"
: sanitize_diagnostic_path(raw.path);
if (sanitized.size() + 64U > limits.max_metadata_bytes ||
metadata_bytes >
limits.max_metadata_bytes - (sanitized.size() + 64U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::list_entries: metadata limit exceeded")};
}
metadata_bytes += sanitized.size() + 64U;
EntryInfo info;
info.path = sanitized;
if (raw.type == EntryType::Hardlink) {
info.type = EntryType::Hardlink;
info.accepted = false;
info.rejection_reason = "hardlink disallowed";
} else if (raw.type == EntryType::Symlink ||
!raw.linkname.empty()) {
info.type = EntryType::Symlink;
info.accepted = false;
info.rejection_reason = "symlink disallowed";
} else if (raw.type != EntryType::Directory &&
raw.type != EntryType::RegularFile) {
info.type = EntryType::Other;
info.accepted = false;
info.rejection_reason = "special file disallowed";
} else {
const bool is_dir = (raw.type == EntryType::Directory);
info.type =
is_dir ? EntryType::Directory : EntryType::RegularFile;
info.declared_size = raw.declared_size;
info.executable = !is_dir && ((raw.mode & 0111U) != 0U);
info.safe_mode =
is_dir ? 0755U : (info.executable ? 0755U : 0644U);
auto vp = validate_archive_path(raw.path, is_dir, limits);
if (!vp.has_value()) {
info.accepted = false;
info.rejection_reason = vp.error().message();
} else if (auto rec = tracker.record(*vp, is_dir);
!rec.has_value()) {
info.accepted = false;
info.rejection_reason = rec.error().message();
} else {
info.path = std::move(vp->normalized);
info.accepted = true;
}
}
out.push_back(std::move(info));
if (auto sk = stream.skip_entry_data(); !sk.has_value()) {
return std::unexpected{std::move(sk.error())};
}
}
return out;
#endif
}
Void::Result::Result<std::vector<EntryInfo>>
@@ -2314,6 +2552,30 @@ namespace Void::Archive
return a.path < b.path;
});
if (options.compression == ArchiveCompression::None &&
(options.prefer_builtin_tar || !has_libarchive_backend())) {
std::vector<Detail::BuiltinCreateItem> builtin_items;
builtin_items.reserve(normalized.size());
for (const auto& item : normalized) {
const bool is_dir = (item.src->type == EntryType::Directory);
const std::uint32_t perm =
item.src->mode.has_value()
? (*item.src->mode & 0777U)
: (is_dir ? 0755U
: (item.src->executable ? 0755U : 0644U));
builtin_items.push_back(Detail::BuiltinCreateItem{
.path = item.path,
.is_directory = is_dir,
.mode = perm,
.size = item.size,
.inline_content = item.src->content,
.source_fd = item.file_fd.get(),
});
}
return Detail::write_builtin_tar(sink, builtin_items, options);
}
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
struct SinkBridge {
ByteSink* sink{nullptr};
std::optional<Void::Result::Error> err{};
@@ -2331,6 +2593,19 @@ namespace Void::Archive
return std::unexpected{
make_libarchive_error(writer.get(), "add zstd filter")};
}
} else if (options.compression == ArchiveCompression::Gzip) {
if (archive_write_add_filter_gzip(writer.get()) != ARCHIVE_OK) {
return std::unexpected{
make_libarchive_error(writer.get(), "add gzip filter")};
}
if (options.reproducible) {
if (archive_write_set_filter_option(
writer.get(), "gzip", "timestamp", nullptr) !=
ARCHIVE_OK) {
return std::unexpected{make_libarchive_error(
writer.get(), "disable gzip timestamp header")};
}
}
} else {
if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) {
return std::unexpected{
@@ -2380,14 +2655,24 @@ namespace Void::Archive
const bool is_dir = (item.src->type == EntryType::Directory);
const std::string wire_path =
is_dir ? (item.path + "/") : item.path;
const std::uint32_t perm =
item.src->mode.has_value()
? (*item.src->mode & 0777U)
: (is_dir ? 0755U
: (item.src->executable ? 0755U : 0644U));
archive_entry_set_pathname(ae.get(), wire_path.c_str());
archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG);
archive_entry_set_perm(
ae.get(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644));
archive_entry_set_perm(ae.get(), static_cast<mode_t>(perm));
if (options.reproducible) {
archive_entry_set_mtime(ae.get(), 0, 0);
archive_entry_set_uid(ae.get(), 0);
archive_entry_set_gid(ae.get(), 0);
archive_entry_set_mtime(
ae.get(),
static_cast<std::time_t>(
std::max<std::int64_t>(0, options.canonical_mtime)),
0);
archive_entry_set_uid(
ae.get(), static_cast<la_int64_t>(options.canonical_uid));
archive_entry_set_gid(
ae.get(), static_cast<la_int64_t>(options.canonical_gid));
archive_entry_set_uname(ae.get(), "");
archive_entry_set_gname(ae.get(), "");
}
@@ -2473,6 +2758,12 @@ namespace Void::Archive
make_libarchive_error(writer.get(), "close archive writer")};
}
return {};
#else
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::create_archive: compressed archives require "
"LibArchive backend")};
#endif
}
Void::Result::Result<void>
@@ -2491,6 +2782,20 @@ namespace Void::Archive
return sink->sync_and_close();
}
Void::Result::Result<void> create(ByteSink& sink,
std::span<const CreateEntry> entries,
const CreationOptions& options)
{
return create_archive(sink, entries, options);
}
Void::Result::Result<void> create(const std::filesystem::path& output_path,
std::span<const CreateEntry> entries,
const CreationOptions& options)
{
return create_archive(output_path, entries, options);
}
// ── Isolated Child Decoder Profile ───────────────────────────────────────
Void::Result::Result<StagedTree>
+16 -1
View File
@@ -1,4 +1,19 @@
set(_void_archive_ext_deps "")
set(_void_archive_has_libarchive 0)
if(NOT CMAKE_DISABLE_FIND_PACKAGE_LibArchive)
if(NOT TARGET LibArchive::LibArchive)
find_package(LibArchive QUIET)
endif()
if(TARGET LibArchive::LibArchive)
list(APPEND _void_archive_ext_deps LibArchive::LibArchive)
set(_void_archive_has_libarchive 1)
endif()
endif()
void_add_module(Archive
INTERNAL_DEPS Functional Time System
EXTERNAL_DEPS LibArchive::LibArchive
EXTERNAL_DEPS ${_void_archive_ext_deps}
)
target_compile_definitions(Void_Archive PUBLIC
VOID_ARCHIVE_HAS_LIBARCHIVE=${_void_archive_has_libarchive}
)
+276 -77
View File
@@ -7,108 +7,284 @@ namespace Void::Argparse
Parser::Parser(std::string program, std::string description)
: program_{std::move(program)}, description_{std::move(description)}
{}
Parser& Parser::flag(std::string_view lng, std::string_view sht,
std::string_view desc, bool& out)
{
flags_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, &out});
}
Parser::~Parser() = default;
Parser::Parser(Parser&&) noexcept = default;
Parser& Parser::operator=(Parser&&) noexcept = default;
Parser& Parser::flag(std::string_view lng,
std::string_view sht,
std::string_view desc,
bool& out)
{
flags_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, &out});
return *this;
}
Parser& Parser::option(std::string_view lng, std::string_view sht,
std::string_view desc, std::optional<std::string>& out)
Parser& Parser::option(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::optional<std::string>& out)
{
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr});
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr, nullptr});
return *this;
}
Parser& Parser::option_default(std::string_view lng, std::string_view sht,
std::string_view desc, std::string& out,
std::string_view default_value)
Parser& Parser::option_many(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::vector<std::string>& out)
{
options_.push_back(
{std::string{lng}, std::string{sht}, std::string{desc}, {}, nullptr, nullptr, &out});
return *this;
}
Parser& Parser::option_default(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::string& out,
std::string_view default_value)
{
out = std::string{default_value};
options_.push_back({std::string{lng}, std::string{sht}, std::string{desc},
std::string{default_value}, nullptr, &out});
options_.push_back({std::string{lng},
std::string{sht},
std::string{desc},
std::string{default_value},
nullptr,
&out,
nullptr});
return *this;
}
Parser& Parser::positional(std::string_view name, std::string_view desc, std::string& out)
Parser& Parser::positional(std::string_view name,
std::string_view desc,
std::string& out)
{
positionals_.push_back({std::string{name}, std::string{desc}, &out});
return *this;
}
std::expected<void, std::string>
Parser::parse(int argc, const char* const* argv) const
Parser& Parser::positional_many(std::string_view name,
std::string_view desc,
std::vector<std::string>& out,
bool required)
{
positional_many_ = MultiPosEntry{
std::string{name}, std::string{desc}, &out, required};
return *this;
}
Parser& Parser::subcommand(std::string name,
std::string description,
std::function<void()> on_selected)
{
const std::string sub_prog =
program_.empty() ? name : (program_ + " " + name);
auto sub_parser = std::make_unique<Parser>(sub_prog, std::move(description));
Parser* raw = sub_parser.get();
subcommands_.push_back(SubcommandEntry{
.name = std::move(name),
.parser = std::move(sub_parser),
.on_selected = std::move(on_selected),
});
return *raw;
}
Parser& Parser::require_subcommand(bool required) noexcept
{
has_explicit_require_sub_ = true;
require_subcommand_ = required;
return *this;
}
ParseResult Parser::parse_detailed(int argc, const char* const* argv) const
{
const Parser* active = this;
std::size_t pos_idx = 0;
bool after_double_dash = false;
std::vector<std::string> matched_path;
std::vector<const std::function<void()>*> callbacks;
auto match_flag_or_opt = [&](const Parser* p,
std::string_view arg,
int& i,
bool& matched,
std::string& err) -> bool {
for (const auto& f : p->flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched = true;
return true;
}
}
for (const auto& opt : p->options_) {
std::string_view value;
bool found = false;
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=') {
value = arg.substr(opt.lng.size() + 1);
found = true;
} else if (arg == opt.lng ||
(!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc) {
err = "option '" + std::string{arg} + "' requires a value";
return false;
}
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
if (opt.out_many) opt.out_many->push_back(val_str);
matched = true;
return true;
}
}
matched = false;
return true;
};
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
// Help
if (arg == "--help" || arg == "-h") {
return std::unexpected{help()};
}
if (!after_double_dash) {
if (arg == "--") {
after_double_dash = true;
continue;
}
// Flag check
bool matched_flag = false;
for (const auto& f : flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) {
*f.out = true;
matched_flag = true;
break;
if (arg == "--help" || arg == "-h") {
return ParseResult{
.outcome = ParseOutcome::Help,
.message = active->help(),
.matched_command_path = std::move(matched_path),
};
}
bool matched = false;
std::string err;
if (!match_flag_or_opt(active, arg, i, matched, err)) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = std::move(err),
.matched_command_path = std::move(matched_path),
};
}
if (matched) {
continue;
}
if (arg.size() > 1 && arg[0] == '-') {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown option: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (pos_idx == 0 && !active->subcommands_.empty()) {
const SubcommandEntry* chosen = nullptr;
for (const auto& sub : active->subcommands_) {
if (sub.name == arg) {
chosen = &sub;
break;
}
}
if (chosen != nullptr) {
matched_path.push_back(chosen->name);
if (chosen->on_selected) {
callbacks.push_back(&chosen->on_selected);
}
active = chosen->parser.get();
pos_idx = 0;
continue;
}
if (active->positionals_.empty() &&
!active->positional_many_.has_value()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown subcommand: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
}
}
if (matched_flag) continue;
// Option check: --key=value or --key value or -k value
bool matched_opt = false;
for (const auto& opt : options_) {
std::string_view value;
bool found = false;
// --key=value
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=')
{
value = arg.substr(opt.lng.size() + 1);
found = true;
}
// --key value or -k value
else if (arg == opt.lng || (!opt.sht.empty() && arg == opt.sht)) {
if (i + 1 >= argc)
return std::unexpected{"option '" + std::string{arg} + "' requires a value"};
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
if (opt.out_opt) *opt.out_opt = val_str;
if (opt.out_str) *opt.out_str = val_str;
matched_opt = true;
break;
}
if (pos_idx < active->positionals_.size()) {
*active->positionals_[pos_idx++].out = std::string{arg};
} else if (active->positional_many_.has_value() &&
active->positional_many_->out != nullptr) {
active->positional_many_->out->push_back(std::string{arg});
} else {
return ParseResult{
.outcome = ParseOutcome::Error,
.message =
"unexpected positional argument: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
if (matched_opt) continue;
// Unknown --/- prefixed arg
if (arg.size() > 1 && arg[0] == '-')
return std::unexpected{"unknown option: " + std::string{arg}};
// Positional
if (pos_idx >= positionals_.size())
return std::unexpected{"unexpected positional argument: " + std::string{arg}};
*positionals_[pos_idx++].out = std::string{arg};
}
// Check required positionals
for (std::size_t j = pos_idx; j < positionals_.size(); ++j)
return std::unexpected{"missing required argument: <" + positionals_[j].name + ">"};
if (!active->subcommands_.empty()) {
const bool req = active->has_explicit_require_sub_
? active->require_subcommand_
: true;
if (req) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing subcommand for '" + active->program_ + "'",
.matched_command_path = std::move(matched_path),
};
}
}
for (std::size_t j = pos_idx; j < active->positionals_.size(); ++j) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required argument: <" +
active->positionals_[j].name + ">",
.matched_command_path = std::move(matched_path),
};
}
if (active->positional_many_.has_value() &&
active->positional_many_->required &&
active->positional_many_->out != nullptr &&
active->positional_many_->out->empty()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required arguments: <" +
active->positional_many_->name + ">",
.matched_command_path = std::move(matched_path),
};
}
for (const auto* cb : callbacks) {
(*cb)();
}
return ParseResult{
.outcome = ParseOutcome::Ok,
.message = {},
.matched_command_path = std::move(matched_path),
};
}
std::expected<void, std::string> Parser::parse(int argc,
const char* const* argv) const
{
auto res = parse_detailed(argc, argv);
if (!res.ok()) {
return std::unexpected{std::move(res.message)};
}
return {};
}
@@ -116,19 +292,42 @@ std::string Parser::help() const
{
std::ostringstream os;
os << "Usage: " << program_;
for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& f : flags_) os << " [" << f.lng << "]";
for (const auto& o : options_) {
const std::string_view dn = std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
const std::string_view dn =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " [" << o.lng << " <" << dn << ">]";
}
if (!subcommands_.empty()) {
os << " <command>";
}
for (const auto& p : positionals_) os << " <" << p.name << ">";
if (positional_many_.has_value()) {
os << (positional_many_->required ? " <" : " [")
<< positional_many_->name
<< (positional_many_->required ? "...>" : "...]");
}
os << "\n";
if (!description_.empty()) os << "\n" << description_ << "\n";
if (!positionals_.empty()) {
if (!subcommands_.empty()) {
os << "\nCommands:\n";
for (const auto& s : subcommands_) {
os << " " << s.name;
if (!s.parser->description_.empty()) {
os << " " << s.parser->description_;
}
os << "\n";
}
}
if (!positionals_.empty() || positional_many_.has_value()) {
os << "\nArguments:\n";
for (const auto& p : positionals_)
os << " <" << p.name << "> " << p.desc << "\n";
if (positional_many_.has_value()) {
os << " <" << positional_many_->name << "...> "
<< positional_many_->desc << "\n";
}
}
if (!flags_.empty()) {
os << "\nFlags:\n";
@@ -141,13 +340,13 @@ std::string Parser::help() const
if (!options_.empty()) {
os << "\nOptions:\n";
for (const auto& o : options_) {
// Derive a display name from the long option (strip leading --)
const std::string_view dname = std::string_view{o.lng}.substr(
o.lng.size() > 2 ? 2 : 0);
const std::string_view dname =
std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0);
os << " " << o.lng;
if (!o.sht.empty()) os << ", " << o.sht;
os << " <" << dname << ">";
if (!o.def.empty()) os << " (default: " << o.def << ")";
if (o.out_many != nullptr) os << " (repeatable)";
os << " " << o.desc << "\n";
}
}
@@ -155,4 +354,4 @@ std::string Parser::help() const
return os.str();
}
} // namespace Void::Argparse
} // namespace Void::Argparse
+895
View File
@@ -0,0 +1,895 @@
#include "BuiltinHash.hpp"
#include <algorithm>
#include <array>
#include <atomic>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <utility>
#include <variant>
namespace Void::Crypto::Detail
{
namespace
{
[[nodiscard]] inline std::uint32_t load_be32(const std::byte* p) noexcept
{
return (static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[0])) << 24U) |
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[1])) << 16U) |
(static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[2])) << 8U) |
static_cast<std::uint32_t>(std::to_integer<std::uint8_t>(p[3]));
}
inline void store_be32(std::byte* p, std::uint32_t v) noexcept
{
p[0] = static_cast<std::byte>((v >> 24U) & 0xFFU);
p[1] = static_cast<std::byte>((v >> 16U) & 0xFFU);
p[2] = static_cast<std::byte>((v >> 8U) & 0xFFU);
p[3] = static_cast<std::byte>(v & 0xFFU);
}
[[nodiscard]] inline std::uint64_t load_be64(const std::byte* p) noexcept
{
return (static_cast<std::uint64_t>(load_be32(p)) << 32U) |
static_cast<std::uint64_t>(load_be32(p + 4));
}
inline void store_be64(std::byte* p, std::uint64_t v) noexcept
{
store_be32(p, static_cast<std::uint32_t>((v >> 32U) & 0xFFFFFFFFU));
store_be32(p + 4, static_cast<std::uint32_t>(v & 0xFFFFFFFFU));
}
[[nodiscard]] inline std::uint64_t load_le64(const std::byte* p) noexcept
{
return static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[0])) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[1])) << 8U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[2])) << 16U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[3])) << 24U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[4])) << 32U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[5])) << 40U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[6])) << 48U) |
(static_cast<std::uint64_t>(std::to_integer<std::uint8_t>(p[7])) << 56U);
}
inline void store_le64(std::byte* p, std::uint64_t v) noexcept
{
for (std::size_t i = 0; i < 8; ++i) {
p[i] = static_cast<std::byte>((v >> (8U * i)) & 0xFFU);
}
}
// ── FIPS 180-4 SHA-1 ─────────────────────────────────────────────────
struct Sha1State {
std::array<std::uint32_t, 5> h{0x67452301U, 0xefcdab89U,
0x98badcfeU, 0x10325476U,
0xc3d2e1f0U};
std::array<std::byte, 64> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint32_t, 80> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be32(block + i * 4);
}
for (std::size_t i = 16; i < 80; ++i) {
w[i] = std::rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^
w[i - 16],
1);
}
std::uint32_t a = h[0];
std::uint32_t b = h[1];
std::uint32_t c = h[2];
std::uint32_t d = h[3];
std::uint32_t e = h[4];
for (std::size_t i = 0; i < 80; ++i) {
std::uint32_t f = 0;
std::uint32_t k = 0;
if (i < 20) {
f = (b & c) | ((~b) & d);
k = 0x5a827999U;
} else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ed9eba1U;
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8f1bbcdcU;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6U;
}
const std::uint32_t temp =
std::rotl(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = std::rotl(b, 30);
b = a;
a = temp;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out20) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 56) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 56, std::byte{0});
store_be64(buf.data() + 56, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 5; ++i) {
store_be32(out20.data() + i * 4, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── FIPS 180-4 SHA-256 ───────────────────────────────────────────────
struct Sha256State {
static constexpr std::array<std::uint32_t, 64> kRound = {
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U,
0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U,
0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U,
0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU,
0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U,
0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U,
0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U,
0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U,
0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U,
0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U,
0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U};
std::array<std::uint32_t, 8> h{0x6a09e667U, 0xbb67ae85U,
0x3c6ef372U, 0xa54ff53aU,
0x510e527fU, 0x9b05688cU,
0x1f83d9abU, 0x5be0cd19U};
std::array<std::byte, 64> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint32_t, 64> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be32(block + i * 4);
}
for (std::size_t i = 16; i < 64; ++i) {
const std::uint32_t s0 = std::rotr(w[i - 15], 7) ^
std::rotr(w[i - 15], 18) ^
(w[i - 15] >> 3U);
const std::uint32_t s1 = std::rotr(w[i - 2], 17) ^
std::rotr(w[i - 2], 19) ^
(w[i - 2] >> 10U);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint32_t a = h[0];
std::uint32_t b = h[1];
std::uint32_t c = h[2];
std::uint32_t d = h[3];
std::uint32_t e = h[4];
std::uint32_t f = h[5];
std::uint32_t g = h[6];
std::uint32_t hv = h[7];
for (std::size_t i = 0; i < 64; ++i) {
const std::uint32_t S1 = std::rotr(e, 6) ^
std::rotr(e, 11) ^
std::rotr(e, 25);
const std::uint32_t ch = (e & f) ^ ((~e) & g);
const std::uint32_t temp1 =
hv + S1 + ch + kRound[i] + w[i];
const std::uint32_t S0 = std::rotr(a, 2) ^
std::rotr(a, 13) ^
std::rotr(a, 22);
const std::uint32_t maj =
(a & b) ^ (a & c) ^ (b & c);
const std::uint32_t temp2 = S0 + maj;
hv = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
h[5] += f;
h[6] += g;
h[7] += hv;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out32) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 56) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 56, std::byte{0});
store_be64(buf.data() + 56, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 8; ++i) {
store_be32(out32.data() + i * 4, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── FIPS 180-4 SHA-512 ───────────────────────────────────────────────
struct Sha512State {
static constexpr std::array<std::uint64_t, 80> kRound = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL};
std::array<std::uint64_t, 8> h{
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
std::array<std::byte, 128> buf{};
std::size_t buf_len{0};
std::uint64_t total_bytes{0};
void compress(const std::byte* block) noexcept
{
std::array<std::uint64_t, 80> w{};
for (std::size_t i = 0; i < 16; ++i) {
w[i] = load_be64(block + i * 8);
}
for (std::size_t i = 16; i < 80; ++i) {
const std::uint64_t s0 = std::rotr(w[i - 15], 1) ^
std::rotr(w[i - 15], 8) ^
(w[i - 15] >> 7U);
const std::uint64_t s1 = std::rotr(w[i - 2], 19) ^
std::rotr(w[i - 2], 61) ^
(w[i - 2] >> 6U);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint64_t a = h[0];
std::uint64_t b = h[1];
std::uint64_t c = h[2];
std::uint64_t d = h[3];
std::uint64_t e = h[4];
std::uint64_t f = h[5];
std::uint64_t g = h[6];
std::uint64_t hv = h[7];
for (std::size_t i = 0; i < 80; ++i) {
const std::uint64_t S1 = std::rotr(e, 14) ^
std::rotr(e, 18) ^
std::rotr(e, 41);
const std::uint64_t ch = (e & f) ^ ((~e) & g);
const std::uint64_t temp1 =
hv + S1 + ch + kRound[i] + w[i];
const std::uint64_t S0 = std::rotr(a, 28) ^
std::rotr(a, 34) ^
std::rotr(a, 39);
const std::uint64_t maj =
(a & b) ^ (a & c) ^ (b & c);
const std::uint64_t temp2 = S0 + maj;
hv = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1 + temp2;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
h[5] += f;
h[6] += g;
h[7] += hv;
builtin_secure_wipe(std::as_writable_bytes(std::span{w}));
}
void update(std::span<const std::byte> data) noexcept
{
total_bytes += data.size();
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
if (buf_len == buf.size()) {
compress(buf.data());
buf_len = 0;
}
}
while (off + buf.size() <= data.size()) {
compress(data.data() + off);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data(), data.data() + off, rem);
buf_len = rem;
}
}
void finalize_into(std::span<std::byte> out64) noexcept
{
buf[buf_len++] = std::byte{0x80};
if (buf_len > 112) {
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data());
buf_len = 0;
}
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.begin() + 112, std::byte{0});
store_be64(buf.data() + 112, total_bytes >> 61U);
store_be64(buf.data() + 120, total_bytes << 3U);
compress(buf.data());
for (std::size_t i = 0; i < 8; ++i) {
store_be64(out64.data() + i * 8, h[i]);
}
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(buf);
buf_len = 0;
total_bytes = 0;
}
};
// ── RFC 7693 BLAKE2b ─────────────────────────────────────────────────
struct Blake2bState {
static constexpr std::array<std::uint64_t, 8> kIv = {
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
static constexpr std::array<std::array<std::uint8_t, 16>, 12>
kSigma = {{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
{11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4},
{7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8},
{9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13},
{2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9},
{12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11},
{13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10},
{6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5},
{10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
}};
std::array<std::uint64_t, 8> h{kIv};
std::array<std::uint64_t, 2> t{0, 0};
std::array<std::byte, 128> buf{};
std::size_t buf_len{0};
std::size_t out_len{64};
void init(std::size_t digest_len) noexcept
{
h = kIv;
out_len = digest_len;
h[0] ^= 0x01010000ULL ^ static_cast<std::uint64_t>(out_len);
t = {0, 0};
buf.fill(std::byte{0});
buf_len = 0;
}
void add_counter(std::uint64_t inc) noexcept
{
t[0] += inc;
if (t[0] < inc) {
++t[1];
}
}
void compress(const std::byte* block, bool is_last) noexcept
{
std::array<std::uint64_t, 16> m{};
for (std::size_t i = 0; i < 16; ++i) {
m[i] = load_le64(block + i * 8);
}
std::array<std::uint64_t, 16> v{};
for (std::size_t i = 0; i < 8; ++i) {
v[i] = h[i];
v[i + 8] = kIv[i];
}
v[12] ^= t[0];
v[13] ^= t[1];
if (is_last) {
v[14] = ~v[14];
}
auto mix = [&](std::size_t r, std::size_t p,
std::size_t ia, std::size_t ib,
std::size_t ic, std::size_t id) noexcept {
const auto s0 = kSigma[r][2 * p];
const auto s1 = kSigma[r][2 * p + 1];
v[ia] = v[ia] + v[ib] + m[s0];
v[id] = std::rotr(v[id] ^ v[ia], 32);
v[ic] = v[ic] + v[id];
v[ib] = std::rotr(v[ib] ^ v[ic], 24);
v[ia] = v[ia] + v[ib] + m[s1];
v[id] = std::rotr(v[id] ^ v[ia], 16);
v[ic] = v[ic] + v[id];
v[ib] = std::rotr(v[ib] ^ v[ic], 63);
};
for (std::size_t r = 0; r < 12; ++r) {
mix(r, 0, 0, 4, 8, 12);
mix(r, 1, 1, 5, 9, 13);
mix(r, 2, 2, 6, 10, 14);
mix(r, 3, 3, 7, 11, 15);
mix(r, 4, 0, 5, 10, 15);
mix(r, 5, 1, 6, 11, 12);
mix(r, 6, 2, 7, 8, 13);
mix(r, 7, 3, 4, 9, 14);
}
for (std::size_t i = 0; i < 8; ++i) {
h[i] ^= v[i] ^ v[i + 8];
}
builtin_secure_wipe(std::as_writable_bytes(std::span{m}));
builtin_secure_wipe(std::as_writable_bytes(std::span{v}));
}
void update(std::span<const std::byte> data) noexcept
{
if (data.empty()) {
return;
}
std::size_t off = 0;
if (buf_len > 0) {
const std::size_t take =
std::min(data.size(), buf.size() - buf_len);
std::memcpy(buf.data() + buf_len, data.data(), take);
buf_len += take;
off += take;
// Only flush a full buffer when more bytes follow so
// finalize() sees the true final block.
if (off < data.size() && buf_len == buf.size()) {
add_counter(128);
compress(buf.data(), false);
buf_len = 0;
}
}
while (off + buf.size() < data.size()) {
add_counter(128);
compress(data.data() + off, false);
off += buf.size();
}
if (off < data.size()) {
const std::size_t rem = data.size() - off;
std::memcpy(buf.data() + buf_len, data.data() + off,
rem);
buf_len += rem;
}
}
void finalize_into(std::span<std::byte> out) noexcept
{
add_counter(static_cast<std::uint64_t>(buf_len));
std::fill(buf.begin() + static_cast<std::ptrdiff_t>(buf_len),
buf.end(), std::byte{0});
compress(buf.data(), true);
std::array<std::byte, 64> full{};
for (std::size_t i = 0; i < 8; ++i) {
store_le64(full.data() + i * 8, h[i]);
}
std::memcpy(out.data(), full.data(), out_len);
builtin_secure_wipe(full);
wipe();
}
void wipe() noexcept
{
builtin_secure_wipe(std::as_writable_bytes(std::span{h}));
builtin_secure_wipe(std::as_writable_bytes(std::span{t}));
builtin_secure_wipe(buf);
buf_len = 0;
}
};
} // namespace
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept
{
if (buffer.empty()) {
return;
}
volatile std::byte* p = buffer.data();
for (std::size_t i = 0; i < buffer.size(); ++i) {
p[i] = std::byte{0};
}
std::atomic_signal_fence(std::memory_order_seq_cst);
}
bool builtin_constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
volatile unsigned char diff = 0;
for (std::size_t i = 0; i < lhs.size(); ++i) {
const auto a = static_cast<unsigned char>(lhs[i]);
const auto b = static_cast<unsigned char>(rhs[i]);
diff = static_cast<unsigned char>(diff | (a ^ b));
}
std::atomic_signal_fence(std::memory_order_seq_cst);
return diff == 0;
}
struct BuiltinHasher::State {
std::variant<std::monostate, Sha1State, Sha256State, Sha512State,
Blake2bState>
impl{};
void wipe() noexcept
{
std::visit(
[](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (!std::is_same_v<T, std::monostate>) {
st.wipe();
}
},
impl);
impl.template emplace<std::monostate>();
}
};
BuiltinHasher::~BuiltinHasher() noexcept { destroy(); }
BuiltinHasher::BuiltinHasher(BuiltinHasher&& other) noexcept
: m_state(std::exchange(other.m_state, nullptr))
{
}
BuiltinHasher& BuiltinHasher::operator=(BuiltinHasher&& other) noexcept
{
if (this != &other) {
destroy();
m_state = std::exchange(other.m_state, nullptr);
}
return *this;
}
void BuiltinHasher::destroy() noexcept
{
if (m_state != nullptr) {
m_state->wipe();
delete m_state;
m_state = nullptr;
}
}
bool BuiltinHasher::init(HashAlgorithm algorithm) noexcept
{
if (m_state == nullptr) {
m_state = new (std::nothrow) State();
if (m_state == nullptr) {
return false;
}
} else {
m_state->wipe();
}
switch (algorithm) {
case HashAlgorithm::Sha1:
m_state->impl.emplace<Sha1State>();
return true;
case HashAlgorithm::Sha256:
m_state->impl.emplace<Sha256State>();
return true;
case HashAlgorithm::Sha512:
m_state->impl.emplace<Sha512State>();
return true;
case HashAlgorithm::Blake2b256: {
auto& b = m_state->impl.emplace<Blake2bState>();
b.init(32);
return true;
}
case HashAlgorithm::Blake2b512: {
auto& b = m_state->impl.emplace<Blake2bState>();
b.init(64);
return true;
}
}
return false;
}
void BuiltinHasher::update(std::span<const std::byte> data) noexcept
{
if (m_state == nullptr || data.empty()) {
return;
}
std::visit(
[&](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (!std::is_same_v<T, std::monostate>) {
st.update(data);
}
},
m_state->impl);
}
Digest BuiltinHasher::finalize()
{
Digest out;
if (m_state == nullptr) {
return out;
}
std::visit(
[&](auto& st) {
using T = std::decay_t<decltype(st)>;
if constexpr (std::is_same_v<T, Sha1State>) {
out.resize(20);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Sha256State>) {
out.resize(32);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Sha512State>) {
out.resize(64);
st.finalize_into(out);
} else if constexpr (std::is_same_v<T, Blake2bState>) {
out.resize(st.out_len);
st.finalize_into(out);
}
},
m_state->impl);
return out;
}
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept
{
std::array<std::byte, 64> key_block{};
if (secret_key.size() > 64) {
Sha256State kh;
kh.update(secret_key);
kh.finalize_into(std::span{key_block}.subspan(0, 32));
} else if (!secret_key.empty()) {
std::memcpy(key_block.data(), secret_key.data(), secret_key.size());
}
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 64; ++i) {
ipad[i] = key_block[i] ^ std::byte{0x36};
opad[i] = key_block[i] ^ std::byte{0x5C};
}
std::array<std::byte, 32> inner_hash{};
{
Sha256State inner;
inner.update(ipad);
inner.update(message);
inner.finalize_into(inner_hash);
}
{
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(output_32);
}
builtin_secure_wipe(key_block);
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output) noexcept
{
std::array<std::byte, 32> zero_salt{};
const auto effective_salt =
salt.empty() ? std::span<const std::byte>{zero_salt} : salt;
std::array<std::byte, 32> prk{};
builtin_hmac_sha256(effective_salt, secret_input, prk);
std::array<std::byte, 32> t{};
std::size_t t_len = 0;
std::size_t written = 0;
std::uint8_t counter = 1;
while (written < secret_output.size()) {
std::array<std::byte, 64> ipad{};
std::array<std::byte, 64> opad{};
for (std::size_t i = 0; i < 32; ++i) {
ipad[i] = prk[i] ^ std::byte{0x36};
opad[i] = prk[i] ^ std::byte{0x5C};
}
for (std::size_t i = 32; i < 64; ++i) {
ipad[i] = std::byte{0x36};
opad[i] = std::byte{0x5C};
}
std::array<std::byte, 32> inner_hash{};
Sha256State inner;
inner.update(ipad);
if (t_len > 0) {
inner.update(std::span<const std::byte>{t.data(), t_len});
}
if (!context.empty()) {
inner.update(context);
}
const std::byte ctr_byte = static_cast<std::byte>(counter);
inner.update(std::span<const std::byte>{&ctr_byte, 1});
inner.finalize_into(inner_hash);
Sha256State outer;
outer.update(opad);
outer.update(inner_hash);
outer.finalize_into(t);
t_len = 32;
const std::size_t copy_n =
std::min<std::size_t>(32, secret_output.size() - written);
std::memcpy(secret_output.data() + written, t.data(), copy_n);
written += copy_n;
++counter;
builtin_secure_wipe(ipad);
builtin_secure_wipe(opad);
builtin_secure_wipe(inner_hash);
}
builtin_secure_wipe(prk);
builtin_secure_wipe(t);
}
} // namespace Void::Crypto::Detail
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <Void/Crypto/Crypto.hpp>
#include <Void/Crypto/Types.hpp>
#include <cstddef>
#include <span>
namespace Void::Crypto::Detail
{
void builtin_secure_wipe(std::span<std::byte> buffer) noexcept;
[[nodiscard]] bool
builtin_constant_time_equal(std::span<const std::byte> lhs,
std::span<const std::byte> rhs) noexcept;
class BuiltinHasher
{
public:
BuiltinHasher() noexcept = default;
~BuiltinHasher() noexcept;
BuiltinHasher(BuiltinHasher&& other) noexcept;
BuiltinHasher& operator=(BuiltinHasher&& other) noexcept;
BuiltinHasher(const BuiltinHasher&) = delete;
BuiltinHasher& operator=(const BuiltinHasher&) = delete;
[[nodiscard]] bool init(HashAlgorithm algorithm) noexcept;
void update(std::span<const std::byte> data) noexcept;
[[nodiscard]] Digest finalize();
private:
struct State;
State* m_state{nullptr};
void destroy() noexcept;
};
void builtin_hmac_sha256(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output_32) noexcept;
void builtin_hkdf_sha256(std::span<const std::byte> secret_input,
std::span<const std::byte> salt,
std::span<const std::byte> context,
std::span<std::byte> secret_output) noexcept;
} // namespace Void::Crypto::Detail
+297 -24
View File
@@ -1,19 +1,24 @@
#include <Void/Crypto/Crypto.hpp>
#include "BuiltinHash.hpp"
#include <array>
#include <cstdint>
#include <cstring>
#include <format>
#include <fstream>
#include <limits>
#include <optional>
#include <utility>
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
#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>
#endif
namespace Void::Crypto
{
@@ -42,6 +47,36 @@ namespace Void::Crypto
std::format("{}: injected crypto backend fault", operation));
}
[[nodiscard]] bool spans_overlap(std::span<const std::byte> a,
std::span<const std::byte> b) noexcept
{
if (a.empty() || b.empty()) {
return false;
}
const auto a_begin = reinterpret_cast<std::uintptr_t>(a.data());
const auto a_end = a_begin + a.size();
const auto b_begin = reinterpret_cast<std::uintptr_t>(b.data());
const auto b_end = b_begin + b.size();
return a_begin < b_end && b_begin < a_end;
}
[[nodiscard]] bool use_builtin_hash(
HashAlgorithm algorithm, const ProviderOptions& provider) noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin ||
algorithm == HashAlgorithm::Blake2b256) {
return true;
}
return false;
#else
(void)algorithm;
(void)provider;
return true;
#endif
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
[[nodiscard]] const char*
algorithm_name(HashAlgorithm algorithm) noexcept
{
@@ -52,6 +87,10 @@ namespace Void::Crypto
return "SHA256";
case HashAlgorithm::Sha512:
return "SHA512";
case HashAlgorithm::Blake2b256:
return nullptr;
case HashAlgorithm::Blake2b512:
return "BLAKE2B512";
}
return nullptr;
}
@@ -78,19 +117,6 @@ namespace Void::Crypto
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)>;
@@ -110,6 +136,7 @@ namespace Void::Crypto
? &kEmptyByte
: reinterpret_cast<const unsigned char*>(span.data());
}
#endif
[[nodiscard]] Void::Result::Result<bool>
verify_ed25519_impl(std::span<const std::byte> message,
@@ -144,6 +171,12 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: Ed25519 requires OpenSSL backend")};
}
ERR_clear_error();
const char* propq = propq_or_null(provider);
EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex(
@@ -182,14 +215,33 @@ namespace Void::Crypto
}
ERR_clear_error();
return result == 1;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::verifyEd25519: built without OpenSSL backend")};
#endif
}
} // namespace
bool has_openssl_backend() noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return true;
#else
return false;
#endif
}
void secure_wipe(std::span<std::byte> buffer) noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!buffer.empty()) {
OPENSSL_cleanse(buffer.data(), buffer.size());
}
#else
Detail::builtin_secure_wipe(buffer);
#endif
}
bool constant_time_equal(std::span<const std::byte> lhs,
@@ -201,7 +253,11 @@ namespace Void::Crypto
if (lhs.empty()) {
return true;
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0;
#else
return Detail::builtin_constant_time_equal(lhs, rhs);
#endif
}
ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept
@@ -218,8 +274,12 @@ namespace Void::Crypto
}
struct Hasher::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free};
EvpMdPtr algorithm{nullptr, &EVP_MD_free};
#endif
Detail::BuiltinHasher builtin{};
bool using_builtin{false};
HasherState state{HasherState::Ready};
};
@@ -244,18 +304,50 @@ namespace Void::Crypto
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")};
switch (algorithm) {
case HashAlgorithm::Sha1:
case HashAlgorithm::Sha256:
case HashAlgorithm::Sha512:
case HashAlgorithm::Blake2b256:
case HashAlgorithm::Blake2b512:
break;
default:
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported algorithm")};
}
if (auto fault = maybe_inject_fault(FaultOperation::hash_create,
"Crypto::Hasher::create");
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(algorithm, provider)) {
if (!provider.property_query.empty()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::Hasher: property_query unavailable on built-in "
"backend")};
}
auto impl = std::make_unique<Impl>();
if (!impl->builtin.init(algorithm)) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: built-in initialization failed")};
}
impl->using_builtin = true;
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const char* md_name = algorithm_name(algorithm);
if (md_name == nullptr) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Hasher: unsupported OpenSSL digest algorithm")};
}
ERR_clear_error();
auto impl = std::make_unique<Impl>();
impl->algorithm = EvpMdPtr{
@@ -278,8 +370,14 @@ namespace Void::Crypto
CryptoErrorCode::provider_error,
"Crypto::Hasher: digest initialization failed")};
}
impl->using_builtin = false;
impl->state = HasherState::Ready;
return Hasher{std::move(impl)};
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher: OpenSSL backend unavailable")};
#endif
}
Void::Result::Result<void> Hasher::update(std::span<const std::byte> data)
@@ -301,6 +399,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
if (m_impl->using_builtin) {
m_impl->builtin.update(data);
m_impl->state = HasherState::Updating;
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (!data.empty() &&
EVP_DigestUpdate(m_impl->context.get(), data.data(),
data.size()) != 1) {
@@ -311,6 +415,12 @@ namespace Void::Crypto
}
m_impl->state = HasherState::Updating;
return {};
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::update: invalid backend")};
#endif
}
Void::Result::Result<void> Hasher::update(std::string_view data)
@@ -337,6 +447,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Failed;
return std::unexpected{std::move(*fault)};
}
if (m_impl->using_builtin) {
Digest digest = m_impl->builtin.finalize();
m_impl->state = HasherState::Finalized;
return digest;
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
const int digest_size = EVP_MD_get_size(m_impl->algorithm.get());
if (digest_size <= 0) {
m_impl->state = HasherState::Failed;
@@ -357,6 +473,12 @@ namespace Void::Crypto
m_impl->state = HasherState::Finalized;
digest.resize(written);
return digest;
#else
m_impl->state = HasherState::Failed;
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::Hasher::finalize: invalid backend")};
#endif
}
auto hash(HashAlgorithm algorithm, std::span<const std::byte> data)
@@ -388,18 +510,31 @@ namespace Void::Crypto
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hashFile(algorithm, path, ProviderOptions{});
return hash_file(algorithm, path, ProviderOptions{});
}
auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, provider);
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path)
-> Void::Result::Result<Digest>
{
return hash_file(algorithm, path, ProviderOptions{});
}
auto hash_file(HashAlgorithm algorithm, const std::filesystem::path& path,
const ProviderOptions& provider)
-> Void::Result::Result<Digest>
{
std::ifstream input{path, std::ios::binary};
if (!input.is_open()) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: cannot open '{}'",
std::format("Crypto::hash_file: cannot open '{}'",
path.string()))};
}
auto hasher = Hasher::create(algorithm, provider);
@@ -422,7 +557,7 @@ namespace Void::Crypto
if (input.bad() || (!input.eof() && input.fail())) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::io_error,
std::format("Crypto::hashFile: I/O error reading '{}'",
std::format("Crypto::hash_file: I/O error reading '{}'",
path.string()))};
}
return hasher->finalize();
@@ -452,21 +587,63 @@ namespace Void::Crypto
{
return hash(HashAlgorithm::Sha512, data);
}
Void::Result::Result<Digest> blake2b256(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b256(std::string_view data)
{
return hash(HashAlgorithm::Blake2b256, data);
}
Void::Result::Result<Digest> blake2b512(std::span<const std::byte> data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> blake2b512(std::string_view data)
{
return hash(HashAlgorithm::Blake2b512, data);
}
Void::Result::Result<Digest> sha1File(const std::filesystem::path& path)
{
return hashFile(HashAlgorithm::Sha1, path);
return hash_file(HashAlgorithm::Sha1, path);
}
Void::Result::Result<Digest> sha256File(const std::filesystem::path& path)
{
return hashFile(HashAlgorithm::Sha256, path);
return hash_file(HashAlgorithm::Sha256, path);
}
Void::Result::Result<Digest> sha512File(const std::filesystem::path& path)
{
return hashFile(HashAlgorithm::Sha512, path);
return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest> sha1_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha1, path);
}
Void::Result::Result<Digest> sha256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha256, path);
}
Void::Result::Result<Digest> sha512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Sha512, path);
}
Void::Result::Result<Digest>
blake2b256_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b256, path);
}
Void::Result::Result<Digest>
blake2b512_file(const std::filesystem::path& path)
{
return hash_file(HashAlgorithm::Blake2b512, path);
}
struct Ed25519PrivateKey::Impl {
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free};
#else
std::uint8_t unused{0};
#endif
};
Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr<Impl> impl) noexcept
@@ -481,7 +658,11 @@ namespace Void::Crypto
bool Ed25519PrivateKey::valid() const noexcept
{
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
return m_impl != nullptr && m_impl->pkey != nullptr;
#else
return false;
#endif
}
Void::Result::Result<Ed25519PrivateKey>
@@ -492,6 +673,12 @@ namespace Void::Crypto
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate requires OpenSSL backend")};
}
ERR_clear_error();
EvpPkeyPtr key{
EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"),
@@ -504,6 +691,13 @@ namespace Void::Crypto
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::generate: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519PrivateKey>
@@ -523,6 +717,13 @@ namespace Void::Crypto
fault.has_value()) {
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed requires OpenSSL "
"backend")};
}
ERR_clear_error();
EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex(
nullptr, "ED25519", propq_or_null(provider),
@@ -536,6 +737,13 @@ namespace Void::Crypto
auto impl = std::make_unique<Impl>();
impl->pkey = std::move(key);
return Ed25519PrivateKey{std::move(impl)};
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::from_raw_seed: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519PublicKey> Ed25519PrivateKey::public_key() const
@@ -546,6 +754,7 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::public_key: invalid or moved-from "
"key")};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
Ed25519PublicKey pub;
std::size_t len = pub.bytes.size();
if (EVP_PKEY_get_raw_public_key(
@@ -558,6 +767,12 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::public_key failed")};
}
return pub;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::public_key: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519Seed> Ed25519PrivateKey::export_raw_seed() const
@@ -568,6 +783,7 @@ namespace Void::Crypto
"Crypto::Ed25519PrivateKey::export_raw_seed: invalid or "
"moved-from key")};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
std::array<std::byte, Ed25519SeedSize> raw{};
std::size_t len = raw.size();
if (EVP_PKEY_get_raw_private_key(
@@ -582,6 +798,12 @@ namespace Void::Crypto
auto result = Ed25519Seed::from_bytes(raw);
secure_wipe(raw);
return result;
#else
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::Ed25519PrivateKey::export_raw_seed: built without OpenSSL "
"backend")};
#endif
}
Void::Result::Result<Ed25519Signature>
@@ -607,6 +829,12 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
if (provider.prefer_builtin) {
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519 requires OpenSSL backend")};
}
ERR_clear_error();
EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!context) {
@@ -635,6 +863,12 @@ namespace Void::Crypto
"Crypto::sign_ed25519 failed")};
}
return signature;
#else
(void)provider;
return std::unexpected{make_crypto_error(
CryptoErrorCode::unsupported_algorithm,
"Crypto::sign_ed25519: built without OpenSSL backend")};
#endif
}
Void::Result::Result<bool> verifyEd25519(std::span<const std::byte> message,
@@ -682,6 +916,19 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hmac_sha256_into: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hmac_sha256(secret_key, message, output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error();
EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)),
&EVP_MAC_free};
@@ -732,6 +979,12 @@ namespace Void::Crypto
"Crypto::hmac_sha256_into: EVP_MAC_final failed")};
}
return {};
#else
secure_wipe(output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hmac_sha256_into: OpenSSL backend unavailable")};
#endif
}
Void::Result::Result<Digest> hmac_sha256(std::span<const std::byte> secret_key,
@@ -780,6 +1033,20 @@ namespace Void::Crypto
return std::unexpected{std::move(*fault)};
}
if (use_builtin_hash(HashAlgorithm::Sha256, provider)) {
if (!provider.property_query.empty()) {
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::provider_error,
"Crypto::hkdf_sha256: property_query unavailable on "
"built-in backend")};
}
Detail::builtin_hkdf_sha256(secret_input, salt, context,
secret_output);
return {};
}
#if defined(VOID_CRYPTO_HAS_OPENSSL) && VOID_CRYPTO_HAS_OPENSSL
ERR_clear_error();
EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)),
&EVP_KDF_free};
@@ -825,6 +1092,12 @@ namespace Void::Crypto
"Crypto::hkdf_sha256: EVP_KDF_derive failed")};
}
return {};
#else
secure_wipe(secret_output);
return std::unexpected{make_crypto_error(
CryptoErrorCode::backend_error,
"Crypto::hkdf_sha256: OpenSSL backend unavailable")};
#endif
}
} // namespace Void::Crypto
+16 -1
View File
@@ -1,6 +1,21 @@
set(_void_crypto_ext_deps "")
set(_void_crypto_has_openssl 0)
if(NOT CMAKE_DISABLE_FIND_PACKAGE_OpenSSL)
if(NOT TARGET OpenSSL::Crypto)
find_package(OpenSSL QUIET)
endif()
if(TARGET OpenSSL::Crypto)
list(APPEND _void_crypto_ext_deps OpenSSL::Crypto)
set(_void_crypto_has_openssl 1)
endif()
endif()
void_add_module(Crypto
INTERNAL_DEPS Functional
EXTERNAL_DEPS OpenSSL::Crypto
EXTERNAL_DEPS ${_void_crypto_ext_deps}
EXCLUDE_HEADERS
Void/Crypto/AsyncHash.hpp
)
target_compile_definitions(Void_Crypto PUBLIC
VOID_CRYPTO_HAS_OPENSSL=${_void_crypto_has_openssl}
)
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Discovery
INTERNAL_DEPS Core Functional Time Async
)
+144
View File
@@ -0,0 +1,144 @@
#include <Void/DiscoveryRpc/EndpointAdapter.hpp>
#include <algorithm>
#include <utility>
namespace Void::DiscoveryRpc
{
namespace
{
struct OutstandingGuard {
std::atomic<std::size_t>& counter;
~OutstandingGuard() noexcept
{
counter.fetch_sub(1, std::memory_order_acq_rel);
}
};
} // namespace
EndpointResolverClient::EndpointResolverClient(
const Void::Discovery::Catalog& catalog,
EndpointResolverOptions options)
: m_catalog(&catalog), m_options(std::move(options))
{
if (m_options.clock == nullptr) {
m_options.clock = &Void::Time::SystemMonotonicClock::instance();
}
if (m_options.require_tls) {
m_options.http_options.verify_tls = true;
}
}
Void::Discovery::Result<SelectedEndpoint>
EndpointResolverClient::select_endpoint(
std::optional<std::string_view> affinity_key)
{
if (m_catalog == nullptr) {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::InvalidArgument,
"EndpointResolverClient: null catalog"));
}
auto snap =
m_catalog->resolve(m_options.service, m_options.resolve_policy);
if (!snap.has_value()) {
return Void::Result::fail(snap.error());
}
auto selected =
affinity_key.has_value()
? Void::Discovery::AffinitySelector::select(*snap, *affinity_key)
: m_rr.select(*snap);
if (!selected.has_value()) {
return Void::Result::fail(selected.error());
}
if (m_options.require_tls && selected->endpoint.scheme != "https") {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::TlsIdentityMismatch,
"EndpointResolverClient: refusing non-TLS endpoint when "
"require_tls is enabled"));
}
const std::string effective_tls{
selected->endpoint.effective_tls_name()};
if (!m_options.expected_tls_name.empty() &&
effective_tls != m_options.expected_tls_name) {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::TlsIdentityMismatch,
"EndpointResolverClient: endpoint TLS identity mismatch "
"(expected '" +
m_options.expected_tls_name + "', got '" + effective_tls +
"')"));
}
SelectedEndpoint out{};
out.origin_url = selected->endpoint.to_origin_url();
out.effective_tls_name = effective_tls;
out.record = std::move(*selected);
return out;
}
Void::Result::Result<Void::RPC::OwnedBytes>
EndpointResolverClient::call(
Void::RPC::MethodId method, Void::RPC::OwnedBytes payload,
Void::RPC::CallOptions options,
std::optional<std::string_view> affinity_key)
{
// Enforce bounded outstanding operations.
std::size_t cur = m_outstanding.load(std::memory_order_acquire);
for (;;) {
if (cur >= m_options.max_outstanding_ops) {
return Void::Result::fail(Void::Discovery::make_discovery_error(
Void::Discovery::DiscoveryErrorCode::LimitExceeded,
"EndpointResolverClient: max_outstanding_ops reached"));
}
if (m_outstanding.compare_exchange_weak(
cur, cur + 1, std::memory_order_acq_rel,
std::memory_order_acquire)) {
break;
}
}
OutstandingGuard guard{m_outstanding};
auto selected = select_endpoint(affinity_key);
if (!selected.has_value()) {
return Void::Result::fail(selected.error());
}
Void::RPC::ClientOptions copts{};
copts.endpoint_base_url = selected->origin_url;
copts.http_options = m_options.http_options;
if (m_options.require_tls) {
copts.http_options.verify_tls = true;
}
copts.limits = m_options.rpc_limits;
copts.clock = m_options.clock;
if (options.timeout <= std::chrono::milliseconds{0} ||
options.timeout > m_options.total_deadline) {
options.timeout = m_options.total_deadline;
}
// Retain peer identity header when address refreshes to an IP while
// expected_tls_name preserves the logical authority.
if (!selected->record.endpoint.expected_tls_name.empty()) {
bool has_authority = false;
for (const auto& m : options.metadata) {
if (m.key == "void-expected-authority") {
has_authority = true;
break;
}
}
if (!has_authority) {
options.metadata.push_back(Void::RPC::MetadataEntry{
.key = "void-expected-authority",
.value = selected->effective_tls_name,
});
}
}
Void::RPC::Client client{std::move(copts)};
return client.call(method, std::move(payload), options);
}
} // namespace Void::DiscoveryRpc
+3
View File
@@ -0,0 +1,3 @@
void_add_module(DiscoveryRpc
INTERNAL_DEPS Discovery RPC
)
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Messaging
INTERNAL_DEPS Core Functional Binary Time Async
)
+513
View File
@@ -0,0 +1,513 @@
#include <Void/MessagingRpc/RpcAdapter.hpp>
#include <cstring>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::MessagingRpc
{
using namespace Void::Messaging;
using Void::Messaging::Result;
namespace
{
void put_u8(Void::RPC::OwnedBytes& out, std::uint8_t v)
{
out.push_back(static_cast<std::byte>(v));
}
void put_u32(Void::RPC::OwnedBytes& out, std::uint32_t v)
{
out.push_back(static_cast<std::byte>((v >> 24U) & 0xFFU));
out.push_back(static_cast<std::byte>((v >> 16U) & 0xFFU));
out.push_back(static_cast<std::byte>((v >> 8U) & 0xFFU));
out.push_back(static_cast<std::byte>(v & 0xFFU));
}
void put_u64(Void::RPC::OwnedBytes& out, std::uint64_t v)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((v >> shift) & 0xFFU));
}
}
void put_i64(Void::RPC::OwnedBytes& out, std::int64_t v)
{
put_u64(out, static_cast<std::uint64_t>(v));
}
void put_str(Void::RPC::OwnedBytes& out, std::string_view s)
{
put_u32(out, static_cast<std::uint32_t>(s.size()));
for (char c : s) {
out.push_back(static_cast<std::byte>(c));
}
}
void put_bytes(Void::RPC::OwnedBytes& out,
const std::vector<std::byte>& b)
{
put_u32(out, static_cast<std::uint32_t>(b.size()));
out.insert(out.end(), b.begin(), b.end());
}
void put_message(Void::RPC::OwnedBytes& out, const Message& m)
{
put_str(out, m.id);
put_u32(out, m.schema_version);
put_bytes(out, m.payload);
put_u32(out, static_cast<std::uint32_t>(m.headers.size()));
for (const auto& [k, v] : m.headers) {
put_str(out, k);
put_str(out, v);
}
}
void put_receipt(Void::RPC::OwnedBytes& out, const Receipt& r)
{
put_str(out, r.queue);
put_str(out, r.group);
put_str(out, r.message_id);
put_u64(out, r.sequence);
put_u64(out, r.generation);
}
struct Cursor {
std::span<const std::byte> data{};
std::size_t pos{0};
[[nodiscard]] bool read_u8(std::uint8_t& v) noexcept
{
if (pos + 1U > data.size()) return false;
v = std::to_integer<std::uint8_t>(data[pos++]);
return true;
}
[[nodiscard]] bool read_u32(std::uint32_t& v) noexcept
{
if (pos + 4U > data.size()) return false;
v = (static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos]))
<< 24U) |
(static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos + 1]))
<< 16U) |
(static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos + 2]))
<< 8U) |
static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(data[pos + 3]));
pos += 4U;
return true;
}
[[nodiscard]] bool read_u64(std::uint64_t& v) noexcept
{
if (pos + 8U > data.size()) return false;
v = 0;
for (std::size_t i = 0; i < 8U; ++i) {
v = (v << 8U) |
static_cast<std::uint64_t>(
std::to_integer<std::uint8_t>(data[pos + i]));
}
pos += 8U;
return true;
}
[[nodiscard]] bool read_i64(std::int64_t& v) noexcept
{
std::uint64_t u = 0;
if (!read_u64(u)) return false;
v = static_cast<std::int64_t>(u);
return true;
}
[[nodiscard]] bool read_str(std::string& s)
{
std::uint32_t len = 0;
if (!read_u32(len) || pos + len > data.size()) return false;
s.resize(len);
if (len > 0U) {
std::memcpy(s.data(), data.data() + pos, len);
}
pos += len;
return true;
}
[[nodiscard]] bool read_bytes(std::vector<std::byte>& b)
{
std::uint32_t len = 0;
if (!read_u32(len) || pos + len > data.size()) return false;
b.resize(len);
if (len > 0U) {
std::memcpy(b.data(), data.data() + pos, len);
}
pos += len;
return true;
}
[[nodiscard]] bool read_message(Message& m)
{
std::uint32_t hcount = 0;
if (!read_str(m.id) || !read_u32(m.schema_version) ||
!read_bytes(m.payload) || !read_u32(hcount)) {
return false;
}
m.headers.clear();
for (std::uint32_t i = 0; i < hcount; ++i) {
std::string k, v;
if (!read_str(k) || !read_str(v)) return false;
m.headers.emplace(std::move(k), std::move(v));
}
return true;
}
[[nodiscard]] bool read_receipt(Receipt& r)
{
return read_str(r.queue) && read_str(r.group) &&
read_str(r.message_id) && read_u64(r.sequence) &&
read_u64(r.generation);
}
[[nodiscard]] bool eof() const noexcept
{
return pos == data.size();
}
};
[[nodiscard]] Void::Result::Error
map_rpc_err(const Void::Result::Error& err)
{
if (err.code().domain == Void::Result::kMessagingErrorDomain) {
return err;
}
const auto status = Void::RPC::rpc_status_from_error(err);
if (status == Void::RPC::RpcStatusCode::UnknownOutcome) {
return make_messaging_error(MessagingErrorCode::UnknownOutcome,
err.message());
}
if (status == Void::RPC::RpcStatusCode::FailedPrecondition) {
return make_messaging_error(MessagingErrorCode::StaleReceipt,
err.message());
}
if (status == Void::RPC::RpcStatusCode::NotFound) {
return make_messaging_error(MessagingErrorCode::NotFound,
err.message());
}
if (status == Void::RPC::RpcStatusCode::ResourceExhausted) {
return make_messaging_error(MessagingErrorCode::QuotaExceeded,
err.message());
}
if (status == Void::RPC::RpcStatusCode::DeadlineExceeded) {
return make_messaging_error(MessagingErrorCode::Timeout,
err.message());
}
if (status == Void::RPC::RpcStatusCode::Cancelled) {
return make_messaging_error(MessagingErrorCode::Cancelled,
err.message());
}
return make_messaging_error(MessagingErrorCode::PersistenceError,
err.message());
}
} // namespace
RpcQueueServer::~RpcQueueServer() noexcept { unmount_and_drain(); }
void RpcQueueServer::unmount_and_drain() noexcept
{
for (auto& reg : m_registrations) {
reg.unregister_and_drain();
}
m_registrations.clear();
}
Result<void> RpcQueueServer::mount(Void::RPC::Server& server, Queue& queue)
{
auto bind_one = [&](Void::RPC::MethodId id, std::string name,
Void::RPC::UnaryHandler handler) -> Result<void> {
auto reg = server.bind(
Void::RPC::MethodDescriptor{
.id = id,
.service_name = "void.messaging.v1",
.method_name = std::move(name),
.schema_version = 1,
},
std::move(handler));
if (!reg.has_value()) {
return Void::Result::fail(reg.error());
}
m_registrations.push_back(std::move(*reg));
return {};
};
if (auto r = bind_one(
kPublishMethod, "publish",
[&queue](const Void::RPC::CallContext& ctx,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
std::string qname;
std::uint8_t dur = 0;
Message msg{};
if (!c.read_str(qname) || !c.read_u8(dur) ||
!c.read_message(msg) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed publish request"));
}
Void::Async::OperationOptions opts{.stop = ctx.stop};
auto res = queue.publish(
qname, std::move(msg),
static_cast<PublishDurability>(dur), opts);
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
Void::RPC::OwnedBytes out;
put_str(out, res->queue);
put_str(out, res->message_id);
put_u64(out, res->sequence);
put_u8(out, static_cast<std::uint8_t>(res->durability));
put_u8(out, res->deduplicated ? 1U : 0U);
return out;
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kTryReceiveMethod, "try_receive",
[&queue](const Void::RPC::CallContext&,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
std::string qname, gname;
if (!c.read_str(qname) || !c.read_str(gname) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed try_receive request"));
}
auto res = queue.try_receive(qname, gname);
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
Void::RPC::OwnedBytes out;
if (!res->has_value()) {
put_u8(out, 0U);
return out;
}
put_u8(out, 1U);
put_message(out, (*res)->message);
put_receipt(out, (*res)->receipt);
put_u32(out, (*res)->attempt);
put_i64(out, to_mono_ns((*res)->visibility_deadline));
return out;
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kAckMethod, "ack",
[&queue](const Void::RPC::CallContext& ctx,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
Receipt rec{};
if (!c.read_receipt(rec) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed ack request"));
}
auto res =
queue.ack(rec, Void::Async::OperationOptions{.stop = ctx.stop});
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
return Void::RPC::OwnedBytes{};
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kNackMethod, "nack",
[&queue](const Void::RPC::CallContext& ctx,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
Receipt rec{};
std::uint8_t has_delay = 0;
std::int64_t delay_ms = 0;
if (!c.read_receipt(rec) || !c.read_u8(has_delay) ||
!c.read_i64(delay_ms) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed nack request"));
}
std::optional<std::chrono::milliseconds> d{};
if (has_delay != 0U) {
d = std::chrono::milliseconds{delay_ms};
}
auto res = queue.nack(
rec, d, Void::Async::OperationOptions{.stop = ctx.stop});
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
return Void::RPC::OwnedBytes{};
});
!r.has_value()) {
return r;
}
if (auto r = bind_one(
kQueryReceiptMethod, "query_receipt",
[&queue](const Void::RPC::CallContext&,
Void::RPC::OwnedBytes req)
-> Void::Result::Result<Void::RPC::OwnedBytes> {
Cursor c{req, 0};
Receipt rec{};
if (!c.read_receipt(rec) || !c.eof()) {
return Void::Result::fail(Void::RPC::make_rpc_error(
Void::RPC::RpcStatusCode::InvalidArgument,
"MessagingRpc: malformed query_receipt request"));
}
auto res = queue.query_receipt(rec);
if (!res.has_value()) {
return Void::Result::fail(res.error());
}
Void::RPC::OwnedBytes out;
put_u8(out, static_cast<std::uint8_t>(*res));
return out;
});
!r.has_value()) {
return r;
}
return {};
}
// ── RpcQueueClient ────────────────────────────────────────────────────────
RpcQueueClient::RpcQueueClient(Void::RPC::ClientOptions options)
: m_client(std::move(options))
{
}
Result<PublishReceipt> RpcQueueClient::publish(
std::string_view queue, const Message& message,
PublishDurability durability, const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_str(req, queue);
put_u8(req, static_cast<std::uint8_t>(durability));
put_message(req, message);
auto resp = m_client.call(kPublishMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
Cursor c{*resp, 0};
PublishReceipt pr{};
std::uint8_t dur = 0, dedup = 0;
if (!c.read_str(pr.queue) || !c.read_str(pr.message_id) ||
!c.read_u64(pr.sequence) || !c.read_u8(dur) || !c.read_u8(dedup) ||
!c.eof()) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt publish response"));
}
pr.durability = static_cast<PublishDurability>(dur);
pr.deduplicated = (dedup != 0U);
return pr;
}
Result<std::optional<Delivery>>
RpcQueueClient::try_receive(std::string_view queue,
std::string_view group,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_str(req, queue);
put_str(req, group);
auto resp = m_client.call(kTryReceiveMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
Cursor c{*resp, 0};
std::uint8_t present = 0;
if (!c.read_u8(present)) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt try_receive response"));
}
if (present == 0U) {
return std::optional<Delivery>{std::nullopt};
}
Delivery d{};
std::int64_t dl_ns = 0;
if (!c.read_message(d.message) || !c.read_receipt(d.receipt) ||
!c.read_u32(d.attempt) || !c.read_i64(dl_ns) || !c.eof()) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt delivery response"));
}
d.visibility_deadline = Void::Time::MonotonicClock::time_point{
std::chrono::duration_cast<
Void::Time::MonotonicClock::time_point::duration>(
std::chrono::nanoseconds{dl_ns})};
return std::optional<Delivery>{std::move(d)};
}
Result<void> RpcQueueClient::ack(const Receipt& receipt,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_receipt(req, receipt);
auto resp = m_client.call(kAckMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
return {};
}
Result<void>
RpcQueueClient::nack(const Receipt& receipt,
std::optional<std::chrono::milliseconds> delay,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_receipt(req, receipt);
put_u8(req, delay.has_value() ? 1U : 0U);
put_i64(req, delay.has_value() ? delay->count() : 0LL);
auto resp = m_client.call(kNackMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
return {};
}
Result<DeliveryState>
RpcQueueClient::query_receipt(const Receipt& receipt,
const Void::RPC::CallOptions& options)
{
Void::RPC::OwnedBytes req;
put_receipt(req, receipt);
auto resp = m_client.call(kQueryReceiptMethod, std::move(req), options);
if (!resp.has_value()) {
return Void::Result::fail(map_rpc_err(resp.error()));
}
Cursor c{*resp, 0};
std::uint8_t st = 0;
if (!c.read_u8(st) || !c.eof() ||
st > static_cast<std::uint8_t>(DeliveryState::DeadLetter)) {
return Void::Result::fail(make_messaging_error(
MessagingErrorCode::CorruptPayload,
"MessagingRpc: corrupt query_receipt response"));
}
return static_cast<DeliveryState>(st);
}
} // namespace Void::MessagingRpc
+3
View File
@@ -0,0 +1,3 @@
void_add_module(MessagingRpc
INTERNAL_DEPS Messaging RPC
)
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(MessagingStorage
INTERNAL_DEPS Messaging Storage
)
+1055 -115
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+492
View File
@@ -0,0 +1,492 @@
#include <Void/Net/Pool.hpp>
#include <deque>
#include <map>
#include <mutex>
#include <utility>
#include <vector>
namespace Void::Net
{
struct ConnectionPool::State {
struct IdleEntry {
std::unique_ptr<PooledConnection> conn;
Void::Time::MonotonicClock::time_point idle_since;
};
PoolLimits limits{};
const Void::Time::MonotonicClock* clock{nullptr};
mutable std::mutex mutex{};
bool shut_down{false};
std::size_t total_connections{0};
std::size_t active_leases{0};
std::size_t idle_connections{0};
std::uint64_t total_acquires{0};
std::uint64_t idle_hits{0};
std::uint64_t idle_evictions{0};
std::uint64_t closed_dirty{0};
std::map<PoolKey, std::size_t> per_origin_count{};
std::map<PoolKey, std::deque<IdleEntry>> idle_by_key{};
void evict_expired_locked(
Void::Time::MonotonicClock::time_point now,
std::vector<std::unique_ptr<PooledConnection>>& to_close)
{
for (auto it = idle_by_key.begin(); it != idle_by_key.end();) {
auto& dq = it->second;
while (!dq.empty()) {
const bool expired =
limits.idle_timeout >
std::chrono::milliseconds::zero() &&
(now - dq.front().idle_since) >=
limits.idle_timeout;
const bool closed =
!dq.front().conn || !dq.front().conn->is_open();
if (!expired && !closed) {
break;
}
to_close.push_back(std::move(dq.front().conn));
dq.pop_front();
--idle_connections;
--total_connections;
++idle_evictions;
auto oit = per_origin_count.find(it->first);
if (oit != per_origin_count.end()) {
if (--oit->second == 0) {
per_origin_count.erase(oit);
}
}
}
if (dq.empty()) {
it = idle_by_key.erase(it);
} else {
++it;
}
}
}
void evict_oldest_idle_locked(
std::vector<std::unique_ptr<PooledConnection>>& to_close)
{
auto oldest_it = idle_by_key.end();
for (auto it = idle_by_key.begin(); it != idle_by_key.end();
++it) {
if (it->second.empty()) {
continue;
}
if (oldest_it == idle_by_key.end() ||
it->second.front().idle_since <
oldest_it->second.front().idle_since) {
oldest_it = it;
}
}
if (oldest_it == idle_by_key.end()) {
return;
}
to_close.push_back(std::move(oldest_it->second.front().conn));
oldest_it->second.pop_front();
--idle_connections;
--total_connections;
++idle_evictions;
auto oit = per_origin_count.find(oldest_it->first);
if (oit != per_origin_count.end()) {
if (--oit->second == 0) {
per_origin_count.erase(oit);
}
}
if (oldest_it->second.empty()) {
idle_by_key.erase(oldest_it);
}
}
void return_lease(const PoolKey& key,
std::unique_ptr<PooledConnection> conn,
bool reusable) noexcept
{
std::vector<std::unique_ptr<PooledConnection>> to_close;
{
std::lock_guard lock{mutex};
const auto now = clock->now();
if (active_leases > 0) {
--active_leases;
}
evict_expired_locked(now, to_close);
const bool can_keep = !shut_down && reusable &&
conn != nullptr && conn->is_open() &&
limits.max_idle_connections > 0;
if (can_keep) {
while (idle_connections >=
limits.max_idle_connections) {
evict_oldest_idle_locked(to_close);
}
idle_by_key[key].push_back(
IdleEntry{std::move(conn), now});
++idle_connections;
} else {
if (conn != nullptr) {
to_close.push_back(std::move(conn));
}
if (!reusable) {
++closed_dirty;
}
if (total_connections > 0) {
--total_connections;
}
auto oit = per_origin_count.find(key);
if (oit != per_origin_count.end()) {
if (--oit->second == 0) {
per_origin_count.erase(oit);
}
}
}
}
for (auto& c : to_close) {
if (c) {
c->close();
}
}
}
};
// ── ConnectionLease ─────────────────────────────────────────────────────
ConnectionLease::~ConnectionLease() noexcept { release(); }
ConnectionLease::ConnectionLease(ConnectionLease&& other) noexcept
: m_pool_state(std::move(other.m_pool_state)),
m_key(std::move(other.m_key)), m_conn(std::move(other.m_conn)),
m_reused(std::exchange(other.m_reused, false)),
m_reusable(std::exchange(other.m_reusable, false)),
m_active(std::exchange(other.m_active, false))
{
}
ConnectionLease& ConnectionLease::operator=(ConnectionLease&& other) noexcept
{
if (this != &other) {
release();
m_pool_state = std::move(other.m_pool_state);
m_key = std::move(other.m_key);
m_conn = std::move(other.m_conn);
m_reused = std::exchange(other.m_reused, false);
m_reusable = std::exchange(other.m_reusable, false);
m_active = std::exchange(other.m_active, false);
}
return *this;
}
bool ConnectionLease::valid() const noexcept
{
return m_active && m_conn != nullptr;
}
bool ConnectionLease::reused() const noexcept { return m_reused; }
const PoolKey& ConnectionLease::key() const noexcept { return m_key; }
PooledConnection* ConnectionLease::get() const noexcept
{
return m_conn.get();
}
PooledConnection& ConnectionLease::operator*() const noexcept
{
return *m_conn;
}
PooledConnection* ConnectionLease::operator->() const noexcept
{
return m_conn.get();
}
void ConnectionLease::mark_reusable(bool reusable) noexcept
{
m_reusable = reusable;
}
void ConnectionLease::release() noexcept
{
if (!m_active) {
return;
}
m_active = false;
auto state = std::static_pointer_cast<ConnectionPool::State>(
std::move(m_pool_state));
auto conn = std::move(m_conn);
const bool reusable = std::exchange(m_reusable, false);
if (state) {
state->return_lease(m_key, std::move(conn), reusable);
} else if (conn) {
conn->close();
}
}
// ── ConnectionPool ──────────────────────────────────────────────────────
ConnectionPool::ConnectionPool(PoolLimits limits,
const Void::Time::MonotonicClock& clock)
: m_state(std::make_shared<State>())
{
m_state->limits = limits;
m_state->clock = &clock;
}
ConnectionPool::~ConnectionPool() noexcept { shutdown(); }
ConnectionPool::ConnectionPool(ConnectionPool&&) noexcept = default;
ConnectionPool&
ConnectionPool::operator=(ConnectionPool&&) noexcept = default;
Void::Result::Result<ConnectionLease>
ConnectionPool::acquire(const PoolKey& key,
const ConnectionFactory& factory)
{
if (!m_state) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ConnectionPool: moved-from pool")};
}
if (!factory) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ConnectionPool: empty connection factory")};
}
if (key.host.empty() || key.port == 0) {
return std::unexpected{make_net_error(
NetErrorCode::invalid_argument,
"Net::ConnectionPool: invalid pool key")};
}
std::vector<std::unique_ptr<PooledConnection>> to_close;
std::unique_ptr<PooledConnection> reused_conn;
{
std::lock_guard lock{m_state->mutex};
if (m_state->shut_down) {
return std::unexpected{make_net_error(
NetErrorCode::cancelled,
"Net::ConnectionPool: pool is shut down")};
}
const auto now = m_state->clock->now();
m_state->evict_expired_locked(now, to_close);
// Try LIFO idle connection for this exact key.
auto it = m_state->idle_by_key.find(key);
if (it != m_state->idle_by_key.end()) {
while (!it->second.empty()) {
auto cand = std::move(it->second.back().conn);
it->second.pop_back();
--m_state->idle_connections;
if (cand && cand->is_open()) {
reused_conn = std::move(cand);
++m_state->active_leases;
++m_state->total_acquires;
++m_state->idle_hits;
break;
}
to_close.push_back(std::move(cand));
--m_state->total_connections;
++m_state->idle_evictions;
auto oit = m_state->per_origin_count.find(key);
if (oit != m_state->per_origin_count.end()) {
if (--oit->second == 0) {
m_state->per_origin_count.erase(oit);
}
}
}
if (it->second.empty()) {
m_state->idle_by_key.erase(it);
}
}
if (!reused_conn) {
// Enforce per-origin and total connection capacity.
const std::size_t cur_origin =
m_state->per_origin_count[key];
if (cur_origin >= m_state->limits.max_per_origin) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::overloaded,
"Net::ConnectionPool: per-origin connection limit "
"reached",
Void::Result::ErrorCode{
Void::Result::kNetErrorDomain,
static_cast<std::int32_t>(
NetErrorCode::quota_exceeded)}}};
}
if (m_state->total_connections >=
m_state->limits.max_total_connections) {
// Evict an idle connection from another origin if possible.
if (m_state->idle_connections > 0) {
m_state->evict_oldest_idle_locked(to_close);
}
}
if (m_state->total_connections >=
m_state->limits.max_total_connections) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::overloaded,
"Net::ConnectionPool: total connection limit reached",
Void::Result::ErrorCode{
Void::Result::kNetErrorDomain,
static_cast<std::int32_t>(
NetErrorCode::quota_exceeded)}}};
}
// Reserve slot before calling factory outside lock.
++m_state->total_connections;
++m_state->active_leases;
++m_state->per_origin_count[key];
++m_state->total_acquires;
}
}
for (auto& c : to_close) {
if (c) {
c->close();
}
}
if (reused_conn) {
ConnectionLease lease;
lease.m_pool_state = m_state;
lease.m_key = key;
lease.m_conn = std::move(reused_conn);
lease.m_reused = true;
lease.m_reusable = false;
lease.m_active = true;
return lease;
}
// Create new connection outside pool lock.
auto created = factory(key);
if (!created.has_value() || !(*created) || !(*created)->is_open()) {
// Roll back reservation.
std::lock_guard lock{m_state->mutex};
if (m_state->active_leases > 0) {
--m_state->active_leases;
}
if (m_state->total_connections > 0) {
--m_state->total_connections;
}
auto oit = m_state->per_origin_count.find(key);
if (oit != m_state->per_origin_count.end()) {
if (--oit->second == 0) {
m_state->per_origin_count.erase(oit);
}
}
if (!created.has_value()) {
return std::unexpected{std::move(created.error())};
}
return std::unexpected{make_net_error(
NetErrorCode::connect_failed,
"Net::ConnectionPool: factory returned closed/null "
"connection")};
}
ConnectionLease lease;
lease.m_pool_state = m_state;
lease.m_key = key;
lease.m_conn = std::move(*created);
lease.m_reused = false;
lease.m_reusable = false;
lease.m_active = true;
return lease;
}
std::size_t ConnectionPool::evict_expired()
{
if (!m_state) {
return 0;
}
std::vector<std::unique_ptr<PooledConnection>> to_close;
{
std::lock_guard lock{m_state->mutex};
m_state->evict_expired_locked(m_state->clock->now(), to_close);
}
for (auto& c : to_close) {
if (c) {
c->close();
}
}
return to_close.size();
}
std::size_t ConnectionPool::clear_idle()
{
if (!m_state) {
return 0;
}
std::vector<std::unique_ptr<PooledConnection>> to_close;
{
std::lock_guard lock{m_state->mutex};
for (auto& [key, dq] : m_state->idle_by_key) {
for (auto& entry : dq) {
to_close.push_back(std::move(entry.conn));
--m_state->idle_connections;
--m_state->total_connections;
++m_state->idle_evictions;
auto oit = m_state->per_origin_count.find(key);
if (oit != m_state->per_origin_count.end()) {
if (--oit->second == 0) {
m_state->per_origin_count.erase(oit);
}
}
}
}
m_state->idle_by_key.clear();
}
for (auto& c : to_close) {
if (c) {
c->close();
}
}
return to_close.size();
}
void ConnectionPool::shutdown() noexcept
{
if (!m_state) {
return;
}
std::vector<std::unique_ptr<PooledConnection>> to_close;
{
std::lock_guard lock{m_state->mutex};
m_state->shut_down = true;
for (auto& [key, dq] : m_state->idle_by_key) {
for (auto& entry : dq) {
to_close.push_back(std::move(entry.conn));
--m_state->idle_connections;
--m_state->total_connections;
auto oit = m_state->per_origin_count.find(key);
if (oit != m_state->per_origin_count.end()) {
if (--oit->second == 0) {
m_state->per_origin_count.erase(oit);
}
}
}
}
m_state->idle_by_key.clear();
}
for (auto& c : to_close) {
if (c) {
c->close();
}
}
}
PoolStats ConnectionPool::stats() const
{
if (!m_state) {
return {};
}
std::lock_guard lock{m_state->mutex};
return PoolStats{
.total_connections = m_state->total_connections,
.active_leases = m_state->active_leases,
.idle_connections = m_state->idle_connections,
.total_acquires = m_state->total_acquires,
.idle_hits = m_state->idle_hits,
.idle_evictions = m_state->idle_evictions,
.closed_dirty = m_state->closed_dirty,
};
}
} // namespace Void::Net
+305 -1
View File
@@ -1,9 +1,20 @@
#include <Void/Net/Server.hpp>
#if !defined(_WIN32)
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <array>
#include <cctype>
#include <cerrno>
#include <cstring>
#include <format>
#include <set>
#include <system_error>
#include <utility>
namespace Void::Net
{
@@ -260,6 +271,21 @@ namespace Void::Net
return find_header(headers, name);
}
ServerResponse ServerResponse::from_file(std::filesystem::path path,
std::string content_type,
std::uint16_t status)
{
if (content_type.empty()) {
content_type = std::string{content_type_for(path)};
}
return ServerResponse{
.status = status,
.headers = {Header{"Content-Type", std::move(content_type)}},
.body = {},
.file_body = std::move(path),
};
}
std::optional<std::string_view>
ServerResponse::header(std::string_view name) const noexcept
{
@@ -334,6 +360,25 @@ namespace Void::Net
return std::optional<ServerResponse>{std::move(*response)};
}
std::vector<Method> Router::allowed_methods(std::string_view path) const
{
if (path.empty() || !path.starts_with('/')) {
return {};
}
const auto segments = split_path(path_only(path));
std::vector<Method> methods;
{
std::shared_lock lock{mutex_};
for (const auto& route : routes_) {
if (match_route(route.segments, segments).has_value() &&
std::ranges::find(methods, route.method) == methods.end()) {
methods.push_back(route.method);
}
}
}
return methods;
}
std::size_t Router::size() const
{
std::shared_lock lock{mutex_};
@@ -406,6 +451,106 @@ namespace Void::Net
return "application/octet-stream";
}
OpenedStaticFile::OpenedStaticFile(int fd,
std::filesystem::path relative_path,
std::string_view content_type,
std::uint64_t size) noexcept
: fd_(fd), relative_path_(std::move(relative_path)),
content_type_(content_type), size_(size)
{
}
OpenedStaticFile::~OpenedStaticFile() noexcept { close(); }
OpenedStaticFile::OpenedStaticFile(OpenedStaticFile&& other) noexcept
: fd_(std::exchange(other.fd_, -1)),
relative_path_(std::move(other.relative_path_)),
content_type_(std::exchange(other.content_type_, {})),
size_(std::exchange(other.size_, 0))
{
}
OpenedStaticFile&
OpenedStaticFile::operator=(OpenedStaticFile&& other) noexcept
{
if (this != &other) {
close();
fd_ = std::exchange(other.fd_, -1);
relative_path_ = std::move(other.relative_path_);
content_type_ = std::exchange(other.content_type_, {});
size_ = std::exchange(other.size_, 0);
}
return *this;
}
void OpenedStaticFile::close() noexcept
{
#if !defined(_WIN32)
if (fd_ >= 0) {
(void)::close(fd_);
fd_ = -1;
}
#endif
}
Void::Result::Result<std::string>
OpenedStaticFile::read_all(std::uint64_t max_bytes) const
{
#if !defined(_WIN32)
if (fd_ < 0) {
return Void::Result::fail(
"Net::OpenedStaticFile: file descriptor is closed");
}
if (size_ > max_bytes) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
"Net::OpenedStaticFile: file size exceeds max_bytes")};
}
std::string out;
out.reserve(static_cast<std::size_t>(size_));
std::array<char, 32 * 1024> buf{};
std::uint64_t offset = 0;
for (;;) {
const ssize_t n = ::pread(fd_, buf.data(), buf.size(),
static_cast<off_t>(offset));
if (n < 0) {
if (errno == EINTR) continue;
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::OpenedStaticFile: pread failed: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
if (n == 0) {
break;
}
const auto un = static_cast<std::uint64_t>(n);
if (un > max_bytes || offset > max_bytes - un) {
return std::unexpected{make_net_error(
NetErrorCode::payload_too_large,
"Net::OpenedStaticFile: read exceeds max_bytes")};
}
out.append(buf.data(), static_cast<std::size_t>(n));
offset += un;
}
return out;
#else
(void)max_bytes;
return Void::Result::fail(
"Net::OpenedStaticFile: unsupported platform");
#endif
}
StaticFileResolver::DirHandle::~DirHandle() noexcept
{
#if !defined(_WIN32)
if (fd >= 0) {
(void)::close(fd);
fd = -1;
}
#endif
}
Void::Result::Result<StaticFileResolver>
StaticFileResolver::create(std::filesystem::path root,
std::string index_file)
@@ -424,8 +569,167 @@ namespace Void::Net
return Void::Result::fail(
"Net::StaticFileResolver: document root is not a directory");
}
std::shared_ptr<DirHandle> root_handle;
#if !defined(_WIN32)
const int dir_fd =
::open(canonical_root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (dir_fd < 0) {
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format(
"Net::StaticFileResolver: cannot open root directory: {}",
std::strerror(errno)),
std::error_code{errno, std::generic_category()})};
}
root_handle = std::make_shared<DirHandle>(dir_fd);
#endif
return StaticFileResolver{std::move(canonical_root),
std::move(index_file)};
std::move(index_file),
std::move(root_handle)};
}
Void::Result::Result<std::optional<OpenedStaticFile>>
StaticFileResolver::open_safe(std::string_view request_path) const
{
#if !defined(_WIN32)
if (!root_dir_ || root_dir_->fd < 0) {
return Void::Result::fail(
"Net::StaticFileResolver: root directory handle unavailable");
}
auto decoded = decode_url_path(request_path);
if (!decoded) {
return Void::Result::fail(std::move(decoded).error());
}
const auto segments = split_path(*decoded);
for (const auto& seg : segments) {
if (seg == "." || seg == ".." ||
seg.find('/') != std::string::npos) {
return Void::Result::fail(
"Net::StaticFileResolver: path traversal rejected");
}
}
struct ScopedFd {
int fd{-1};
bool owned{false};
~ScopedFd() noexcept
{
if (owned && fd >= 0) {
(void)::close(fd);
}
}
};
ScopedFd cur{root_dir_->fd, false};
std::filesystem::path rel_path;
// Walk intermediate directories strictly via openat + O_NOFOLLOW.
for (std::size_t i = 0; i + 1U < segments.size(); ++i) {
const int next =
::openat(cur.fd, segments[i].c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (next < 0) {
const int err = errno;
if (err == ENOENT || err == ENOTDIR) {
return std::optional<OpenedStaticFile>{};
}
if (err == ELOOP) {
return Void::Result::fail(
"Net::StaticFileResolver: symlink directory rejected");
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::StaticFileResolver: openat dir failed: "
"{}",
std::strerror(err)),
std::error_code{err, std::generic_category()})};
}
if (cur.owned && cur.fd >= 0) {
(void)::close(cur.fd);
}
cur.fd = next;
cur.owned = true;
rel_path /= segments[i];
}
// Open leaf (or index_file_ if root or directory).
int file_fd = -1;
if (segments.empty()) {
file_fd = ::openat(cur.fd, index_file_.c_str(),
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
rel_path /= index_file_;
} else {
const std::string& leaf = segments.back();
file_fd = ::openat(cur.fd, leaf.c_str(),
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
if (file_fd >= 0) {
struct stat st{};
if (::fstat(file_fd, &st) == 0 && S_ISDIR(st.st_mode)) {
const int idx_fd = ::openat(
file_fd, index_file_.c_str(),
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
(void)::close(file_fd);
file_fd = idx_fd;
rel_path /= leaf;
rel_path /= index_file_;
} else {
rel_path /= leaf;
}
} else if (errno == EISDIR) {
const int dir_fd =
::openat(cur.fd, leaf.c_str(),
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (dir_fd >= 0) {
file_fd = ::openat(dir_fd, index_file_.c_str(),
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
(void)::close(dir_fd);
rel_path /= leaf;
rel_path /= index_file_;
}
}
}
if (file_fd < 0) {
const int err = errno;
if (err == ENOENT || err == ENOTDIR) {
return std::optional<OpenedStaticFile>{};
}
if (err == ELOOP) {
return Void::Result::fail(
"Net::StaticFileResolver: symlink file rejected");
}
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::StaticFileResolver: openat file failed: {}",
std::strerror(err)),
std::error_code{err, std::generic_category()})};
}
struct stat st{};
if (::fstat(file_fd, &st) != 0) {
const int err = errno;
(void)::close(file_fd);
return std::unexpected{make_net_error(
NetErrorCode::io_error,
std::format("Net::StaticFileResolver: fstat failed: {}",
std::strerror(err)),
std::error_code{err, std::generic_category()})};
}
if (!S_ISREG(st.st_mode)) {
(void)::close(file_fd);
return std::optional<OpenedStaticFile>{};
}
const auto ct = content_type_for(rel_path);
return std::optional<OpenedStaticFile>{OpenedStaticFile{
file_fd, std::move(rel_path), ct,
static_cast<std::uint64_t>(st.st_size)}};
#else
(void)request_path;
return Void::Result::fail(
"Net::StaticFileResolver::open_safe: unsupported platform");
#endif
}
Void::Result::Result<std::optional<StaticFile>>
File diff suppressed because it is too large. Load diff
+11 -1
View File
@@ -1,5 +1,5 @@
void_add_module(Net
INTERNAL_DEPS Functional Text
INTERNAL_DEPS Functional Text Time
EXTERNAL_DEPS
Boost::headers
Boost::beast
@@ -9,3 +9,13 @@ void_add_module(Net
OpenSSL::Crypto
Threads::Threads
)
if(VOID_ENABLE_TSAN AND TARGET Void_Net)
# Boost.Asio 1.84's std_fenced_block calls std::atomic_thread_fence, which
# GCC warns is unsupported under -fsanitize=thread (-Werror=tsan). Keep
# hardware fences intact and scope the diagnostic suppression solely to
# Http.cpp so HttpServer.cpp and all other TUs keep full -Werror=tsan.
set_source_files_properties("${CMAKE_CURRENT_LIST_DIR}/Http.cpp"
PROPERTIES COMPILE_OPTIONS "$<$<CXX_COMPILER_ID:GNU>:-Wno-tsan>"
)
endif()
+339
View File
@@ -0,0 +1,339 @@
#include <Void/RPC/Codec.hpp>
#include <Void/Binary/Reader.hpp>
#include <Void/Binary/Writer.hpp>
#include <cstring>
#include <format>
#include <limits>
#include <random>
namespace Void::RPC
{
namespace
{
[[nodiscard]] bool is_valid_frame_kind(std::uint8_t raw) noexcept
{
return raw >= static_cast<std::uint8_t>(FrameKind::UnaryRequest) &&
raw <= static_cast<std::uint8_t>(FrameKind::StreamTerminal);
}
[[nodiscard]] bool is_valid_status_code(std::uint16_t raw) noexcept
{
return raw <=
static_cast<std::uint16_t>(RpcStatusCode::IncompatibleVersion);
}
} // namespace
CallId CallId::generate()
{
CallId id;
std::random_device rd;
for (std::size_t i = 0; i < 16U; i += 4U) {
const std::uint32_t v = rd();
id.bytes[i + 0] = static_cast<std::byte>((v >> 24U) & 0xFFU);
id.bytes[i + 1] = static_cast<std::byte>((v >> 16U) & 0xFFU);
id.bytes[i + 2] = static_cast<std::byte>((v >> 8U) & 0xFFU);
id.bytes[i + 3] = static_cast<std::byte>(v & 0xFFU);
}
// Mark UUIDv4 version & RFC 4122 variant bits.
id.bytes[6] = (id.bytes[6] & std::byte{0x0F}) | std::byte{0x40};
id.bytes[8] = (id.bytes[8] & std::byte{0x3F}) | std::byte{0x80};
return id;
}
Void::Result::Result<std::vector<std::byte>>
encode_envelope(const WireEnvelope& env, const RpcLimits& limits)
{
if (env.major != kWireMajorV1) {
return std::unexpected{make_rpc_error(
RpcStatusCode::IncompatibleVersion,
std::format("RPC::encode_envelope: unsupported major {}",
env.major))};
}
if ((env.flags & kFlagRequiredMask) != 0) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::encode_envelope: unsupported required flags")};
}
if (env.metadata.size() > limits.max_metadata_entries) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::encode_envelope: metadata count exceeds limit")};
}
if (env.payload.size() > limits.max_payload_bytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::encode_envelope: payload exceeds limit")};
}
// Compute exact header size with overflow checks.
std::uint64_t header_len = kWireFixedHeaderBytes;
for (const auto& entry : env.metadata) {
if (entry.key.size() > std::numeric_limits<std::uint16_t>::max() ||
entry.value.size() > std::numeric_limits<std::uint16_t>::max()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument,
"RPC::encode_envelope: metadata field exceeds uint16")};
}
header_len += 4ULL + entry.key.size() + entry.value.size();
if (header_len > limits.max_header_bytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::encode_envelope: header size exceeds limit")};
}
}
const std::uint64_t total_len = header_len + env.payload.size();
if (total_len > std::numeric_limits<std::uint32_t>::max()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::encode_envelope: total frame exceeds uint32")};
}
std::vector<std::byte> out(static_cast<std::size_t>(total_len));
Void::Binary::Writer w{out};
auto check = [](Void::Result::Result<void> r) -> bool {
return r.has_value();
};
const bool ok =
check(w.writeBytes(kWireMagic)) &&
check(w.writeBig<std::uint16_t>(env.major)) &&
check(w.writeBig<std::uint16_t>(env.minor)) &&
check(w.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(header_len))) &&
check(w.writeBig<std::uint32_t>(
static_cast<std::uint32_t>(total_len))) &&
check(w.writeBig<std::uint8_t>(
static_cast<std::uint8_t>(env.kind))) &&
check(w.writeBig<std::uint8_t>(env.flags)) &&
check(w.writeBig<std::uint16_t>(0U)) && // reserved = 0
check(w.writeBytes(env.call_id.bytes)) &&
check(w.writeBig<std::uint64_t>(env.method.service)) &&
check(w.writeBig<std::uint32_t>(env.method.method)) &&
check(w.writeBig<std::uint32_t>(env.schema_version)) &&
check(w.writeBig<std::uint32_t>(env.remaining_timeout_ms)) &&
check(w.writeBig<std::uint16_t>(
static_cast<std::uint16_t>(env.status_code))) &&
check(w.writeBig<std::uint16_t>(
static_cast<std::uint16_t>(env.metadata.size())));
if (!ok) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Internal,
"RPC::encode_envelope: header write failure")};
}
for (const auto& entry : env.metadata) {
if (!w.writeBig<std::uint16_t>(
static_cast<std::uint16_t>(entry.key.size()))
.has_value() ||
!w.writeBytes(
std::span<const std::byte>{
reinterpret_cast<const std::byte*>(entry.key.data()),
entry.key.size()})
.has_value() ||
!w.writeBig<std::uint16_t>(
static_cast<std::uint16_t>(entry.value.size()))
.has_value() ||
!w.writeBytes(
std::span<const std::byte>{
reinterpret_cast<const std::byte*>(
entry.value.data()),
entry.value.size()})
.has_value()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Internal,
"RPC::encode_envelope: metadata write failure")};
}
}
if (!env.payload.empty() && !w.writeBytes(env.payload).has_value()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Internal,
"RPC::encode_envelope: payload write failure")};
}
return out;
}
Void::Result::Result<WireEnvelope>
decode_envelope(std::span<const std::byte> bytes,
const RpcLimits& limits)
{
if (bytes.size() < kWireFixedHeaderBytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: truncated fixed header")};
}
Void::Binary::Reader r{bytes};
auto magic = r.readBytes(4U);
if (!magic.has_value() ||
std::memcmp(magic->data(), kWireMagic.data(), 4U) != 0) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: invalid VRPC magic")};
}
auto major = r.readBig<std::uint16_t>();
auto minor = r.readBig<std::uint16_t>();
auto header_len = r.readBig<std::uint32_t>();
auto total_len = r.readBig<std::uint32_t>();
auto raw_kind = r.readBig<std::uint8_t>();
auto flags = r.readBig<std::uint8_t>();
auto reserved = r.readBig<std::uint16_t>();
auto call_id_bytes = r.readBytes(16U);
auto service_id = r.readBig<std::uint64_t>();
auto method_id = r.readBig<std::uint32_t>();
auto schema_ver = r.readBig<std::uint32_t>();
auto timeout_ms = r.readBig<std::uint32_t>();
auto raw_status = r.readBig<std::uint16_t>();
auto meta_count = r.readBig<std::uint16_t>();
if (!major || !minor || !header_len || !total_len || !raw_kind ||
!flags || !reserved || !call_id_bytes || !service_id ||
!method_id || !schema_ver || !timeout_ms || !raw_status ||
!meta_count) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: truncated header fields")};
}
if (*major != kWireMajorV1) {
return std::unexpected{make_rpc_error(
RpcStatusCode::IncompatibleVersion,
std::format("RPC::decode_envelope: unsupported wire major {}",
*major))};
}
if (*reserved != 0U) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: non-zero reserved header field")};
}
if ((*flags & kFlagRequiredMask) != 0U) {
return std::unexpected{make_rpc_error(
RpcStatusCode::IncompatibleVersion,
"RPC::decode_envelope: unknown required frame flag")};
}
if (!is_valid_frame_kind(*raw_kind)) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: invalid frame kind")};
}
if (!is_valid_status_code(*raw_status)) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: invalid status code")};
}
// Validate lengths & overflow BEFORE subtracting or allocating!
if (*header_len < kWireFixedHeaderBytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: header_length smaller than fixed "
"header")};
}
if (*header_len > limits.max_header_bytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::decode_envelope: header_length exceeds limit")};
}
if (*total_len < *header_len) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: total_length smaller than "
"header_length")};
}
if (*total_len != bytes.size()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: frame length mismatch")};
}
const std::size_t payload_len =
static_cast<std::size_t>(*total_len) -
static_cast<std::size_t>(*header_len);
if (payload_len > limits.max_payload_bytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::decode_envelope: payload exceeds limit")};
}
if (*meta_count > limits.max_metadata_entries) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::decode_envelope: metadata count exceeds limit")};
}
WireEnvelope env;
env.major = *major;
env.minor = *minor;
env.kind = static_cast<FrameKind>(*raw_kind);
env.flags = *flags;
std::memcpy(env.call_id.bytes.data(), call_id_bytes->data(), 16U);
env.method = MethodId{*service_id, *method_id};
env.schema_version = *schema_ver;
env.remaining_timeout_ms = *timeout_ms;
env.status_code = static_cast<RpcStatusCode>(*raw_status);
env.metadata.reserve(*meta_count);
for (std::uint16_t i = 0; i < *meta_count; ++i) {
if (r.position() + 2U > *header_len) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: metadata overruns header_length")};
}
auto klen = r.readBig<std::uint16_t>();
if (!klen || r.position() + *klen + 2U > *header_len) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: metadata key overruns header")};
}
auto kbytes = r.readBytes(*klen);
auto vlen = r.readBig<std::uint16_t>();
if (!kbytes || !vlen || r.position() + *vlen > *header_len) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: metadata value overruns header")};
}
auto vbytes = r.readBytes(*vlen);
if (!vbytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: truncated metadata value")};
}
env.metadata.push_back(MetadataEntry{
.key = std::string{
reinterpret_cast<const char*>(kbytes->data()),
kbytes->size()},
.value = std::string{
reinterpret_cast<const char*>(vbytes->data()),
vbytes->size()},
});
}
// Minor-version optional header extensions (if minor > 0) are
// length-skippable up to `header_len`; reject unexpected bytes on
// minor == 0.
if (r.position() < *header_len) {
if (*minor == 0U) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: unexpected trailing header bytes "
"for minor 0")};
}
if (!r.seek(*header_len).has_value()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: failed to skip minor extension")};
}
}
auto pay = r.readBytes(payload_len);
if (!pay.has_value()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::decode_envelope: truncated payload")};
}
env.payload.assign(pay->begin(), pay->end());
return env;
}
} // namespace Void::RPC
+652
View File
@@ -0,0 +1,652 @@
#include <Void/RPC/Rpc.hpp>
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <cstring>
#include <exception>
#include <format>
#include <limits>
#include <map>
#include <mutex>
#include <stop_token>
#include <utility>
namespace Void::RPC
{
namespace
{
constexpr std::string_view kErrorMessageMetaKey = "x-void-rpc-error";
[[nodiscard]] OwnedBytes
encode_error_response(const WireEnvelope* req_env,
RpcStatusCode code, std::string_view message,
const RpcLimits& limits)
{
WireEnvelope resp;
resp.major = kWireMajorV1;
resp.minor = kWireMinorV1;
resp.kind = FrameKind::UnaryResponse;
resp.flags = kFlagEndOfMessage;
if (req_env != nullptr) {
resp.call_id = req_env->call_id;
resp.method = req_env->method;
resp.schema_version = req_env->schema_version;
}
resp.status_code = code;
if (!message.empty()) {
std::string clipped{message.substr(0, 512U)};
resp.metadata.push_back(MetadataEntry{
std::string{kErrorMessageMetaKey}, std::move(clipped)});
}
auto enc = encode_envelope(resp, limits);
if (enc.has_value()) {
return std::move(*enc);
}
// Fallback without metadata if limits were tight.
resp.metadata.clear();
auto fallback = encode_envelope(resp, RpcLimits{});
return fallback.has_value() ? std::move(*fallback) : OwnedBytes{};
}
} // namespace
struct Server::State {
struct BoundMethod {
std::uint64_t reg_gen{0};
MethodDescriptor desc{};
UnaryHandler handler{};
bool accepting{true};
std::size_t in_flight{0};
std::condition_variable cv{};
};
ServerOptions options{};
std::optional<Void::Net::HttpServer> owned_http{};
std::stop_source stop_source{};
mutable std::mutex mutex{};
std::condition_variable drain_cv{};
bool accepting{true};
std::uint64_t next_reg_gen{1};
std::size_t executing_calls{0};
std::size_t queued_bytes{0};
std::map<MethodId, std::shared_ptr<BoundMethod>> methods{};
void unregister_and_drain(MethodId id, std::uint64_t gen) noexcept
{
std::shared_ptr<BoundMethod> target;
{
std::unique_lock lock{mutex};
const auto it = methods.find(id);
if (it == methods.end() || it->second->reg_gen != gen) {
return;
}
target = it->second;
target->accepting = false;
methods.erase(it);
target->cv.wait(lock,
[&] { return target->in_flight == 0; });
}
}
[[nodiscard]] OwnedBytes dispatch_raw(
std::span<const std::byte> request_bytes,
const std::vector<Void::Net::Header>& transport_headers)
{
auto decoded = decode_envelope(request_bytes, options.limits);
if (!decoded.has_value()) {
return encode_error_response(
nullptr, rpc_status_from_error(decoded.error()),
decoded.error().message(), options.limits);
}
WireEnvelope req = std::move(*decoded);
if (req.kind != FrameKind::UnaryRequest) {
return encode_error_response(
&req, RpcStatusCode::ProtocolError,
"RPC::Server: expected UnaryRequest frame",
options.limits);
}
std::shared_ptr<BoundMethod> bound;
MethodDescriptor desc;
UnaryHandler handler;
const std::size_t payload_sz = req.payload.size();
{
std::lock_guard lock{mutex};
if (!accepting) {
return encode_error_response(
&req, RpcStatusCode::Unavailable,
"RPC::Server: server shutting down",
options.limits);
}
const auto it = methods.find(req.method);
if (it == methods.end() || !it->second->accepting) {
return encode_error_response(
&req, RpcStatusCode::Unimplemented,
"RPC::Server: unknown method", options.limits);
}
if (req.schema_version != it->second->desc.schema_version) {
return encode_error_response(
&req, RpcStatusCode::IncompatibleVersion,
std::format("RPC::Server: schema version mismatch "
"(got {}, expected {})",
req.schema_version,
it->second->desc.schema_version),
options.limits);
}
if (executing_calls >=
options.limits.max_server_executing ||
payload_sz > options.limits.max_server_queued_bytes ||
queued_bytes >
options.limits.max_server_queued_bytes -
payload_sz) {
return encode_error_response(
&req, RpcStatusCode::ResourceExhausted,
"RPC::Server: concurrency or payload budget "
"exhausted",
options.limits);
}
bound = it->second;
desc = bound->desc;
handler = bound->handler;
++bound->in_flight;
++executing_calls;
queued_bytes += payload_sz;
}
struct InFlightGuard {
State* st;
std::shared_ptr<BoundMethod> bm;
std::size_t bytes;
~InFlightGuard() noexcept
{
std::lock_guard lock{st->mutex};
if (bm->in_flight > 0) {
--bm->in_flight;
}
if (bm->in_flight == 0) {
bm->cv.notify_all();
}
if (st->executing_calls > 0) {
--st->executing_calls;
}
if (st->queued_bytes >= bytes) {
st->queued_bytes -= bytes;
} else {
st->queued_bytes = 0;
}
if (st->executing_calls == 0) {
st->drain_cv.notify_all();
}
}
} guard{this, bound, payload_sz};
// Execute authentication & authorization OUTSIDE dispatch locks.
PrincipalView principal;
if (options.auth.authenticate) {
auto ar =
options.auth.authenticate(transport_headers, req.metadata);
if (!ar.has_value()) {
return encode_error_response(
&req, RpcStatusCode::Unauthenticated,
ar.error().message(), options.limits);
}
principal = std::move(*ar);
}
if (options.auth.authorize) {
auto az = options.auth.authorize(desc, principal);
if (!az.has_value()) {
return encode_error_response(
&req, RpcStatusCode::PermissionDenied,
az.error().message(), options.limits);
}
}
// Convert relative timeout into local steady deadline clamped
// to `limits.max_server_timeout`.
const auto* clk =
options.clock != nullptr
? options.clock
: &Void::Time::SystemMonotonicClock::instance();
std::chrono::milliseconds rel_timeout =
req.remaining_timeout_ms > 0
? std::chrono::milliseconds{req.remaining_timeout_ms}
: options.limits.max_server_timeout;
if (rel_timeout > options.limits.max_server_timeout) {
rel_timeout = options.limits.max_server_timeout;
}
CallContext ctx;
ctx.call_id = req.call_id;
ctx.method = desc;
ctx.principal = std::move(principal);
ctx.clock = clk;
ctx.deadline = clk->now() + rel_timeout;
ctx.metadata = std::move(req.metadata);
ctx.stop = stop_source.get_token();
Void::Result::Result<OwnedBytes> handler_res =
std::unexpected{make_rpc_error(RpcStatusCode::Internal,
"uninitialized")};
try {
handler_res = handler(ctx, std::move(req.payload));
} catch (const std::exception&) {
// Sanitized error — never leak internal exception text.
return encode_error_response(
&req, RpcStatusCode::Internal,
"RPC::Server: internal handler error", options.limits);
} catch (...) {
return encode_error_response(
&req, RpcStatusCode::Internal,
"RPC::Server: internal handler error", options.limits);
}
if (!handler_res.has_value()) {
return encode_error_response(
&req, rpc_status_from_error(handler_res.error()),
handler_res.error().message(), options.limits);
}
WireEnvelope resp;
resp.major = kWireMajorV1;
resp.minor = kWireMinorV1;
resp.kind = FrameKind::UnaryResponse;
resp.flags = kFlagEndOfMessage;
resp.call_id = req.call_id;
resp.method = req.method;
resp.schema_version = desc.schema_version;
resp.status_code = RpcStatusCode::Ok;
resp.payload = std::move(*handler_res);
auto encoded = encode_envelope(resp, options.limits);
if (!encoded.has_value()) {
return encode_error_response(
&req, rpc_status_from_error(encoded.error()),
encoded.error().message(), options.limits);
}
return std::move(*encoded);
}
};
// ── Registration ────────────────────────────────────────────────────────
Registration::~Registration() noexcept { unregister_and_drain(); }
Registration::Registration(Registration&& other) noexcept
: m_server_state(std::move(other.m_server_state)),
m_id(std::exchange(other.m_id, MethodId{})),
m_reg_gen(std::exchange(other.m_reg_gen, 0)),
m_active(std::exchange(other.m_active, false))
{
}
Registration& Registration::operator=(Registration&& other) noexcept
{
if (this != &other) {
unregister_and_drain();
m_server_state = std::move(other.m_server_state);
m_id = std::exchange(other.m_id, MethodId{});
m_reg_gen = std::exchange(other.m_reg_gen, 0);
m_active = std::exchange(other.m_active, false);
}
return *this;
}
bool Registration::active() const noexcept { return m_active; }
void Registration::unregister_and_drain() noexcept
{
if (!m_active) {
return;
}
m_active = false;
auto st =
std::static_pointer_cast<Server::State>(std::move(m_server_state));
if (st) {
st->unregister_and_drain(m_id, m_reg_gen);
}
}
// ── Server ──────────────────────────────────────────────────────────────
Server::Server(ServerOptions options) : m_state(std::make_shared<State>())
{
m_state->options = std::move(options);
if (m_state->options.http_options.max_body_bytes <
m_state->options.limits.max_header_bytes +
m_state->options.limits.max_payload_bytes) {
m_state->options.http_options.max_body_bytes =
m_state->options.limits.max_header_bytes +
m_state->options.limits.max_payload_bytes;
}
}
Server::~Server() noexcept { shutdown(std::chrono::seconds{5}); }
Server::Server(Server&&) noexcept = default;
Server& Server::operator=(Server&&) noexcept = default;
Void::Result::Result<Registration>
Server::bind(MethodDescriptor descriptor, UnaryHandler handler)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
if (!handler) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument,
"RPC::Server: handler cannot be empty")};
}
if (descriptor.id.service == 0 || descriptor.id.method == 0) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument,
"RPC::Server: service and method IDs must be non-zero")};
}
std::lock_guard lock{m_state->mutex};
if (!m_state->accepting) {
return std::unexpected{make_rpc_error(
RpcStatusCode::FailedPrecondition,
"RPC::Server: cannot bind after shutdown")};
}
if (m_state->methods.contains(descriptor.id)) {
return std::unexpected{make_rpc_error(
RpcStatusCode::FailedPrecondition,
"RPC::Server: method ID already bound")};
}
const std::uint64_t gen = m_state->next_reg_gen++;
auto bm = std::make_shared<State::BoundMethod>();
bm->reg_gen = gen;
bm->desc = std::move(descriptor);
bm->handler = std::move(handler);
const MethodId mid = bm->desc.id;
m_state->methods.emplace(mid, std::move(bm));
Registration reg;
reg.m_server_state = m_state;
reg.m_id = mid;
reg.m_reg_gen = gen;
reg.m_active = true;
return reg;
}
Void::Result::Result<void> Server::mount(Void::Net::HttpServer& http_server)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
std::weak_ptr<State> weak_state = m_state;
return http_server.add_route(
Void::Net::Method::Post, std::string{kUnaryHttpPath},
[weak_state](const Void::Net::ServerRequest& req)
-> Void::Net::RouteResult {
auto st = weak_state.lock();
if (!st) {
return Void::Net::ServerResponse{
.status = 503, .body = "RPC server unavailable"};
}
const auto req_bytes = std::span<const std::byte>{
reinterpret_cast<const std::byte*>(req.body.data()),
req.body.size()};
auto resp_bytes = st->dispatch_raw(req_bytes, req.headers);
std::string body_str(
reinterpret_cast<const char*>(resp_bytes.data()),
resp_bytes.size());
return Void::Net::ServerResponse{
.status = 200,
.headers = {Void::Net::Header{
"Content-Type", std::string{kWireContentType}}},
.body = std::move(body_str),
};
});
}
Void::Result::Result<void> Server::start()
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
if (m_state->owned_http.has_value() && m_state->owned_http->running()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::FailedPrecondition,
"RPC::Server: already running")};
}
m_state->owned_http.emplace(m_state->options.http_options);
auto mr = mount(*m_state->owned_http);
if (!mr.has_value()) {
m_state->owned_http.reset();
return mr;
}
auto sr = m_state->owned_http->start();
if (!sr.has_value()) {
m_state->owned_http.reset();
return sr;
}
return {};
}
void Server::shutdown(std::chrono::milliseconds drain_timeout) noexcept
{
if (!m_state) {
return;
}
{
std::lock_guard lock{m_state->mutex};
m_state->accepting = false;
for (auto& [id, bm] : m_state->methods) {
(void)id;
bm->accepting = false;
}
}
if (m_state->owned_http.has_value()) {
m_state->owned_http->shutdown(drain_timeout);
}
{
std::unique_lock lock{m_state->mutex};
if (!m_state->drain_cv.wait_for(
lock, drain_timeout,
[&] { return m_state->executing_calls == 0; })) {
m_state->stop_source.request_stop();
m_state->drain_cv.wait(
lock, [&] { return m_state->executing_calls == 0; });
}
m_state->methods.clear();
}
}
bool Server::running() const noexcept
{
return m_state && m_state->owned_http.has_value() &&
m_state->owned_http->running();
}
std::uint16_t Server::bound_port() const noexcept
{
return (m_state && m_state->owned_http.has_value())
? m_state->owned_http->bound_port()
: 0;
}
std::string Server::base_url() const
{
return (m_state && m_state->owned_http.has_value())
? m_state->owned_http->base_url()
: std::string{};
}
Void::Result::Result<OwnedBytes> Server::handle_raw_envelope(
std::span<const std::byte> request_bytes,
const std::vector<Void::Net::Header>& transport_headers)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
return m_state->dispatch_raw(request_bytes, transport_headers);
}
// ── Client ──────────────────────────────────────────────────────────────
struct Client::State {
ClientOptions options{};
Void::Net::HttpClient http_client{};
std::atomic<std::size_t> in_flight{0};
};
Client::Client(ClientOptions options) : m_state(std::make_shared<State>())
{
while (options.endpoint_base_url.size() > 1U &&
options.endpoint_base_url.back() == '/') {
options.endpoint_base_url.pop_back();
}
options.http_options.max_body_size =
options.limits.max_header_bytes + options.limits.max_payload_bytes;
m_state->http_client = Void::Net::HttpClient{options.http_options};
m_state->options = std::move(options);
}
Client::~Client() noexcept = default;
Client::Client(Client&&) noexcept = default;
Client& Client::operator=(Client&&) noexcept = default;
std::size_t Client::in_flight_calls() const noexcept
{
return m_state ? m_state->in_flight.load(std::memory_order_acquire) : 0;
}
Void::Result::Result<OwnedBytes>
Client::call(MethodId method, OwnedBytes payload,
const CallOptions& options)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Client: moved-from")};
}
if (options.stop.stop_requested()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Cancelled, "RPC::Client: call cancelled")};
}
if (payload.size() > m_state->options.limits.max_payload_bytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::Client: request payload exceeds max_payload_bytes")};
}
// Acquire client concurrency slot.
std::size_t cur = m_state->in_flight.load(std::memory_order_relaxed);
for (;;) {
if (cur >= m_state->options.limits.max_client_calls) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::Client: max_client_calls reached")};
}
if (m_state->in_flight.compare_exchange_weak(
cur, cur + 1U, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
break;
}
}
struct ClientSlot {
std::atomic<std::size_t>* count;
~ClientSlot() noexcept
{
count->fetch_sub(1, std::memory_order_acq_rel);
}
} slot{&m_state->in_flight};
WireEnvelope env;
env.major = kWireMajorV1;
env.minor = kWireMinorV1;
env.kind = FrameKind::UnaryRequest;
env.flags = kFlagEndOfMessage;
env.call_id = CallId::generate();
env.method = method;
env.schema_version = options.schema_version;
const auto ms = std::clamp<long long>(
options.timeout.count(), 0,
static_cast<long long>(std::numeric_limits<std::uint32_t>::max()));
env.remaining_timeout_ms = static_cast<std::uint32_t>(ms);
env.metadata = options.metadata;
env.payload = std::move(payload);
auto encoded = encode_envelope(env, m_state->options.limits);
if (!encoded.has_value()) {
return std::unexpected{std::move(encoded.error())};
}
Void::Net::Request http_req;
http_req.method = Void::Net::Method::Post;
http_req.url =
m_state->options.endpoint_base_url + std::string{kUnaryHttpPath};
http_req.headers = options.transport_headers;
http_req.headers.push_back(Void::Net::Header{
"Content-Type", std::string{kWireContentType}});
http_req.body = std::string(
reinterpret_cast<const char*>(encoded->data()), encoded->size());
http_req.timeout = std::chrono::seconds{
std::max<long long>(1, (options.timeout.count() + 999) / 1000)};
auto http_resp = m_state->http_client.send(http_req);
if (!http_resp.has_value()) {
if (http_resp.error().kind() == Void::Result::ErrorKind::timeout) {
return std::unexpected{make_rpc_error(
RpcStatusCode::DeadlineExceeded,
std::format("RPC::Client: call timed out (remote commit "
"unknown): {}",
http_resp.error().message()))};
}
if (http_resp.error().kind() ==
Void::Result::ErrorKind::cancelled) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Cancelled,
std::format("RPC::Client: call cancelled: {}",
http_resp.error().message()))};
}
return std::unexpected{make_rpc_error(
RpcStatusCode::Unavailable,
std::format("RPC::Client: transport failed: {}",
http_resp.error().message()))};
}
if (http_resp->status != 200) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Unavailable,
std::format("RPC::Client: HTTP transport status {}",
http_resp->status))};
}
const auto resp_span = std::span<const std::byte>{
reinterpret_cast<const std::byte*>(http_resp->body.data()),
http_resp->body.size()};
auto resp_env = decode_envelope(resp_span, m_state->options.limits);
if (!resp_env.has_value()) {
return std::unexpected{std::move(resp_env.error())};
}
if (resp_env->kind != FrameKind::UnaryResponse) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::Client: expected UnaryResponse frame")};
}
if (resp_env->call_id != env.call_id) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::Client: response call_id mismatch")};
}
if (resp_env->status_code != RpcStatusCode::Ok) {
std::string msg = "RPC domain error";
for (const auto& m : resp_env->metadata) {
if (m.key == kErrorMessageMetaKey) {
msg = m.value;
break;
}
}
return std::unexpected{
make_rpc_error(resp_env->status_code, std::move(msg))};
}
return std::move(resp_env->payload);
}
} // namespace Void::RPC
+3
View File
@@ -0,0 +1,3 @@
void_add_module(RPC
INTERNAL_DEPS Core Functional Binary Data Time Async Net
)
+632
View File
@@ -0,0 +1,632 @@
#include <Void/Scheduler/Calendar.hpp>
#include <algorithm>
#include <charconv>
#include <limits>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Scheduler
{
namespace
{
// Howard Hinnant's exact civil-from-days / days-from-civil algorithms.
[[nodiscard]] constexpr std::int64_t
days_from_civil(std::int32_t y, std::uint32_t m,
std::uint32_t d) noexcept
{
const std::int64_t y_adj = static_cast<std::int64_t>(y) - (m <= 2);
const std::int64_t era =
(y_adj >= 0 ? y_adj : y_adj - 399) / 400;
const auto yoe =
static_cast<std::uint64_t>(y_adj - era * 400); // [0, 399]
const std::uint64_t doy =
(153U * (m + (m > 2 ? static_cast<std::uint32_t>(-3) : 9U)) +
2U) /
5U +
d - 1U; // [0, 365]
const std::uint64_t doe =
yoe * 365U + yoe / 4U - yoe / 100U + doy; // [0, 146096]
return era * 146097 + static_cast<std::int64_t>(doe) - 719468;
}
[[nodiscard]] constexpr bool is_leap_year(std::int32_t y) noexcept
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
[[nodiscard]] constexpr std::uint32_t
days_in_month(std::int32_t y, std::uint32_t m) noexcept
{
switch (m) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31U;
case 4:
case 6:
case 9:
case 11:
return 30U;
case 2:
return is_leap_year(y) ? 29U : 28U;
default:
return 30U;
}
}
[[nodiscard]] std::optional<std::int32_t>
parse_fixed_offset_minutes(std::string_view tz) noexcept
{
if (tz == "UTC" || tz == "Z") {
return 0;
}
if (tz.starts_with("UTC")) {
tz.remove_prefix(3U);
}
if (tz.size() != 6U || (tz[0] != '+' && tz[0] != '-') ||
tz[3] != ':') {
return std::nullopt;
}
const int sign = tz[0] == '-' ? -1 : 1;
std::uint32_t hh = 0;
std::uint32_t mm = 0;
auto r1 = std::from_chars(tz.data() + 1, tz.data() + 3, hh);
auto r2 = std::from_chars(tz.data() + 4, tz.data() + 6, mm);
if (r1.ec != std::errc{} || r1.ptr != tz.data() + 3 ||
r2.ec != std::errc{} || r2.ptr != tz.data() + 6 || hh > 14U ||
mm > 59U || (hh == 14U && mm > 0U)) {
return std::nullopt;
}
return sign * static_cast<std::int32_t>(hh * 60U + mm);
}
[[nodiscard]] Result<std::uint64_t> parse_field(std::string_view field,
std::uint32_t min_val,
std::uint32_t max_val,
bool map_7_to_0 = false)
{
if (field.empty()) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar empty field"));
}
std::uint64_t mask = 0;
std::size_t pos = 0;
while (pos <= field.size()) {
const std::size_t comma = field.find(',', pos);
const std::string_view part =
comma == std::string_view::npos
? field.substr(pos)
: field.substr(pos, comma - pos);
if (part.empty()) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar empty list item"));
}
std::string_view range_part = part;
std::uint32_t step = 1;
if (const std::size_t slash = part.find('/');
slash != std::string_view::npos) {
range_part = part.substr(0, slash);
const std::string_view step_sv = part.substr(slash + 1);
if (step_sv.empty() || step_sv.find('/') !=
std::string_view::npos) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar invalid step syntax"));
}
auto sr = std::from_chars(
step_sv.data(), step_sv.data() + step_sv.size(), step);
if (sr.ec != std::errc{} ||
sr.ptr != step_sv.data() + step_sv.size() ||
step == 0U) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar step must be positive"));
}
}
std::uint32_t lo = min_val;
std::uint32_t hi = max_val;
const std::uint32_t parse_max = map_7_to_0 ? 7U : max_val;
if (range_part == "*") {
lo = min_val;
hi = max_val;
} else if (const std::size_t dash = range_part.find('-');
dash != std::string_view::npos) {
const std::string_view a_sv = range_part.substr(0, dash);
const std::string_view b_sv = range_part.substr(dash + 1);
if (a_sv.empty() || b_sv.empty() ||
b_sv.find('-') != std::string_view::npos) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar invalid range syntax"));
}
auto r1 = std::from_chars(
a_sv.data(), a_sv.data() + a_sv.size(), lo);
auto r2 = std::from_chars(
b_sv.data(), b_sv.data() + b_sv.size(), hi);
if (r1.ec != std::errc{} ||
r1.ptr != a_sv.data() + a_sv.size() ||
r2.ec != std::errc{} ||
r2.ptr != b_sv.data() + b_sv.size() || lo < min_val ||
hi > parse_max || lo > hi) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar range bounds invalid"));
}
} else {
std::uint32_t val = 0;
auto rv = std::from_chars(
range_part.data(),
range_part.data() + range_part.size(), val);
if (rv.ec != std::errc{} ||
rv.ptr != range_part.data() + range_part.size() ||
val < min_val || val > parse_max) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar field value out of range"));
}
lo = val;
hi = (part.find('/') != std::string_view::npos) ? max_val
: val;
}
for (std::uint32_t v = lo; v <= hi; v += step) {
const std::uint32_t bit =
(map_7_to_0 && v == 7U) ? 0U : v;
mask |= (1ULL << bit);
if (hi - v < step) {
break;
}
}
if (comma == std::string_view::npos) {
break;
}
pos = comma + 1;
}
if (mask == 0ULL) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::Calendar field matched zero values"));
}
return mask;
}
} // namespace
std::int64_t civil_to_epoch_minute(std::int32_t year, std::uint32_t month,
std::uint32_t day, std::uint32_t hour,
std::uint32_t minute) noexcept
{
const std::int64_t days = days_from_civil(year, month, day);
return days * 1440LL + static_cast<std::int64_t>(hour) * 60LL +
static_cast<std::int64_t>(minute);
}
CivilMinute epoch_minute_to_civil(std::int64_t epoch_minute) noexcept
{
std::int64_t days = epoch_minute / 1440LL;
std::int64_t rem = epoch_minute % 1440LL;
if (rem < 0) {
rem += 1440LL;
--days;
}
const auto hour = static_cast<std::uint32_t>(rem / 60LL);
const auto minute = static_cast<std::uint32_t>(rem % 60LL);
const std::int64_t z = days + 719468;
const std::int64_t era = (z >= 0 ? z : z - 146096) / 146097;
const auto doe =
static_cast<std::uint64_t>(z - era * 146097); // [0, 146096]
const std::uint64_t yoe =
(doe - doe / 1460U + doe / 36524U - doe / 146096U) /
365U; // [0, 399]
const std::int64_t y = static_cast<std::int64_t>(yoe) + era * 400;
const std::uint64_t doy =
doe - (365U * yoe + yoe / 4U - yoe / 100U); // [0, 365]
const std::uint64_t mp = (5U * doy + 2U) / 153U; // [0, 11]
const auto d = static_cast<std::uint32_t>(
doy - (153U * mp + 2U) / 5U + 1U); // [1, 31]
const auto m =
static_cast<std::uint32_t>(mp < 10U ? mp + 3U : mp - 9U); // [1, 12]
const auto year = static_cast<std::int32_t>(y + (m <= 2U ? 1 : 0));
// 1970-01-01 was Thursday (4).
std::int64_t wd = (days + 4LL) % 7LL;
if (wd < 0) {
wd += 7LL;
}
return CivilMinute{
.year = year,
.month = m,
.day = d,
.hour = hour,
.minute = minute,
.weekday = static_cast<std::uint32_t>(wd),
};
}
// ── TimezoneRegistry ──────────────────────────────────────────────────────
void TimezoneRegistry::register_dst_zone(DstTransitionRule rule)
{
if (!rule.name.empty()) {
m_dst_zones[rule.name] = std::move(rule);
}
}
Result<void> TimezoneRegistry::validate_timezone(std::string_view tz) const
{
if (parse_fixed_offset_minutes(tz).has_value() ||
m_dst_zones.contains(tz)) {
return {};
}
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::UnsupportedTimezone,
"Scheduler: unsupported or unknown timezone '" + std::string{tz} +
"' (silent UTC fallback is forbidden)"));
}
Result<std::vector<ResolvedSlot>> TimezoneRegistry::resolve_local_minute(
std::string_view tz, std::int64_t local_epoch_minute,
DstGapPolicy gap_policy, DstFoldPolicy fold_policy) const
{
if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) {
const std::int64_t utc_min =
local_epoch_minute - static_cast<std::int64_t>(*fixed);
return std::vector<ResolvedSlot>{
ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}};
}
auto it = m_dst_zones.find(tz);
if (it == m_dst_zones.end()) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::UnsupportedTimezone,
"Scheduler: unsupported timezone '" + std::string{tz} + "'"));
}
const auto& rule = it->second;
// Check spring-forward gap window.
if (rule.gap_start_local_min.has_value() &&
rule.gap_end_local_min.has_value() &&
local_epoch_minute >= *rule.gap_start_local_min &&
local_epoch_minute < *rule.gap_end_local_min) {
if (gap_policy == DstGapPolicy::Skip) {
return std::vector<ResolvedSlot>{};
}
const std::int64_t shifted_utc_min =
*rule.gap_end_local_min -
static_cast<std::int64_t>(rule.dst_offset_minutes);
return std::vector<ResolvedSlot>{ResolvedSlot{
.utc_ms = shifted_utc_min * 60000LL,
.fold_index = 0,
}};
}
// Check fall-back fold window.
if (rule.fold_start_local_min.has_value() &&
rule.fold_end_local_min.has_value() &&
local_epoch_minute >= *rule.fold_start_local_min &&
local_epoch_minute < *rule.fold_end_local_min) {
const std::int64_t first_utc_min =
local_epoch_minute -
static_cast<std::int64_t>(rule.dst_offset_minutes);
const std::int64_t second_utc_min =
local_epoch_minute -
static_cast<std::int64_t>(rule.standard_offset_minutes);
switch (fold_policy) {
case DstFoldPolicy::First:
return std::vector<ResolvedSlot>{ResolvedSlot{
.utc_ms = first_utc_min * 60000LL, .fold_index = 0}};
case DstFoldPolicy::Second:
return std::vector<ResolvedSlot>{ResolvedSlot{
.utc_ms = second_utc_min * 60000LL, .fold_index = 1}};
case DstFoldPolicy::Twice:
return std::vector<ResolvedSlot>{
ResolvedSlot{.utc_ms = first_utc_min * 60000LL,
.fold_index = 0},
ResolvedSlot{.utc_ms = second_utc_min * 60000LL,
.fold_index = 1},
};
}
}
// Outside gap/fold: determine whether DST or standard offset applies.
bool in_dst = false;
if (rule.gap_end_local_min.has_value() &&
rule.fold_start_local_min.has_value()) {
in_dst = (local_epoch_minute >= *rule.gap_end_local_min &&
local_epoch_minute < *rule.fold_start_local_min);
} else if (rule.gap_end_local_min.has_value()) {
in_dst = (local_epoch_minute >= *rule.gap_end_local_min);
}
const std::int32_t off =
in_dst ? rule.dst_offset_minutes : rule.standard_offset_minutes;
const std::int64_t utc_min =
local_epoch_minute - static_cast<std::int64_t>(off);
return std::vector<ResolvedSlot>{
ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}};
}
Result<std::pair<std::int64_t, std::int64_t>>
TimezoneRegistry::local_minute_bounds(std::string_view tz,
std::int64_t utc_min_lo,
std::int64_t utc_min_hi) const
{
if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) {
return std::pair{utc_min_lo + *fixed, utc_min_hi + *fixed};
}
auto it = m_dst_zones.find(tz);
if (it == m_dst_zones.end()) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::UnsupportedTimezone,
"Scheduler: unsupported timezone '" + std::string{tz} + "'"));
}
const std::int32_t min_off = std::min(it->second.standard_offset_minutes,
it->second.dst_offset_minutes);
const std::int32_t max_off = std::max(it->second.standard_offset_minutes,
it->second.dst_offset_minutes);
return std::pair{utc_min_lo + min_off - 120LL,
utc_min_hi + max_off + 120LL};
}
// ── CalendarExpression ────────────────────────────────────────────────────
Result<CalendarExpression>
CalendarExpression::parse(std::string_view expression)
{
std::vector<std::string_view> tokens;
std::size_t i = 0;
while (i < expression.size()) {
while (i < expression.size() &&
(expression[i] == ' ' || expression[i] == '\t')) {
++i;
}
if (i >= expression.size()) {
break;
}
const std::size_t start = i;
while (i < expression.size() && expression[i] != ' ' &&
expression[i] != '\t') {
++i;
}
tokens.push_back(expression.substr(start, i - start));
}
if (tokens.size() != 5U) {
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::InvalidRule,
"Scheduler::CalendarExpression requires exactly 5 fields "
"(minute hour day month weekday)"));
}
auto min_m = parse_field(tokens[0], 0, 59);
if (!min_m.has_value()) return Void::Result::fail(min_m.error());
auto hr_m = parse_field(tokens[1], 0, 23);
if (!hr_m.has_value()) return Void::Result::fail(hr_m.error());
auto day_m = parse_field(tokens[2], 1, 31);
if (!day_m.has_value()) return Void::Result::fail(day_m.error());
auto mon_m = parse_field(tokens[3], 1, 12);
if (!mon_m.has_value()) return Void::Result::fail(mon_m.error());
auto wd_m = parse_field(tokens[4], 0, 6, true);
if (!wd_m.has_value()) return Void::Result::fail(wd_m.error());
CalendarExpression expr{};
expr.m_minutes = *min_m;
expr.m_hours = static_cast<std::uint32_t>(*hr_m);
expr.m_days = static_cast<std::uint32_t>(*day_m);
expr.m_months = static_cast<std::uint32_t>(*mon_m);
expr.m_weekdays = static_cast<std::uint32_t>(*wd_m);
return expr;
}
bool CalendarExpression::matches(const CivilMinute& cm) const noexcept
{
return ((m_minutes & (1ULL << cm.minute)) != 0ULL) &&
((m_hours & (1U << cm.hour)) != 0U) &&
((m_days & (1U << cm.day)) != 0U) &&
((m_months & (1U << cm.month)) != 0U) &&
((m_weekdays & (1U << cm.weekday)) != 0U);
}
std::optional<std::int64_t> CalendarExpression::next_matching_minute(
std::int64_t from_local_min, std::int64_t max_local_min) const noexcept
{
if (from_local_min > max_local_min) {
return std::nullopt;
}
std::int64_t cur = from_local_min;
// Guard iteration count against unsatisfiable combinations (e.g. Feb 31).
for (int guard = 0; guard < 100000 && cur <= max_local_min; ++guard) {
const CivilMinute cm = epoch_minute_to_civil(cur);
if ((m_months & (1U << cm.month)) == 0U) {
std::int32_t ny = cm.year;
std::uint32_t nm = cm.month + 1U;
if (nm > 12U) {
nm = 1U;
++ny;
}
cur = civil_to_epoch_minute(ny, nm, 1U, 0U, 0U);
continue;
}
if ((m_days & (1U << cm.day)) == 0U ||
(m_weekdays & (1U << cm.weekday)) == 0U) {
// Jump to 00:00 of next day.
const std::int64_t next_day_min =
civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) +
1440LL;
cur = next_day_min;
continue;
}
if ((m_hours & (1U << cm.hour)) == 0U) {
const std::int64_t next_hr_min =
civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour,
0U) +
60LL;
cur = next_hr_min;
continue;
}
if ((m_minutes & (1ULL << cm.minute)) == 0U) {
++cur;
continue;
}
return cur;
}
return std::nullopt;
}
std::optional<std::int64_t> CalendarExpression::prev_matching_minute(
std::int64_t from_local_min, std::int64_t min_local_min) const noexcept
{
if (from_local_min < min_local_min) {
return std::nullopt;
}
std::int64_t cur = from_local_min;
for (int guard = 0; guard < 100000 && cur >= min_local_min; ++guard) {
const CivilMinute cm = epoch_minute_to_civil(cur);
if ((m_months & (1U << cm.month)) == 0U) {
std::int32_t py = cm.year;
std::uint32_t pm = cm.month - 1U;
if (pm == 0U) {
pm = 12U;
--py;
}
cur = civil_to_epoch_minute(py, pm, days_in_month(py, pm), 23U,
59U);
continue;
}
if ((m_days & (1U << cm.day)) == 0U ||
(m_weekdays & (1U << cm.weekday)) == 0U) {
// Jump to 23:59 of previous day.
cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) -
1LL;
continue;
}
if ((m_hours & (1U << cm.hour)) == 0U) {
cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour,
0U) -
1LL;
continue;
}
if ((m_minutes & (1ULL << cm.minute)) == 0U) {
--cur;
continue;
}
return cur;
}
return std::nullopt;
}
Result<MaterializedSlots> CalendarExpression::materialize_range(
const CalendarSpec& spec, const TimezoneRegistry& tz_registry,
std::int64_t after_utc_ms, std::int64_t up_to_utc_ms,
MisfirePolicy misfire, std::size_t max_catch_up) const
{
if (auto tz_ok = tz_registry.validate_timezone(spec.timezone);
!tz_ok.has_value()) {
return Void::Result::fail(tz_ok.error());
}
MaterializedSlots out{};
out.next_cursor_utc_ms = after_utc_ms;
if (up_to_utc_ms <= after_utc_ms) {
return out;
}
const std::int64_t utc_min_lo = after_utc_ms / 60000LL - 1LL;
const std::int64_t utc_min_hi = up_to_utc_ms / 60000LL + 1LL;
auto bounds =
tz_registry.local_minute_bounds(spec.timezone, utc_min_lo, utc_min_hi);
if (!bounds.has_value()) {
return Void::Result::fail(bounds.error());
}
const auto [local_lo, local_hi] = *bounds;
if (misfire == MisfirePolicy::Skip) {
out.next_cursor_utc_ms = up_to_utc_ms;
return out;
}
if (misfire == MisfirePolicy::CoalesceLatest) {
// Scan backward from local_hi to coalesce arbitrarily many missed
// slots (even millions) in bounded O(1) jumps!
std::int64_t probe = local_hi;
std::optional<ResolvedSlot> best{};
while (probe >= local_lo) {
auto found = prev_matching_minute(probe, local_lo);
if (!found.has_value()) {
break;
}
auto resolved = tz_registry.resolve_local_minute(
spec.timezone, *found, spec.gap_policy, spec.fold_policy);
if (!resolved.has_value()) {
return Void::Result::fail(resolved.error());
}
for (const auto& slot : *resolved) {
if (slot.utc_ms > after_utc_ms &&
slot.utc_ms <= up_to_utc_ms) {
if (!best.has_value() ||
slot.utc_ms > best->utc_ms ||
(slot.utc_ms == best->utc_ms &&
slot.fold_index > best->fold_index)) {
best = slot;
}
}
}
if (best.has_value()) {
break;
}
probe = *found - 1LL;
}
if (best.has_value()) {
out.slots.push_back(*best);
}
out.next_cursor_utc_ms = up_to_utc_ms;
return out;
}
// CatchUpBounded: scan forward up to `max_catch_up` slots, preserving
// remaining cursor state when more slots remain!
const std::size_t cap = max_catch_up > 0U ? max_catch_up : 1U;
std::int64_t probe = local_lo;
while (probe <= local_hi) {
auto found = next_matching_minute(probe, local_hi);
if (!found.has_value()) {
break;
}
auto resolved = tz_registry.resolve_local_minute(
spec.timezone, *found, spec.gap_policy, spec.fold_policy);
if (!resolved.has_value()) {
return Void::Result::fail(resolved.error());
}
for (const auto& slot : *resolved) {
if (slot.utc_ms > after_utc_ms && slot.utc_ms <= up_to_utc_ms) {
if (out.slots.size() < cap) {
out.slots.push_back(slot);
out.next_cursor_utc_ms =
std::max(out.next_cursor_utc_ms, slot.utc_ms);
} else {
out.more_pending = true;
return out;
}
}
}
probe = *found + 1LL;
}
out.next_cursor_utc_ms = up_to_utc_ms;
return out;
}
} // namespace Void::Scheduler
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(Scheduler
INTERNAL_DEPS Core Functional Time Async
)
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
void_add_module(SchedulerStorage
INTERNAL_DEPS Scheduler Storage
)
+1 -1
View File
@@ -1,3 +1,3 @@
void_add_module(ShortUrl
INTERNAL_DEPS Service
INTERNAL_DEPS Service Time
)
+368
View File
@@ -0,0 +1,368 @@
#include <Void/ShortUrlRemote/RemoteProvider.hpp>
#include <Void/Data/StrictJson.hpp>
#include <charconv>
#include <format>
#include <string>
#include <string_view>
namespace Void::ShortUrl::V2
{
namespace
{
[[nodiscard]] std::uint32_t
parse_retry_after(const Void::Net::Response& resp) noexcept
{
auto hdr = resp.header("Retry-After");
if (!hdr.has_value() || hdr->empty()) {
return 0;
}
std::uint32_t sec = 0;
const auto [ptr, ec] =
std::from_chars(hdr->data(), hdr->data() + hdr->size(), sec);
if (ec != std::errc{} || ptr != hdr->data() + hdr->size()) {
return 0;
}
return sec;
}
[[nodiscard]] const std::string*
find_string(const Void::Json::Strict::Value::Object& obj,
std::string_view key) noexcept
{
const auto it = obj.find(key);
if (it == obj.end()) {
return nullptr;
}
return std::get_if<std::string>(&it->second.value);
}
[[nodiscard]] std::optional<std::int64_t>
find_i64(const Void::Json::Strict::Value::Object& obj,
std::string_view key) noexcept
{
const auto it = obj.find(key);
if (it == obj.end()) {
return std::nullopt;
}
if (const auto* v = std::get_if<std::int64_t>(&it->second.value)) {
return *v;
}
return std::nullopt;
}
[[nodiscard]] V2ErrorCode
map_http_status_to_v2(std::uint16_t status) noexcept
{
switch (status) {
case 400: return V2ErrorCode::InvalidRequest;
case 401:
case 403: return V2ErrorCode::Unauthorized;
case 404: return V2ErrorCode::NotFound;
case 408: return V2ErrorCode::Timeout;
case 409: return V2ErrorCode::Conflict;
case 410: return V2ErrorCode::Revoked;
case 413: return V2ErrorCode::ResponseTooLarge;
case 422: return V2ErrorCode::InvalidUrl;
case 429: return V2ErrorCode::RateLimited;
case 501: return V2ErrorCode::Unsupported;
case 503: return V2ErrorCode::Unavailable;
case 504: return V2ErrorCode::Timeout;
default: return V2ErrorCode::ProviderError;
}
}
} // namespace
RemoteProvider::RemoteProvider(RemoteProviderOptions options)
: m_options(std::move(options)), m_client(m_options.http_options)
{
while (m_options.base_url.size() > 1U &&
m_options.base_url.back() == '/') {
m_options.base_url.pop_back();
}
m_client.set_max_body_size(m_options.max_response_bytes);
}
std::string_view RemoteProvider::provider_id() const noexcept
{
return m_options.provider_id;
}
V1::Health RemoteProvider::health() const
{
if (m_options.base_url.empty()) {
return {V1::HealthStatus::unhealthy, "empty remote base_url"};
}
return {V1::HealthStatus::healthy, "remote provider configured"};
}
bool RemoteProvider::supports_resolve() const noexcept
{
return m_options.capabilities.supports_resolve;
}
std::uint32_t RemoteProvider::last_retry_after_seconds() const noexcept
{
return m_last_retry_after.load(std::memory_order_acquire);
}
Void::Result::Result<Link>
RemoteProvider::shorten(const CreateLink& request,
const ShortenOptions& options)
{
m_last_retry_after.store(0, std::memory_order_release);
// Check capability flags BEFORE any network mutation.
if (!request.custom_key.empty() &&
!m_options.capabilities.supports_custom_key) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support custom keys")};
}
if (request.expires_at_unix_seconds != 0 &&
!m_options.capabilities.supports_expiry) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support link expiry")};
}
if (auto u = validate_target_url(request.target_url); !u.has_value()) {
return std::unexpected{std::move(u.error())};
}
if (!request.custom_key.empty()) {
if (auto k = validate_custom_key(request.custom_key);
!k.has_value()) {
return std::unexpected{std::move(k.error())};
}
}
Void::Json::Strict::Value::Object obj;
obj.emplace("target_url",
Void::Json::Strict::Value{request.target_url});
if (!request.custom_key.empty()) {
obj.emplace("custom_key",
Void::Json::Strict::Value{request.custom_key});
}
if (request.expires_at_unix_seconds != 0) {
obj.emplace(
"expires_at_unix_seconds",
Void::Json::Strict::Value{request.expires_at_unix_seconds});
}
if (!options.operation_id.empty()) {
obj.emplace("operation_id",
Void::Json::Strict::Value{options.operation_id});
}
auto body = Void::Json::Strict::serialize(
Void::Json::Strict::Value{std::move(obj)});
if (!body.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::InvalidRequest,
std::format("ShortUrlRemote: serialize failed: {}",
body.error().message))};
}
Void::Net::Request req;
req.method = Void::Net::Method::Post;
req.url = m_options.base_url + "/v2/shorten";
req.headers = m_options.headers;
req.headers.push_back({"Content-Type", "application/json"});
if (!options.operation_id.empty()) {
req.headers.push_back({"Idempotency-Key", options.operation_id});
}
req.body = std::move(*body);
req.timeout = m_options.timeout;
auto resp = m_client.send(req);
if (!resp.has_value()) {
// Transport timeout or lost reply after mutation send: classify as
// UnknownOutcome without fabricating a local rollback or replay.
if (resp.error().kind() == Void::Result::ErrorKind::timeout ||
resp.error().kind() == Void::Result::ErrorKind::io) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
std::format("ShortUrlRemote: shorten outcome unknown: {}",
resp.error().message()))};
}
if (resp.error().kind() == Void::Result::ErrorKind::exhausted) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ResponseTooLarge,
std::format("ShortUrlRemote: response too large: {}",
resp.error().message()))};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
std::format("ShortUrlRemote: transport error: {}",
resp.error().message()))};
}
if (resp->body.size() > m_options.max_response_bytes) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ResponseTooLarge,
"ShortUrlRemote: response exceeds max_response_bytes")};
}
const std::uint32_t retry_after = parse_retry_after(*resp);
if (retry_after > 0) {
m_last_retry_after.store(retry_after, std::memory_order_release);
}
if (!resp->ok()) {
return std::unexpected{make_shorturl_error(
map_http_status_to_v2(resp->status),
std::format("ShortUrlRemote: shorten HTTP {}", resp->status))};
}
auto parsed = Void::Json::Strict::parse(resp->body);
if (!parsed.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: invalid JSON response")};
}
const auto* root =
std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
if (root == nullptr) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: expected JSON object")};
}
const auto* key = find_string(*root, "key");
const auto* short_url = find_string(*root, "short_url");
if (key == nullptr || key->empty() || short_url == nullptr ||
short_url->empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: response missing key or short_url")};
}
const auto* target = find_string(*root, "target_url");
return Link{
.key = *key,
.short_url = *short_url,
.target_url = target ? *target : request.target_url,
.expires_at_unix_seconds =
find_i64(*root, "expires_at_unix_seconds")
.value_or(request.expires_at_unix_seconds),
.retry_after_seconds = retry_after,
};
}
Void::Result::Result<Link> RemoteProvider::resolve(std::string_view key)
{
m_last_retry_after.store(0, std::memory_order_release);
if (!m_options.capabilities.supports_resolve) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support resolve")};
}
if (auto k = validate_custom_key(key); !k.has_value()) {
return std::unexpected{std::move(k.error())};
}
Void::Net::Request req;
req.method = Void::Net::Method::Get;
req.url = std::format("{}/v2/resolve/{}", m_options.base_url, key);
req.headers = m_options.headers;
req.timeout = m_options.timeout;
auto resp = m_client.send(req);
if (!resp.has_value()) {
if (resp.error().kind() == Void::Result::ErrorKind::timeout) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Timeout,
std::format("ShortUrlRemote: resolve timed out: {}",
resp.error().message()))};
}
if (resp.error().kind() == Void::Result::ErrorKind::exhausted) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ResponseTooLarge,
"ShortUrlRemote: resolve response too large")};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
std::format("ShortUrlRemote: resolve transport failed: {}",
resp.error().message()))};
}
const std::uint32_t retry_after = parse_retry_after(*resp);
if (retry_after > 0) {
m_last_retry_after.store(retry_after, std::memory_order_release);
}
if (!resp->ok()) {
return std::unexpected{make_shorturl_error(
map_http_status_to_v2(resp->status),
std::format("ShortUrlRemote: resolve HTTP {}", resp->status))};
}
auto parsed = Void::Json::Strict::parse(resp->body);
if (!parsed.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: invalid JSON resolve response")};
}
const auto* root =
std::get_if<Void::Json::Strict::Value::Object>(&parsed->value);
if (root == nullptr) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: expected JSON object")};
}
const auto* target = find_string(*root, "target_url");
if (target == nullptr || target->empty()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::ProviderError,
"ShortUrlRemote: missing target_url in resolve response")};
}
const auto* short_url = find_string(*root, "short_url");
return Link{
.key = std::string{key},
.short_url = short_url ? *short_url : std::string{},
.target_url = *target,
.expires_at_unix_seconds =
find_i64(*root, "expires_at_unix_seconds").value_or(0),
.retry_after_seconds = retry_after,
};
}
Void::Result::Result<void> RemoteProvider::revoke(std::string_view key)
{
m_last_retry_after.store(0, std::memory_order_release);
if (!m_options.capabilities.supports_revoke) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unsupported,
"ShortUrlRemote: provider does not support revoke")};
}
if (auto k = validate_custom_key(key); !k.has_value()) {
return std::unexpected{std::move(k.error())};
}
Void::Net::Request req;
req.method = Void::Net::Method::Delete;
req.url = std::format("{}/v2/links/{}", m_options.base_url, key);
req.headers = m_options.headers;
req.timeout = m_options.timeout;
auto resp = m_client.send(req);
if (!resp.has_value()) {
if (resp.error().kind() == Void::Result::ErrorKind::timeout ||
resp.error().kind() == Void::Result::ErrorKind::io) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
std::format("ShortUrlRemote: revoke outcome unknown: {}",
resp.error().message()))};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::Unavailable,
std::format("ShortUrlRemote: revoke failed: {}",
resp.error().message()))};
}
const std::uint32_t retry_after = parse_retry_after(*resp);
if (retry_after > 0) {
m_last_retry_after.store(retry_after, std::memory_order_release);
}
if (!resp->ok()) {
return std::unexpected{make_shorturl_error(
map_http_status_to_v2(resp->status),
std::format("ShortUrlRemote: revoke HTTP {}", resp->status))};
}
return {};
}
} // namespace Void::ShortUrl::V2
+3
View File
@@ -0,0 +1,3 @@
void_add_module(ShortUrlRemote
INTERNAL_DEPS ShortUrl Net Data
)
+470
View File
@@ -0,0 +1,470 @@
#include <Void/ShortUrlStorage/StorageRepository.hpp>
#include <Void/Security/Security.hpp>
#include <charconv>
#include <cstring>
#include <format>
#include <string>
#include <string_view>
#include <vector>
namespace Void::ShortUrl::V2
{
namespace
{
constexpr std::string_view kLinkPrefix = "shorturl:v1:link:";
constexpr std::string_view kIdemPrefix = "shorturl:v1:idem:";
constexpr std::string_view kMetaCountsKey = "shorturl:v1:meta:counts";
void append_u32(std::string& out, std::uint32_t v)
{
out.push_back(static_cast<char>((v >> 24U) & 0xFFU));
out.push_back(static_cast<char>((v >> 16U) & 0xFFU));
out.push_back(static_cast<char>((v >> 8U) & 0xFFU));
out.push_back(static_cast<char>(v & 0xFFU));
}
void append_u64(std::string& out, std::uint64_t v)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<char>((v >> shift) & 0xFFU));
}
}
void append_str(std::string& out, std::string_view s)
{
append_u32(out, static_cast<std::uint32_t>(s.size()));
out.append(s);
}
[[nodiscard]] bool read_u32(std::string_view& in,
std::uint32_t& out) noexcept
{
if (in.size() < 4U) return false;
out = (static_cast<std::uint32_t>(static_cast<unsigned char>(in[0]))
<< 24U) |
(static_cast<std::uint32_t>(static_cast<unsigned char>(in[1]))
<< 16U) |
(static_cast<std::uint32_t>(static_cast<unsigned char>(in[2]))
<< 8U) |
static_cast<std::uint32_t>(static_cast<unsigned char>(in[3]));
in.remove_prefix(4U);
return true;
}
[[nodiscard]] bool read_u64(std::string_view& in,
std::uint64_t& out) noexcept
{
if (in.size() < 8U) return false;
std::uint64_t v = 0;
for (std::size_t i = 0; i < 8U; ++i) {
v = (v << 8U) |
static_cast<std::uint64_t>(
static_cast<unsigned char>(in[i]));
}
in.remove_prefix(8U);
out = v;
return true;
}
[[nodiscard]] bool read_str(std::string_view& in, std::string& out)
{
std::uint32_t len = 0;
if (!read_u32(in, len) || len > in.size()) {
return false;
}
out.assign(in.data(), len);
in.remove_prefix(len);
return true;
}
[[nodiscard]] std::string encode_link(const LinkRecord& r)
{
std::string out;
append_u32(out, r.schema_version);
out.push_back(static_cast<char>(static_cast<std::uint8_t>(r.state)));
append_u64(out, static_cast<std::uint64_t>(r.created_at_unix_seconds));
append_u64(out, static_cast<std::uint64_t>(r.expires_at_unix_seconds));
append_str(out, r.key);
append_str(out, r.target_url);
append_str(out, r.operation_id);
return out;
}
[[nodiscard]] std::optional<LinkRecord>
decode_link(std::string_view raw)
{
std::uint32_t ver = 0;
if (!read_u32(raw, ver) || ver != kRecordSchemaVersion) {
return std::nullopt;
}
if (raw.empty()) return std::nullopt;
const auto st = static_cast<std::uint8_t>(raw.front());
raw.remove_prefix(1U);
if (st != static_cast<std::uint8_t>(LinkState::Active) &&
st != static_cast<std::uint8_t>(LinkState::Revoked)) {
return std::nullopt;
}
std::uint64_t created = 0;
std::uint64_t expires = 0;
if (!read_u64(raw, created) || !read_u64(raw, expires)) {
return std::nullopt;
}
LinkRecord rec;
rec.schema_version = ver;
rec.state = static_cast<LinkState>(st);
rec.created_at_unix_seconds = static_cast<std::int64_t>(created);
rec.expires_at_unix_seconds = static_cast<std::int64_t>(expires);
if (!read_str(raw, rec.key) || !read_str(raw, rec.target_url) ||
!read_str(raw, rec.operation_id) || !raw.empty()) {
return std::nullopt;
}
return rec;
}
[[nodiscard]] std::string encode_idem(const IdempotencyRecord& r)
{
std::string out;
append_u32(out, kRecordSchemaVersion);
append_u64(out, static_cast<std::uint64_t>(r.created_at_unix_seconds));
append_u64(out,
static_cast<std::uint64_t>(r.retain_until_unix_seconds));
append_str(out, r.operation_id);
append_str(out, r.key);
append_str(out, r.target_url);
return out;
}
[[nodiscard]] std::optional<IdempotencyRecord>
decode_idem(std::string_view raw)
{
std::uint32_t ver = 0;
std::uint64_t created = 0;
std::uint64_t retain = 0;
if (!read_u32(raw, ver) || ver != kRecordSchemaVersion ||
!read_u64(raw, created) || !read_u64(raw, retain)) {
return std::nullopt;
}
IdempotencyRecord rec;
rec.created_at_unix_seconds = static_cast<std::int64_t>(created);
rec.retain_until_unix_seconds = static_cast<std::int64_t>(retain);
if (!read_str(raw, rec.operation_id) || !read_str(raw, rec.key) ||
!read_str(raw, rec.target_url) || !raw.empty()) {
return std::nullopt;
}
return rec;
}
struct MetaCounts {
std::uint64_t entries{0};
std::uint64_t retained_identities{0};
std::uint64_t approx_bytes{0};
};
[[nodiscard]] std::string encode_counts(const MetaCounts& c)
{
std::string out;
append_u32(out, kRecordSchemaVersion);
append_u64(out, c.entries);
append_u64(out, c.retained_identities);
append_u64(out, c.approx_bytes);
return out;
}
[[nodiscard]] std::optional<MetaCounts>
decode_counts(std::string_view raw)
{
std::uint32_t ver = 0;
MetaCounts c;
if (!read_u32(raw, ver) || ver != kRecordSchemaVersion ||
!read_u64(raw, c.entries) ||
!read_u64(raw, c.retained_identities) ||
!read_u64(raw, c.approx_bytes) || !raw.empty()) {
return std::nullopt;
}
return c;
}
} // namespace
Void::Result::Result<void>
SecurityRandomBytesPort::fill(std::span<std::byte> out)
{
std::size_t off = 0;
while (off < out.size()) {
auto key = Void::Security::random_secret_key();
if (!key.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::Internal,
std::format("ShortUrlStorage: CSPRNG failed: {}",
key.error().message()))};
}
const std::size_t take = std::min(key->size(), out.size() - off);
std::memcpy(out.data() + off, key->data(), take);
Void::Security::wipe_bytes(*key);
off += take;
}
return {};
}
StorageLinkRepository::StorageLinkRepository(
std::shared_ptr<Void::Storage::Engine> engine,
std::uint64_t disk_quota_bytes)
: m_engine(std::move(engine)), m_disk_quota_bytes(disk_quota_bytes)
{
}
Void::Result::Result<InsertOutcome>
StorageLinkRepository::insert_conditional(
const LinkRecord& record,
const std::optional<IdempotencyRecord>& idem,
std::int64_t now_unix_seconds, std::size_t max_entries,
std::size_t max_retained_identities)
{
if (!m_engine) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: null storage engine")};
}
std::lock_guard lock{m_write_mutex};
auto snap = m_engine->snapshot();
if (!snap.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: snapshot failed: {}",
snap.error().message()))};
}
// 1. Check existing idempotency record first.
std::string idem_storage_key;
if (idem.has_value() && !idem->operation_id.empty()) {
idem_storage_key = std::string{kIdemPrefix} + idem->operation_id;
auto existing_idem = m_engine->get(*snap, idem_storage_key);
if (existing_idem.has_value()) {
auto decoded = decode_idem(existing_idem->as_string_view());
if (!decoded.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt idempotency record")};
}
if (decoded->retain_until_unix_seconds <= now_unix_seconds) {
return InsertOutcome{InsertStatus::IdentityExpired, {}};
}
const std::string link_k =
std::string{kLinkPrefix} + decoded->key;
auto existing_link = m_engine->get(*snap, link_k);
if (!existing_link.has_value()) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
auto link_dec = decode_link(existing_link->as_string_view());
if (!link_dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt link record")};
}
return InsertOutcome{InsertStatus::IdempotentReplay, *link_dec};
}
if (existing_idem.error().kind() !=
Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get idempotency failed: {}",
existing_idem.error().message()))};
}
}
// 2. Check existing link key.
const std::string link_storage_key =
std::string{kLinkPrefix} + record.key;
auto existing_link = m_engine->get(*snap, link_storage_key);
if (existing_link.has_value()) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
if (existing_link.error().kind() !=
Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get link failed: {}",
existing_link.error().message()))};
}
// 3. Load and verify counts + disk quota.
MetaCounts counts{};
std::optional<Void::Storage::Sequence> counts_version;
auto counts_res = m_engine->get(*snap, kMetaCountsKey);
if (counts_res.has_value()) {
auto dec = decode_counts(counts_res->as_string_view());
if (!dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt metadata counts record")};
}
counts = *dec;
counts_version = counts_res->version;
} else if (counts_res.error().kind() !=
Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get counts failed: {}",
counts_res.error().message()))};
}
const std::string encoded_link = encode_link(record);
std::string encoded_idem;
if (!idem_storage_key.empty()) {
if (counts.retained_identities >= max_retained_identities) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
encoded_idem = encode_idem(*idem);
}
if (counts.entries >= max_entries) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
const std::uint64_t added_bytes =
link_storage_key.size() + encoded_link.size() +
idem_storage_key.size() + encoded_idem.size();
if (m_disk_quota_bytes > 0 &&
(added_bytes > m_disk_quota_bytes ||
counts.approx_bytes > m_disk_quota_bytes - added_bytes)) {
return InsertOutcome{InsertStatus::QuotaExceeded, {}};
}
counts.entries += 1U;
if (!idem_storage_key.empty()) {
counts.retained_identities += 1U;
}
counts.approx_bytes += added_bytes;
// 4. Atomic conditional WriteBatch.
Void::Storage::Batch batch;
batch.require_absent(link_storage_key);
batch.put(link_storage_key, encoded_link);
if (!idem_storage_key.empty()) {
batch.require_absent(idem_storage_key);
batch.put(idem_storage_key, encoded_idem);
}
if (counts_version.has_value()) {
batch.require_version(kMetaCountsKey, *counts_version);
} else {
batch.require_absent(kMetaCountsKey);
}
batch.put(kMetaCountsKey, encode_counts(counts));
auto wr = m_engine->write(std::move(batch), Void::Storage::Durability::Sync);
if (!wr.has_value()) {
if (wr.error().outcome == Void::Storage::Outcome::Unknown) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
std::format("ShortUrlStorage: commit outcome unknown: {}",
wr.error().cause.error.message()))};
}
if (wr.error().cause.code ==
Void::Storage::StorageErrorCode::conflict) {
return InsertOutcome{InsertStatus::Conflict, {}};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: conditional write failed: {}",
wr.error().cause.error.message()))};
}
return InsertOutcome{InsertStatus::Inserted, record};
}
Void::Result::Result<std::optional<LinkRecord>>
StorageLinkRepository::get(std::string_view key) const
{
if (!m_engine) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: null storage engine")};
}
auto snap = m_engine->snapshot();
if (!snap.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: snapshot failed: {}",
snap.error().message()))};
}
const std::string storage_key =
std::string{kLinkPrefix} + std::string{key};
auto res = m_engine->get(*snap, storage_key);
if (!res.has_value()) {
if (res.error().kind() == Void::Result::ErrorKind::not_found) {
return std::optional<LinkRecord>{};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get failed: {}",
res.error().message()))};
}
auto dec = decode_link(res->as_string_view());
if (!dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt link record")};
}
return std::optional<LinkRecord>{std::move(*dec)};
}
Void::Result::Result<void>
StorageLinkRepository::revoke(std::string_view key, std::int64_t)
{
if (!m_engine) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: null storage engine")};
}
std::lock_guard lock{m_write_mutex};
auto snap = m_engine->snapshot();
if (!snap.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: snapshot failed: {}",
snap.error().message()))};
}
const std::string storage_key =
std::string{kLinkPrefix} + std::string{key};
auto res = m_engine->get(*snap, storage_key);
if (!res.has_value()) {
if (res.error().kind() == Void::Result::ErrorKind::not_found) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::NotFound,
"ShortUrlStorage: key not found for revoke")};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: get failed: {}",
res.error().message()))};
}
auto dec = decode_link(res->as_string_view());
if (!dec.has_value()) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
"ShortUrlStorage: corrupt link record")};
}
if (dec->state == LinkState::Revoked) {
return {};
}
dec->state = LinkState::Revoked;
Void::Storage::Batch batch;
batch.require_version(storage_key, res->version);
batch.put(storage_key, encode_link(*dec));
auto wr =
m_engine->write(std::move(batch), Void::Storage::Durability::Sync);
if (!wr.has_value()) {
if (wr.error().outcome == Void::Storage::Outcome::Unknown) {
return std::unexpected{make_shorturl_error(
V2ErrorCode::UnknownOutcome,
"ShortUrlStorage: revoke outcome unknown")};
}
return std::unexpected{make_shorturl_error(
V2ErrorCode::StorageError,
std::format("ShortUrlStorage: revoke write failed: {}",
wr.error().cause.error.message()))};
}
return {};
}
} // namespace Void::ShortUrl::V2
+3
View File
@@ -0,0 +1,3 @@
void_add_module(ShortUrlStorage
INTERNAL_DEPS ShortUrl Storage Security
)
+833
View File
@@ -0,0 +1,833 @@
#include <Void/System/DirectoryWatcher.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <deque>
#include <filesystem>
#include <format>
#include <map>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#if defined(__linux__)
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <unistd.h>
#endif
namespace Void::FileSystem
{
#if defined(__linux__)
namespace
{
constexpr std::uint32_t kWatchMask =
IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_FROM |
IN_MOVED_TO | IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_EXCL_UNLINK |
IN_ONLYDIR;
[[nodiscard]] bool is_subpath_or_equal(const std::filesystem::path& candidate,
const std::filesystem::path& prefix)
{
const std::string c = candidate.lexically_normal().generic_string();
const std::string p = prefix.lexically_normal().generic_string();
if (c == p) {
return true;
}
if (p.empty()) {
return false;
}
const std::size_t plen = p.size();
return c.size() > plen && c.compare(0, plen, p) == 0 && c[plen] == '/';
}
[[nodiscard]] std::filesystem::path
rebase_path(const std::filesystem::path& p,
const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
const std::string ps = p.lexically_normal().generic_string();
const std::string os = old_prefix.lexically_normal().generic_string();
if (ps == os) {
return new_prefix;
}
if (ps.size() > os.size() && ps.compare(0, os.size(), os) == 0 &&
ps[os.size()] == '/') {
return new_prefix / std::filesystem::path{ps.substr(os.size() + 1U)};
}
return p;
}
} // namespace
struct DirectoryWatcher::Impl {
struct PendingMove {
std::filesystem::path path{};
bool is_directory{false};
std::chrono::steady_clock::time_point expires_at{};
};
Void::System::OwnedFd inotify_fd{};
Void::System::OwnedFd wake_fd{};
std::filesystem::path root{};
DirectoryWatcherOptions options{};
mutable std::mutex mutex{};
std::unordered_map<int, std::filesystem::path> wd_to_path{};
std::map<std::filesystem::path, int> path_to_wd{};
std::unordered_map<std::uint32_t, PendingMove> pending_moves{};
std::deque<DirectoryEvent> queue{};
bool rescan_emitted{false};
~Impl() noexcept
{
std::lock_guard lock{mutex};
for (const auto& [wd, _] : wd_to_path) {
if (inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
wd_to_path.clear();
path_to_wd.clear();
}
[[nodiscard]] bool should_ignore(const std::filesystem::path& p,
bool is_dir) const
{
if (options.ignore) {
return options.ignore(p, is_dir);
}
return false;
}
void push_event_locked(DirectoryEvent ev)
{
if (ev.kind == DirectoryEventKind::RescanRequired) {
if (rescan_emitted) {
return;
}
rescan_emitted = true;
queue.push_back(std::move(ev));
return;
}
if (queue.size() >= options.max_queued_events) {
if (!rescan_emitted) {
rescan_emitted = true;
queue.push_back(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher event queue full",
});
}
return;
}
queue.push_back(std::move(ev));
}
void remove_watch_by_wd_locked(int wd, bool call_rm)
{
auto it = wd_to_path.find(wd);
if (it == wd_to_path.end()) {
return;
}
path_to_wd.erase(it->second);
wd_to_path.erase(it);
if (call_rm && inotify_fd.valid()) {
(void)::inotify_rm_watch(inotify_fd.get(), wd);
}
}
void remove_subtree_watches_locked(const std::filesystem::path& prefix)
{
std::vector<int> wds;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, prefix)) {
wds.push_back(wd);
}
}
for (int wd : wds) {
remove_watch_by_wd_locked(wd, true);
}
}
void rewrite_subtree_watches_locked(const std::filesystem::path& old_prefix,
const std::filesystem::path& new_prefix)
{
std::vector<std::pair<int, std::filesystem::path>> updates;
for (const auto& [wd, p] : wd_to_path) {
if (is_subpath_or_equal(p, old_prefix)) {
updates.emplace_back(wd, rebase_path(p, old_prefix, new_prefix));
}
}
for (const auto& [wd, new_p] : updates) {
auto old_it = wd_to_path.find(wd);
if (old_it != wd_to_path.end()) {
path_to_wd.erase(old_it->second);
old_it->second = new_p;
path_to_wd[new_p] = wd;
}
}
}
void attach_single_dir_locked(const std::filesystem::path& dir_path)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
if (path_to_wd.contains(norm)) {
return;
}
if (wd_to_path.size() >= options.max_watches) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = "DirectoryWatcher max_watches exceeded",
});
return;
}
const int wd =
::inotify_add_watch(inotify_fd.get(), norm.c_str(), kWatchMask);
if (wd < 0) {
const int err = errno;
if (err == ENOSPC || err == ENOMEM) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = norm,
.old_path = {},
.is_directory = true,
.detail = std::format(
"inotify_add_watch exhausted watches (errno={})", err),
});
}
return;
}
// inotify_add_watch may return an existing wd if directory inode aliased.
if (auto existing = wd_to_path.find(wd); existing != wd_to_path.end()) {
if (existing->second != norm) {
path_to_wd.erase(existing->second);
existing->second = norm;
}
} else {
wd_to_path.emplace(wd, norm);
}
path_to_wd[norm] = wd;
}
void attach_subtree_locked(const std::filesystem::path& dir_path,
bool emit_existing_children)
{
const std::filesystem::path norm = dir_path.lexically_normal();
if (norm != root && should_ignore(norm, true)) {
return;
}
std::error_code ec;
const auto st = std::filesystem::symlink_status(norm, ec);
if (ec || std::filesystem::is_symlink(st) ||
!std::filesystem::is_directory(st)) {
return;
}
attach_single_dir_locked(norm);
std::vector<std::filesystem::path> stack{norm};
while (!stack.empty()) {
const std::filesystem::path cur = std::move(stack.back());
stack.pop_back();
ec.clear();
std::filesystem::directory_iterator it{
cur,
std::filesystem::directory_options::skip_permission_denied,
ec};
if (ec) {
continue;
}
for (const auto& entry : it) {
std::error_code st_ec;
const auto est = entry.symlink_status(st_ec);
if (st_ec || std::filesystem::is_symlink(est)) {
continue;
}
const bool is_dir = std::filesystem::is_directory(est);
const std::filesystem::path ep =
entry.path().lexically_normal();
if (should_ignore(ep, is_dir)) {
continue;
}
if (emit_existing_children) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = ep,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if (is_dir) {
attach_single_dir_locked(ep);
stack.push_back(ep);
}
}
}
}
void flush_expired_moves_locked(std::chrono::steady_clock::time_point now,
bool force_all)
{
for (auto it = pending_moves.begin(); it != pending_moves.end();) {
if (force_all || now >= it->second.expires_at) {
const auto p = it->second.path;
const bool is_dir = it->second.is_directory;
if (is_dir) {
remove_subtree_watches_locked(p);
}
if (!should_ignore(p, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = p,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
it = pending_moves.erase(it);
} else {
++it;
}
}
}
void process_inotify_event_locked(const struct inotify_event* ev)
{
if ((ev->mask & IN_Q_OVERFLOW) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "inotify kernel event queue overflow (IN_Q_OVERFLOW)",
});
return;
}
if ((ev->mask & IN_IGNORED) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
return;
}
const auto dir_it = wd_to_path.find(ev->wd);
if (dir_it == wd_to_path.end()) {
return;
}
const std::filesystem::path base = dir_it->second;
const bool is_dir = (ev->mask & IN_ISDIR) != 0U;
if ((ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF)) != 0U && ev->len == 0U) {
if (base == root) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = root,
.old_path = {},
.is_directory = true,
.detail = "watched root directory deleted or moved",
});
remove_watch_by_wd_locked(ev->wd, false);
} else if ((ev->mask & IN_DELETE_SELF) != 0U) {
remove_watch_by_wd_locked(ev->wd, false);
}
return;
}
const std::string name =
(ev->len > 0U && ev->name[0] != '\0') ? std::string{ev->name}
: std::string{};
const std::filesystem::path full_path =
name.empty() ? base : (base / name).lexically_normal();
if ((ev->mask & IN_MOVED_FROM) != 0U) {
if (ev->cookie != 0U) {
pending_moves.insert_or_assign(
ev->cookie,
PendingMove{
.path = full_path,
.is_directory = is_dir,
.expires_at = std::chrono::steady_clock::now() +
options.rename_pair_window,
});
} else {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
if (!should_ignore(full_path, is_dir)) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
return;
}
if ((ev->mask & IN_MOVED_TO) != 0U) {
if (ev->cookie != 0U) {
if (auto mit = pending_moves.find(ev->cookie);
mit != pending_moves.end()) {
const std::filesystem::path old_path =
std::move(mit->second.path);
pending_moves.erase(mit);
const bool old_ignored = should_ignore(old_path, is_dir);
const bool new_ignored = should_ignore(full_path, is_dir);
if (is_dir) {
if (new_ignored) {
remove_subtree_watches_locked(old_path);
} else {
rewrite_subtree_watches_locked(old_path, full_path);
attach_subtree_locked(full_path, false);
}
}
if (!old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Renamed,
.path = full_path,
.old_path = old_path,
.is_directory = is_dir,
.detail = {},
});
} else if (!old_ignored && new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = old_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
} else if (old_ignored && !new_ignored) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
return;
}
}
if (should_ignore(full_path, is_dir)) {
return;
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
return;
}
if (should_ignore(full_path, is_dir)) {
return;
}
if ((ev->mask & IN_CREATE) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Created,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
if (is_dir) {
attach_subtree_locked(full_path, true);
}
}
if ((ev->mask & IN_DELETE) != 0U) {
if (is_dir) {
remove_subtree_watches_locked(full_path);
}
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Deleted,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & (IN_MODIFY | IN_CLOSE_WRITE)) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::Modified,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
if ((ev->mask & IN_ATTRIB) != 0U) {
push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::AttributeChanged,
.path = full_path,
.old_path = {},
.is_directory = is_dir,
.detail = {},
});
}
}
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
drain_inotify_locked()
{
alignas(struct inotify_event) std::array<char, 16384> buf{};
for (;;) {
const ssize_t n =
::read(inotify_fd.get(), buf.data(), buf.size());
if (n > 0) {
ssize_t offset = 0;
while (offset < n) {
const auto* ev =
reinterpret_cast<const struct inotify_event*>(
buf.data() + offset);
process_inotify_event_locked(ev);
offset += static_cast<ssize_t>(
sizeof(struct inotify_event) + ev->len);
}
continue;
}
if (n == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher: read(inotify) failed",
err)};
}
return {};
}
void drain_wake_locked() noexcept
{
std::uint64_t val = 0;
while (::read(wake_fd.get(), &val, sizeof(val)) > 0 ||
(errno == EINTR)) {
}
}
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path& root,
DirectoryWatcherOptions options)
{
if (root.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::create: root cannot be empty")};
}
std::error_code ec;
const auto st = std::filesystem::status(root, ec);
if (ec || !std::filesystem::is_directory(st)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::not_found,
std::format(
"FileSystem::DirectoryWatcher::create: '{}' is not a directory",
root.string()))};
}
const int ifd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (ifd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: inotify_init1 failed",
err)};
}
Void::System::OwnedFd owned_ifd{ifd};
const int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (efd < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::create: eventfd failed",
err)};
}
Void::System::OwnedFd owned_efd{efd};
auto impl = std::make_unique<Impl>();
impl->inotify_fd = std::move(owned_ifd);
impl->wake_fd = std::move(owned_efd);
impl->root = std::filesystem::weakly_canonical(root, ec);
if (ec || impl->root.empty()) {
impl->root = root.lexically_normal();
}
impl->options = std::move(options);
{
std::lock_guard lock{impl->mutex};
impl->attach_subtree_locked(impl->root, false);
}
return DirectoryWatcher{std::move(impl)};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds timeout)
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::poll: moved-from watcher")};
}
const auto start = std::chrono::steady_clock::now();
const auto end_time = start + std::max(std::chrono::milliseconds{0}, timeout);
int ifd = -1;
int efd = -1;
{
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
timeout.count() <= 0);
if (!impl_->queue.empty() && impl_->pending_moves.empty()) {
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
ifd = impl_->inotify_fd.get();
efd = impl_->wake_fd.get();
}
if (timeout.count() > 0) {
for (;;) {
const auto now = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point wait_until = end_time;
{
std::lock_guard lock{impl_->mutex};
for (const auto& [_, pm] : impl_->pending_moves) {
wait_until = std::min(wait_until, pm.expires_at);
}
}
if (now >= wait_until) {
std::lock_guard lock{impl_->mutex};
impl_->flush_expired_moves_locked(now, false);
if (now >= end_time ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
continue;
}
const auto rem_ms = std::max<long long>(
1,
std::chrono::duration_cast<std::chrono::milliseconds>(
wait_until - now)
.count());
std::array<struct pollfd, 2> pfds{{
{ifd, POLLIN, 0},
{efd, POLLIN, 0},
}};
const int rc =
::poll(pfds.data(), pfds.size(), static_cast<int>(rem_ms));
if (rc < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"FileSystem::DirectoryWatcher::poll: poll failed",
err)};
}
std::lock_guard lock{impl_->mutex};
if (auto dr = impl_->drain_inotify_locked(); !dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
const bool woken = (pfds[1].revents & POLLIN) != 0;
if (woken) {
impl_->drain_wake_locked();
}
impl_->flush_expired_moves_locked(std::chrono::steady_clock::now(),
false);
if (woken ||
(!impl_->queue.empty() && impl_->pending_moves.empty())) {
break;
}
}
}
std::lock_guard lock{impl_->mutex};
std::vector<DirectoryEvent> out;
out.reserve(impl_->queue.size());
while (!impl_->queue.empty()) {
out.push_back(std::move(impl_->queue.front()));
impl_->queue.pop_front();
}
return out;
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
if (!impl_) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::DirectoryWatcher::rescan: moved-from watcher")};
}
std::lock_guard lock{impl_->mutex};
for (const auto& [wd, _] : impl_->wd_to_path) {
(void)::inotify_rm_watch(impl_->inotify_fd.get(), wd);
}
impl_->wd_to_path.clear();
impl_->path_to_wd.clear();
impl_->pending_moves.clear();
impl_->queue.clear();
impl_->rescan_emitted = false;
impl_->attach_subtree_locked(impl_->root, false);
return {};
}
void DirectoryWatcher::wake() noexcept
{
if (!impl_ || !impl_->wake_fd.valid()) {
return;
}
const std::uint64_t one = 1;
while (::write(impl_->wake_fd.get(), &one, sizeof(one)) < 0 &&
errno == EINTR) {
}
}
void DirectoryWatcher::simulate_overflow_for_test()
{
if (!impl_) {
return;
}
{
std::lock_guard lock{impl_->mutex};
impl_->push_event_locked(DirectoryEvent{
.kind = DirectoryEventKind::RescanRequired,
.path = impl_->root,
.old_path = {},
.is_directory = true,
.detail = "simulated IN_Q_OVERFLOW",
});
}
wake();
}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept
{
if (!impl_) {
return 0;
}
std::lock_guard lock{impl_->mutex};
return impl_->wd_to_path.size();
}
int DirectoryWatcher::native_handle() const noexcept
{
return impl_ ? impl_->inotify_fd.get() : -1;
}
#else
struct DirectoryWatcher::Impl {
std::filesystem::path root{};
};
DirectoryWatcher::DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept
: impl_(std::move(impl))
{
}
DirectoryWatcher::~DirectoryWatcher() noexcept = default;
DirectoryWatcher::DirectoryWatcher(DirectoryWatcher&&) noexcept = default;
DirectoryWatcher&
DirectoryWatcher::operator=(DirectoryWatcher&&) noexcept = default;
Void::Result::Result<DirectoryWatcher, Void::Result::Error>
DirectoryWatcher::create(const std::filesystem::path&,
DirectoryWatcherOptions)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: inotify watcher is Linux-only")};
}
Void::Result::Result<std::vector<DirectoryEvent>, Void::Result::Error>
DirectoryWatcher::poll(std::chrono::milliseconds)
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
Void::Result::Result<void, Void::Result::Error> DirectoryWatcher::rescan()
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::DirectoryWatcher: unsupported platform")};
}
void DirectoryWatcher::wake() noexcept {}
void DirectoryWatcher::simulate_overflow_for_test() {}
const std::filesystem::path& DirectoryWatcher::root() const noexcept
{
static const std::filesystem::path kEmpty{};
return impl_ ? impl_->root : kEmpty;
}
std::size_t DirectoryWatcher::watch_count() const noexcept { return 0; }
int DirectoryWatcher::native_handle() const noexcept { return -1; }
#endif
} // namespace Void::FileSystem
+192 -54
View File
@@ -40,6 +40,7 @@ Child::Child(Child&&) noexcept = default;
Child& Child::operator=(Child&&) noexcept = default;
bool Child::valid() const noexcept { return false; }
bool Child::running() const noexcept { return false; }
bool Child::process_group_alive() const noexcept { return false; }
long long Child::pid() const noexcept { return -1; }
long long Child::pgid() const noexcept { return -1; }
bool Child::owns_process_group() const noexcept { return false; }
@@ -142,6 +143,13 @@ Void::Result::Result<void, Void::Result::Error> reexec(
return Void::Result::fail("Process::reexec: not implemented on Windows");
}
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: not supported on Windows")};
}
} // namespace Void::Process
#else // POSIX
@@ -150,6 +158,9 @@ Void::Result::Result<void, Void::Result::Error> reexec(
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#if defined(__linux__) && __has_include(<sys/prctl.h>)
#include <sys/prctl.h>
#endif
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
@@ -468,26 +479,102 @@ void write_child_failure(int err_fd, int phase, int err) noexcept
return st;
}
[[nodiscard]] bool is_process_group_alive(pid_t pgid) noexcept
{
if (pgid <= 0) {
return false;
}
for (;;) {
if (::kill(-pgid, 0) == 0) {
return true;
}
if (errno == EINTR) {
continue;
}
return errno == EPERM;
}
}
void reap_group_nonblocking(pid_t pid,
pid_t pgid,
bool owns_group,
bool& reaped,
ExitStatus& cached,
int& out_errno) noexcept
{
out_errno = 0;
if (!reaped && pid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(pid, &raw, WNOHANG);
if (w == pid) {
cached = decode_wait_status(raw);
reaped = true;
break;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped = true;
break;
}
out_errno = errno;
break;
}
}
if (owns_group && pgid > 0) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(-pgid, &raw, WNOHANG);
if (w > 0) {
if (w == pid && !reaped) {
cached = decode_wait_status(raw);
reaped = true;
}
continue;
}
if (w == 0) {
break;
}
if (errno == EINTR) {
continue;
}
break;
}
}
}
[[nodiscard]] bool signal_target(pid_t pid,
pid_t pgid,
bool owns_group,
bool leader_reaped,
int sig,
int& out_errno) noexcept
{
bool delivered = false;
out_errno = 0;
if (owns_group && pgid > 0) {
if (::kill(-pgid, sig) == 0) {
return true;
}
out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) {
return false;
delivered = true;
} else {
out_errno = errno;
if (out_errno != ESRCH && out_errno != EPERM) {
return false;
}
}
}
if (::kill(pid, sig) == 0) {
return true;
if (!leader_reaped && pid > 0) {
if (::kill(pid, sig) == 0) {
delivered = true;
} else {
out_errno = errno;
}
}
out_errno = errno;
return false;
return delivered;
}
[[nodiscard]] std::optional<std::string>
@@ -706,6 +793,13 @@ Child& Child::operator=(Child&& other) noexcept
bool Child::valid() const noexcept { return pid_ > 0; }
bool Child::running() const noexcept { return pid_ > 0 && !reaped_; }
bool Child::process_group_alive() const noexcept
{
if (owns_group_ && pgid_ > 0) {
return is_process_group_alive(static_cast<pid_t>(pgid_));
}
return running();
}
long long Child::pid() const noexcept { return pid_; }
long long Child::pgid() const noexcept { return pgid_; }
bool Child::owns_process_group() const noexcept { return owns_group_; }
@@ -738,7 +832,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
Void::System::SystemErrorCode::invalid_argument,
"Process::Child::send_signal: invalid child")};
}
if (reaped_) {
if (reaped_ && (!owns_group_ || !process_group_alive())) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::busy,
"Process::Child::send_signal: child already reaped")};
@@ -747,6 +841,7 @@ Void::Result::Result<void, Void::Result::Error> Child::send_signal(int sig) noex
if (!signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
reaped_,
sig,
err)) {
return std::unexpected{Void::System::make_system_error(
@@ -798,35 +893,37 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
Void::System::SystemErrorCode::invalid_argument,
"Process::Child::terminate: invalid child")};
}
if (reaped_) {
const pid_t target_pid = static_cast<pid_t>(pid_);
const pid_t target_pgid = static_cast<pid_t>(pgid_);
const bool group_owned = owns_group_ && target_pgid > 0;
auto group_finished = [&]() noexcept -> bool {
int reap_err = 0;
reap_group_nonblocking(
target_pid, target_pgid, group_owned, reaped_, cached_status_, reap_err);
if (!reaped_) {
return false;
}
return !group_owned || !is_process_group_alive(target_pgid);
};
if (group_finished()) {
return cached_status_;
}
const auto effective_grace =
(grace.count() >= 0) ? grace : kill_grace_;
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
}
int sig_err = 0;
(void)signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
SIGTERM,
sig_err);
(void)signal_target(
target_pid, target_pgid, group_owned, reaped_, SIGTERM, sig_err);
const auto grace_deadline =
std::chrono::steady_clock::now() + effective_grace;
while (std::chrono::steady_clock::now() < grace_deadline) {
auto polled = try_wait();
if (!polled.has_value()) {
return std::unexpected{polled.error()};
}
if (polled->has_value()) {
return **polled;
if (group_finished()) {
return cached_status_;
}
const auto rem = std::chrono::duration_cast<std::chrono::milliseconds>(
grace_deadline - std::chrono::steady_clock::now());
@@ -834,38 +931,61 @@ Void::Result::Result<ExitStatus, Void::Result::Error>
break;
}
std::this_thread::sleep_for(
std::min(rem, std::chrono::milliseconds{10}));
std::min(rem, std::chrono::milliseconds{5}));
}
if (auto polled = try_wait(); !polled.has_value()) {
return std::unexpected{polled.error()};
} else if (polled->has_value()) {
return **polled;
if (group_finished()) {
return cached_status_;
}
(void)signal_target(static_cast<pid_t>(pid_),
static_cast<pid_t>(pgid_),
owns_group_,
SIGKILL,
sig_err);
(void)signal_target(
target_pid, target_pgid, group_owned, reaped_, SIGKILL, sig_err);
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(static_cast<pid_t>(pid_), &raw, 0);
if (w == static_cast<pid_t>(pid_)) {
cached_status_ = decode_wait_status(raw);
reaped_ = true;
return cached_status_;
if (!reaped_) {
int raw = 0;
for (;;) {
const pid_t w = ::waitpid(target_pid, &raw, 0);
if (w == target_pid) {
cached_status_ = decode_wait_status(raw);
reaped_ = true;
break;
}
if (errno == EINTR) {
continue;
}
if (errno == ECHILD) {
reaped_ = true;
break;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
}
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::Child::terminate: final waitpid failed",
err)};
}
if (group_owned) {
const auto kill_ceiling =
std::chrono::steady_clock::now() + std::chrono::seconds{5};
while (!group_finished()) {
if (std::chrono::steady_clock::now() >= kill_ceiling) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::timed_out,
"Process::Child::terminate: process group members failed "
"to exit after SIGKILL")};
}
(void)signal_target(target_pid,
target_pgid,
group_owned,
reaped_,
SIGKILL,
sig_err);
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
return cached_status_;
}
Void::Result::Result<ExitStatus, Void::Result::Error> Child::wait_blocking(
@@ -950,7 +1070,7 @@ void Child::reset_and_reap() noexcept
stdin_.reset();
stdout_.reset();
stderr_.reset();
if (pid_ > 0 && !reaped_) {
if (pid_ > 0 && (!reaped_ || process_group_alive())) {
(void)terminate(kill_grace_);
}
pid_ = -1;
@@ -1643,6 +1763,24 @@ Void::Result::Result<void, Void::Result::Error>
err)};
}
Void::Result::Result<void, Void::Result::Error> enable_subreaper() noexcept
{
#if defined(__linux__) && defined(PR_SET_CHILD_SUBREAPER)
if (::prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
"Process::enable_subreaper: prctl(PR_SET_CHILD_SUBREAPER) failed",
err)};
}
return {};
#else
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"Process::enable_subreaper: PR_SET_CHILD_SUBREAPER unavailable on this platform")};
#endif
}
} // namespace Void::Process
#endif // _WIN32
+3
View File
@@ -133,6 +133,9 @@ if(_all_generated)
if(TARGET OpenSSL::Crypto)
target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto)
endif()
if(TARGET OpenSSL::SSL)
target_link_libraries(VoidTests PRIVATE OpenSSL::SSL)
endif()
if(TARGET SQLite3::SQLite3)
target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3)
endif()
+54
View File
@@ -194,6 +194,57 @@ int mode_ignore_sigterm(int argc, char** argv)
return 0;
}
int mode_grandchild_ignore_sigterm(int argc, char** argv)
{
if (argc < 3) {
return usage_error("grandchild-ignore-sigterm requires <marker_file>");
}
const char* marker_path = argv[2];
int ready_p[2]{-1, -1};
if (::pipe(ready_p) != 0) {
return 1;
}
const pid_t gc = ::fork();
if (gc < 0) {
(void)::close(ready_p[0]);
(void)::close(ready_p[1]);
return 1;
}
if (gc == 0) {
(void)::close(ready_p[0]);
std::signal(SIGTERM, SIG_IGN);
const int mfd = ::open(marker_path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
if (mfd < 0) {
(void)::close(ready_p[1]);
::_exit(1);
}
static constexpr char kTick[] = "tick\n";
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
static constexpr char kReady[] = "ready\n";
(void)write_all_fd(STDOUT_FILENO, kReady, sizeof(kReady) - 1);
const char one = '1';
(void)write_all_fd(ready_p[1], &one, 1);
(void)::close(ready_p[1]);
(void)::close(STDIN_FILENO);
(void)::close(STDOUT_FILENO);
(void)::close(STDERR_FILENO);
for (int iter = 0; iter < 500; ++iter) {
std::this_thread::sleep_for(std::chrono::milliseconds{10});
(void)write_all_fd(mfd, kTick, sizeof(kTick) - 1);
}
(void)::close(mfd);
::_exit(0);
}
(void)::close(ready_p[1]);
char dummy = 0;
bool eof = false;
(void)read_exact_fd(ready_p[0], &dummy, 1, eof);
(void)::close(ready_p[0]);
::_exit(0);
}
int mode_simultaneous_io(int argc, char** argv)
{
if (argc != 3) {
@@ -485,6 +536,9 @@ int main(int argc, char** argv)
if (mode == "ignore-sigterm") {
return mode_ignore_sigterm(argc, argv);
}
if (mode == "grandchild-ignore-sigterm") {
return mode_grandchild_ignore_sigterm(argc, argv);
}
if (mode == "simultaneous-io") {
return mode_simultaneous_io(argc, argv);
}
+5 -1
View File
@@ -12,8 +12,12 @@ int main()
.content = {std::byte{'h'}, std::byte{'i'}},
},
}};
Void::Archive::CreationOptions opts;
opts.compression = Void::Archive::has_libarchive_backend()
? Void::Archive::ArchiveCompression::Zstd
: Void::Archive::ArchiveCompression::None;
Void::Archive::VectorByteSink sink;
if (!Void::Archive::create_archive(sink, entries).has_value()) {
if (!Void::Archive::create(sink, entries, opts).has_value()) {
return 1;
}
Void::Archive::SpanByteSource src{sink.bytes()};
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more