Merge branch 'feat/roadmap-p2-wave9' (P2 Net, TestingMock, ShortUrl, RPC)
This commit is contained in:
commit
65ad9b3f31
53 files changed
+10295
-60
No files matched your search
@@ -1,8 +1,8 @@
|
||||
# Workflow state
|
||||
|
||||
Updated: 2026-11-26.
|
||||
Repository: VoidLibrary; active branch `feat/upstream-vbs-requests` (from `main`
|
||||
at `53d42bd`, merged Waves 1–8 and pushed to `origin/main`).
|
||||
Updated: 2026-11-27.
|
||||
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave9` (from `main`
|
||||
at `3e25405`, merged Waves 1–8 + `VL-001`..`VL-013` and pushed to `origin/main`).
|
||||
|
||||
## Completed objective
|
||||
|
||||
@@ -339,11 +339,21 @@ while leaving local untracked files untouched.
|
||||
- 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.
|
||||
|
||||
## 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`,
|
||||
`Service`/`ServicePlugin`/`Plugin`/`Configuration`/`ConfigurationAsync`/`Fsm`)
|
||||
and the VoidBuildSystem upstream feature wave (`VL-001`..`VL-013`) are complete,
|
||||
verified, and merged to `main` via `--no-ff`.
|
||||
Waves 1–9 (`P0`, `P1`, all `P2` functional modules and `VL-001`..`VL-013`) are
|
||||
complete, verified, and merged to `main` via `--no-ff`. Next roadmap phase:
|
||||
**P3** (new single-node subsystems `Discovery`, `Scheduler`, `Messaging` +
|
||||
`NetworkedApplications` / `ReloadableApplications` platform integrations).
|
||||
@@ -119,6 +119,15 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
|
||||
| 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) |
|
||||
|
||||
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
|
||||
|
||||
@@ -291,3 +291,9 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
|
||||
| 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 |
|
||||
@@ -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,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`.
|
||||
@@ -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);
|
||||
|
||||
@@ -76,6 +76,10 @@ namespace Void::Result
|
||||
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;
|
||||
|
||||
struct ErrorCode {
|
||||
std::uint32_t domain{kGenericErrorDomain};
|
||||
|
||||
@@ -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
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/Server.hpp>
|
||||
#include <Void/Net/WebSocket.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
@@ -89,6 +90,14 @@ namespace Void::Net
|
||||
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 =
|
||||
|
||||
@@ -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
|
||||
@@ -98,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);
|
||||
|
||||
@@ -115,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_;
|
||||
@@ -122,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 {
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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
|
||||
@@ -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), ...);
|
||||
|
||||
@@ -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
|
||||
+54
-15
@@ -917,9 +917,15 @@ namespace Void::Net
|
||||
HttpClient::send(const Request& req) const
|
||||
{
|
||||
std::string target_url = req.url;
|
||||
Method active_method = req.method;
|
||||
std::optional<std::string> active_body = req.body;
|
||||
std::vector<Header> active_headers = req.headers;
|
||||
int redirects = 0;
|
||||
|
||||
const auto overall_start = std::chrono::steady_clock::now();
|
||||
const bool has_deadline = req.timeout > std::chrono::seconds::zero();
|
||||
const auto overall_deadline = overall_start + req.timeout;
|
||||
|
||||
while (true) {
|
||||
const auto url = Url::parse(target_url);
|
||||
if (!url) {
|
||||
@@ -928,11 +934,25 @@ namespace Void::Net
|
||||
std::format("Net: invalid URL '{}'",
|
||||
sanitize_url_for_log(target_url)))};
|
||||
}
|
||||
std::chrono::seconds remaining_timeout = req.timeout;
|
||||
if (has_deadline) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now >= overall_deadline) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::timeout,
|
||||
std::format("Net: request to '{}' timed out across "
|
||||
"redirects",
|
||||
sanitize_url_for_log(target_url)))};
|
||||
}
|
||||
const auto rem_ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
overall_deadline - now);
|
||||
remaining_timeout = std::chrono::seconds{
|
||||
std::max<long long>(1, (rem_ms.count() + 999) / 1000)};
|
||||
}
|
||||
bool cancelled = false;
|
||||
bool timed_out = false;
|
||||
try {
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
|
||||
asio::io_context ioc;
|
||||
ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file);
|
||||
|
||||
@@ -945,26 +965,26 @@ namespace Void::Net
|
||||
asio::connect(socket, resolver.resolve(
|
||||
m_proxy.host,
|
||||
std::to_string(m_proxy.port)));
|
||||
DeadlineGuard deadline{socket, req.timeout};
|
||||
DeadlineGuard deadline{socket, remaining_timeout};
|
||||
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
||||
socks5_connect(socket, *url, m_proxy);
|
||||
response = finish(socket, tls, ctx, *url, req.method,
|
||||
active_headers, req.body,
|
||||
response = finish(socket, tls, ctx, *url, active_method,
|
||||
active_headers, active_body,
|
||||
m_user_agent, m_max_body,
|
||||
m_verify_tls);
|
||||
} else {
|
||||
if (url->is_tls) {
|
||||
http_connect_tunnel(socket, *url, m_proxy);
|
||||
response = finish(socket, tls, ctx, *url,
|
||||
req.method, active_headers,
|
||||
req.body, m_user_agent,
|
||||
active_method, active_headers,
|
||||
active_body, m_user_agent,
|
||||
m_max_body, m_verify_tls);
|
||||
} else {
|
||||
const std::string absolute = std::format(
|
||||
"{}://{}{}", url->scheme, url->host,
|
||||
url->target);
|
||||
auto rq = build_request(*url, req.method,
|
||||
active_headers, req.body,
|
||||
auto rq = build_request(*url, active_method,
|
||||
active_headers, active_body,
|
||||
m_user_agent, absolute);
|
||||
if (m_proxy.has_auth()) {
|
||||
const auto enc = Void::Encoding::Base64::encode(
|
||||
@@ -981,17 +1001,21 @@ namespace Void::Net
|
||||
} else {
|
||||
asio::connect(socket,
|
||||
resolver.resolve(url->host, url->port));
|
||||
DeadlineGuard deadline{socket, req.timeout};
|
||||
DeadlineGuard deadline{socket, remaining_timeout};
|
||||
response =
|
||||
finish(socket, tls, ctx, *url, req.method,
|
||||
active_headers, req.body, m_user_agent,
|
||||
finish(socket, tls, ctx, *url, active_method,
|
||||
active_headers, active_body, m_user_agent,
|
||||
m_max_body, m_verify_tls);
|
||||
timed_out = deadline.timed_out();
|
||||
cancelled = deadline.cancelled();
|
||||
}
|
||||
|
||||
if (m_max_redirects > 0 && response.status >= 300 &&
|
||||
response.status < 400 && redirects < m_max_redirects) {
|
||||
const bool is_redirect_status =
|
||||
response.status == 301 || response.status == 302 ||
|
||||
response.status == 303 || response.status == 307 ||
|
||||
response.status == 308;
|
||||
if (m_max_redirects > 0 && is_redirect_status &&
|
||||
redirects < m_max_redirects) {
|
||||
if (auto loc = response.header("location")) {
|
||||
const std::string next_url =
|
||||
resolve_redirect(*url, *loc);
|
||||
@@ -1011,6 +1035,21 @@ namespace Void::Net
|
||||
if (!same_origin(*url, *next_parsed)) {
|
||||
strip_sensitive_headers(active_headers);
|
||||
}
|
||||
// RFC 9110 §15.4.4: 303 changes non-HEAD to GET and
|
||||
// drops body + representation headers.
|
||||
if (response.status == 303 &&
|
||||
active_method != Method::Head) {
|
||||
active_method = Method::Get;
|
||||
active_body.reset();
|
||||
std::erase_if(active_headers, [](const Header& h) {
|
||||
return equal_ascii_ci(h.name,
|
||||
"Content-Length") ||
|
||||
equal_ascii_ci(h.name,
|
||||
"Content-Type") ||
|
||||
equal_ascii_ci(h.name,
|
||||
"Transfer-Encoding");
|
||||
});
|
||||
}
|
||||
target_url = next_url;
|
||||
++redirects;
|
||||
continue;
|
||||
@@ -1019,7 +1058,7 @@ namespace Void::Net
|
||||
|
||||
response.elapsed =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - start);
|
||||
std::chrono::steady_clock::now() - overall_start);
|
||||
return response;
|
||||
} catch (const TlsError& e) {
|
||||
return std::unexpected{make_net_error(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -882,6 +882,138 @@ namespace Void::Net
|
||||
std::atomic<bool> finished{false};
|
||||
std::thread thread{};
|
||||
};
|
||||
|
||||
struct WebSocketRoute {
|
||||
std::string pattern;
|
||||
std::vector<std::string> segments;
|
||||
WebSocketSessions* sessions{nullptr};
|
||||
WebSocketUpgradeOptions options{};
|
||||
};
|
||||
|
||||
class TcpWebSocketConnection final : public WebSocketConnection
|
||||
{
|
||||
public:
|
||||
|
||||
TcpWebSocketConnection(WebSocketConnectionId id, int fd,
|
||||
WebSocketLimits limits) noexcept
|
||||
: m_id(id), m_fd(fd), m_limits(limits)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] WebSocketConnectionId id() const noexcept override
|
||||
{
|
||||
return m_id;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_text(std::string_view message) override
|
||||
{
|
||||
if (!is_valid_utf8(message)) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::WebSocket: invalid UTF-8 in server text")};
|
||||
}
|
||||
if (message.size() > m_limits.max_message_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::WebSocket: message exceeds max_message_bytes")};
|
||||
}
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Text;
|
||||
f.masked = false;
|
||||
f.payload.resize(message.size());
|
||||
if (!message.empty()) {
|
||||
std::memcpy(f.payload.data(), message.data(),
|
||||
message.size());
|
||||
}
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_binary(std::span<const std::byte> message) override
|
||||
{
|
||||
if (message.size() > m_limits.max_message_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::WebSocket: binary message exceeds limit")};
|
||||
}
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Binary;
|
||||
f.masked = false;
|
||||
f.payload.assign(message.begin(), message.end());
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_pong(std::span<const std::byte> payload)
|
||||
{
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Pong;
|
||||
f.masked = false;
|
||||
f.payload.assign(payload.begin(), payload.end());
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
void close(const WebSocketClose& close_info) noexcept override
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
if (m_closed || m_fd < 0) {
|
||||
m_closed = true;
|
||||
return;
|
||||
}
|
||||
m_closed = true;
|
||||
if (!m_close_sent) {
|
||||
m_close_sent = true;
|
||||
auto cf = encode_websocket_close_frame(close_info, false);
|
||||
if (cf.has_value()) {
|
||||
(void)send_all(m_fd, *cf,
|
||||
std::chrono::milliseconds{500});
|
||||
}
|
||||
}
|
||||
(void)::shutdown(m_fd, SHUT_RDWR);
|
||||
}
|
||||
|
||||
void detach_fd() noexcept
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
m_closed = true;
|
||||
m_fd = -1;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_closed() const noexcept
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
return m_closed || m_fd < 0;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_frame(const WebSocketFrame& frame)
|
||||
{
|
||||
auto encoded = encode_websocket_frame(frame);
|
||||
if (!encoded.has_value()) {
|
||||
return std::unexpected{std::move(encoded.error())};
|
||||
}
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
if (m_closed || m_fd < 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net::WebSocket: connection closed")};
|
||||
}
|
||||
return send_all(m_fd, *encoded, m_limits.io_timeout);
|
||||
}
|
||||
|
||||
WebSocketConnectionId m_id{};
|
||||
mutable std::mutex m_io_mutex{};
|
||||
int m_fd{-1};
|
||||
bool m_closed{false};
|
||||
bool m_close_sent{false};
|
||||
WebSocketLimits m_limits{};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
struct HttpServer::Impl {
|
||||
@@ -891,6 +1023,8 @@ namespace Void::Net
|
||||
|
||||
mutable std::shared_mutex stream_mutex{};
|
||||
std::vector<StreamingRoute> streaming_routes{};
|
||||
std::vector<WebSocketRoute> ws_routes{};
|
||||
std::atomic<std::uint64_t> next_ws_id{1};
|
||||
|
||||
std::atomic<bool> running{false};
|
||||
std::atomic<bool> stopping{false};
|
||||
@@ -958,6 +1092,157 @@ namespace Void::Net
|
||||
best->handler, std::move(best_params)};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<WebSocketRoute>
|
||||
match_websocket(std::string_view path_view) const
|
||||
{
|
||||
const auto segments = split_path(path_view);
|
||||
std::shared_lock lock{stream_mutex};
|
||||
const WebSocketRoute* best = nullptr;
|
||||
for (const auto& r : ws_routes) {
|
||||
if (!match_segments(r.segments, segments).has_value()) {
|
||||
continue;
|
||||
}
|
||||
if (best == nullptr ||
|
||||
more_specific_route(r.segments, best->segments)) {
|
||||
best = &r;
|
||||
}
|
||||
}
|
||||
if (best == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return *best;
|
||||
}
|
||||
|
||||
void run_websocket_session(int fd, const WebSocketRoute& route,
|
||||
const WebSocketUpgradeHandshake& hs,
|
||||
std::string& rx_buf,
|
||||
std::size_t& rx_off)
|
||||
{
|
||||
std::string resp = std::format(
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: {}\r\n",
|
||||
hs.accept_key);
|
||||
if (hs.selected_subprotocol.has_value()) {
|
||||
resp += std::format("Sec-WebSocket-Protocol: {}\r\n",
|
||||
*hs.selected_subprotocol);
|
||||
}
|
||||
resp += "\r\n";
|
||||
if (!send_str(fd, resp, options.write_timeout).has_value()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const WebSocketConnectionId cid{
|
||||
next_ws_id.fetch_add(1, std::memory_order_relaxed)};
|
||||
auto conn = std::make_shared<TcpWebSocketConnection>(
|
||||
cid, fd, route.options.limits);
|
||||
auto opened = route.sessions->open(conn);
|
||||
if (!opened.has_value() || !(*opened)) {
|
||||
conn->close({1001, "session rejected"});
|
||||
conn->detach_fd();
|
||||
return;
|
||||
}
|
||||
|
||||
WebSocketDecoder decoder{true, route.options.limits};
|
||||
WebSocketClose final_close{1000, ""};
|
||||
bool protocol_failed = false;
|
||||
|
||||
auto process_messages =
|
||||
[&](const std::vector<WebSocketMessage>& messages) -> bool {
|
||||
for (const auto& msg : messages) {
|
||||
switch (msg.opcode) {
|
||||
case WebSocketOpcode::Text:
|
||||
(void)route.sessions->receive_text(
|
||||
cid, msg.text_view());
|
||||
break;
|
||||
case WebSocketOpcode::Binary:
|
||||
(void)route.sessions->receive_binary(
|
||||
cid, msg.payload);
|
||||
break;
|
||||
case WebSocketOpcode::Ping:
|
||||
if (!conn->send_pong(msg.payload).has_value()) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case WebSocketOpcode::Pong:
|
||||
break;
|
||||
case WebSocketOpcode::Close:
|
||||
final_close = msg.close_info.value_or(
|
||||
WebSocketClose{1000, ""});
|
||||
conn->close(final_close);
|
||||
return false;
|
||||
case WebSocketOpcode::Continuation:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return !conn->is_closed();
|
||||
};
|
||||
|
||||
bool active = true;
|
||||
if (rx_off < rx_buf.size()) {
|
||||
const auto tail = std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(rx_buf.data()) +
|
||||
rx_off,
|
||||
rx_buf.size() - rx_off};
|
||||
std::vector<WebSocketMessage> msgs;
|
||||
auto dr = decoder.feed(tail, msgs);
|
||||
rx_buf.clear();
|
||||
rx_off = 0;
|
||||
if (!dr.has_value()) {
|
||||
protocol_failed = true;
|
||||
(void)route.sessions->fail(cid, dr.error());
|
||||
final_close = {1002, "protocol error"};
|
||||
conn->close(final_close);
|
||||
active = false;
|
||||
} else {
|
||||
active = process_messages(msgs);
|
||||
}
|
||||
}
|
||||
|
||||
std::array<char, 8192> buf{};
|
||||
while (active && !stopping.load(std::memory_order_acquire) &&
|
||||
!conn->is_closed()) {
|
||||
auto nr = recv_slice(fd, buf, stopping,
|
||||
route.options.limits.io_timeout);
|
||||
if (!nr.has_value()) {
|
||||
if (stopping.load(std::memory_order_acquire)) {
|
||||
final_close = {1001, "server shutdown"};
|
||||
conn->close(final_close);
|
||||
} else if (nr.error().kind() !=
|
||||
Void::Result::ErrorKind::cancelled) {
|
||||
(void)route.sessions->fail(cid, nr.error());
|
||||
final_close = {1006, "transport error"};
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (*nr == 0) {
|
||||
if (!decoder.close_received()) {
|
||||
final_close = {1006, "peer closed"};
|
||||
}
|
||||
break;
|
||||
}
|
||||
std::vector<WebSocketMessage> msgs;
|
||||
auto dr = decoder.feed(
|
||||
std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(buf.data()),
|
||||
*nr},
|
||||
msgs);
|
||||
if (!dr.has_value()) {
|
||||
protocol_failed = true;
|
||||
(void)route.sessions->fail(cid, dr.error());
|
||||
final_close = {1002, "protocol error"};
|
||||
conn->close(final_close);
|
||||
break;
|
||||
}
|
||||
active = process_messages(msgs);
|
||||
}
|
||||
|
||||
(void)protocol_failed;
|
||||
conn->detach_fd();
|
||||
(void)route.sessions->disconnect(cid, final_close);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<Method>
|
||||
collect_allowed_methods(std::string_view path_view) const
|
||||
{
|
||||
@@ -1289,6 +1574,26 @@ namespace Void::Net
|
||||
keep_alive = false;
|
||||
}
|
||||
|
||||
// 3b. Check RFC 6455 WebSocket upgrade route.
|
||||
if (auto ws_match = match_websocket(raw_path);
|
||||
ws_match.has_value()) {
|
||||
ServerRequest ws_req;
|
||||
ws_req.method = *method_opt;
|
||||
ws_req.path = std::string{raw_path};
|
||||
ws_req.headers = std::move(headers);
|
||||
ws_req.query = std::string{raw_query};
|
||||
auto hs = validate_websocket_upgrade_request(
|
||||
ws_req, ws_match->options);
|
||||
if (!hs.has_value()) {
|
||||
send_error_close(fd_guard.get(), 400,
|
||||
"Bad Request");
|
||||
break;
|
||||
}
|
||||
run_websocket_session(fd_guard.get(), *ws_match, *hs,
|
||||
rx_buf, rx_off);
|
||||
break;
|
||||
}
|
||||
|
||||
// 4. Check streaming route vs buffered Router.
|
||||
auto streaming_match =
|
||||
match_streaming(*method_opt, raw_path);
|
||||
@@ -1681,6 +1986,31 @@ namespace Void::Net
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
HttpServer::add_websocket_route(std::string pattern,
|
||||
WebSocketSessions& sessions,
|
||||
WebSocketUpgradeOptions options)
|
||||
{
|
||||
auto compiled = compile_route_pattern(pattern);
|
||||
if (!compiled.has_value()) {
|
||||
return std::unexpected{std::move(compiled.error())};
|
||||
}
|
||||
std::unique_lock lock{m_impl->stream_mutex};
|
||||
const auto dup = std::ranges::find_if(
|
||||
m_impl->ws_routes, [&](const WebSocketRoute& r) {
|
||||
return same_route_shape(r.segments, *compiled);
|
||||
});
|
||||
if (dup != m_impl->ws_routes.end()) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::HttpServer: duplicate WebSocket route")};
|
||||
}
|
||||
m_impl->ws_routes.push_back(WebSocketRoute{
|
||||
std::move(pattern), std::move(*compiled), &sessions,
|
||||
std::move(options)});
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> HttpServer::start()
|
||||
{
|
||||
if (m_impl->running.load(std::memory_order_acquire)) {
|
||||
|
||||
@@ -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
|
||||
+271
-1
@@ -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
|
||||
{
|
||||
@@ -440,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)
|
||||
@@ -458,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
@@ -1,5 +1,5 @@
|
||||
void_add_module(Net
|
||||
INTERNAL_DEPS Functional Text
|
||||
INTERNAL_DEPS Functional Text Time
|
||||
EXTERNAL_DEPS
|
||||
Boost::headers
|
||||
Boost::beast
|
||||
|
||||
@@ -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
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(RPC
|
||||
INTERNAL_DEPS Core Functional Binary Data Time Async Net
|
||||
)
|
||||
@@ -1,3 +1,3 @@
|
||||
void_add_module(ShortUrl
|
||||
INTERNAL_DEPS Service
|
||||
INTERNAL_DEPS Service Time
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(ShortUrlRemote
|
||||
INTERNAL_DEPS ShortUrl Net Data
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(ShortUrlStorage
|
||||
INTERNAL_DEPS ShortUrl Storage Security
|
||||
)
|
||||
@@ -292,7 +292,7 @@ if(_has_fsm)
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
has_modules(_has_net Net Functional Text)
|
||||
has_modules(_has_net Net Functional Text Time)
|
||||
if(_has_net)
|
||||
run_consumer(NetOnly "${install_prefix}" "NetOnly"
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||
@@ -300,6 +300,24 @@ if(_has_net)
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
has_modules(_has_testing_mock TestingMock Testing Functional Core)
|
||||
if(_has_testing_mock)
|
||||
run_consumer(TestingMockOnly "${install_prefix}" "TestingMockOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_short_url ShortUrl Service Time Functional)
|
||||
if(_has_short_url)
|
||||
run_consumer(ShortUrlOnly "${install_prefix}" "ShortUrlOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_rpc RPC Net Binary Data Time Async Functional Core)
|
||||
if(_has_rpc)
|
||||
run_consumer(RpcOnly "${install_prefix}" "RpcOnly"
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -1,10 +1,29 @@
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/HttpCodec.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/Net/Pool.hpp>
|
||||
#include <Void/Net/WebSocket.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
{
|
||||
if (Void::Net::compute_websocket_accept("dGhlIHNhbXBsZSBub25jZQ==") !=
|
||||
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") {
|
||||
return 10;
|
||||
}
|
||||
Void::Net::HttpRequestParser parser;
|
||||
std::size_t consumed = 0;
|
||||
auto pr = parser.feed("GET /ping HTTP/1.1\r\nHost: localhost\r\n\r\n",
|
||||
consumed);
|
||||
if (!pr.has_value() || *pr != Void::Net::HttpParseStatus::Complete) {
|
||||
return 11;
|
||||
}
|
||||
Void::Net::ConnectionPool pool;
|
||||
if (pool.stats().total_connections != 0) {
|
||||
return 12;
|
||||
}
|
||||
|
||||
Void::Net::HttpServer server;
|
||||
if (!server
|
||||
.add_route(Void::Net::Method::Get, "/ping",
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidRpcOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS RPC)
|
||||
|
||||
add_executable(rpc_only_consumer main.cpp)
|
||||
target_link_libraries(rpc_only_consumer PRIVATE Void::RPC)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME rpc_only_consumer COMMAND rpc_only_consumer)
|
||||
@@ -0,0 +1,26 @@
|
||||
#include <Void/RPC/Codec.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace Void::RPC;
|
||||
Server server;
|
||||
constexpr MethodId kPing{1, 1};
|
||||
auto reg = server.bind(
|
||||
MethodDescriptor{kPing, "sys", "ping", 1, true},
|
||||
[](const CallContext&, OwnedBytes body) { return Void::Result::ok(body); });
|
||||
if (!reg.has_value() || !server.start().has_value()) {
|
||||
return 1;
|
||||
}
|
||||
Client client{ClientOptions{.endpoint_base_url = server.base_url()}};
|
||||
OwnedBytes payload{std::byte{'o'}, std::byte{'k'}};
|
||||
auto resp = client.call(kPing, payload);
|
||||
server.shutdown();
|
||||
if (!resp.has_value() || resp->size() != 2 || (*resp)[0] != std::byte{'o'}) {
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidShortUrlOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS ShortUrl)
|
||||
|
||||
add_executable(short_url_only_consumer main.cpp)
|
||||
target_link_libraries(short_url_only_consumer PRIVATE Void::ShortUrl)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME short_url_only_consumer COMMAND short_url_only_consumer)
|
||||
@@ -0,0 +1,21 @@
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
#include <Void/ShortUrl/V2.hpp>
|
||||
|
||||
#include <memory>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace Void::ShortUrl::V2;
|
||||
auto repo = std::make_shared<InMemoryLinkRepository>();
|
||||
auto provider = std::make_shared<LocalProvider>(repo);
|
||||
V1Adapter v1{provider};
|
||||
auto s = v1.shorten({.target_url = "https://example.com/pkg"});
|
||||
if (!s.ok()) {
|
||||
return 1;
|
||||
}
|
||||
auto r = v1.resolve({.key = s.key});
|
||||
if (!r.ok() || r.target_url != "https://example.com/pkg") {
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidTestingMockOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS TestingMock)
|
||||
|
||||
add_executable(testing_mock_only_consumer main.cpp)
|
||||
target_link_libraries(testing_mock_only_consumer PRIVATE Void::TestingMock)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME testing_mock_only_consumer COMMAND testing_mock_only_consumer)
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <Void/TestingMock/Matcher.hpp>
|
||||
#include <Void/TestingMock/MockFunction.hpp>
|
||||
#include <Void/TestingMock/Session.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace Void::TestingMock;
|
||||
|
||||
MockSession session;
|
||||
MockFunction<std::unique_ptr<int>(std::string)> fn{session, "lookup"};
|
||||
auto exp = fn.try_expect(
|
||||
AllOf<std::string>(StartsWith<std::string>("k_"),
|
||||
EndsWith<std::string>("_1")));
|
||||
if (!exp.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
(*exp)->returns_once(std::make_unique<int>(42));
|
||||
if (!freeze(session, Concurrency::SingleThread).has_value()) {
|
||||
return 2;
|
||||
}
|
||||
auto out = fn("k_ok_1");
|
||||
if (!out || *out != 42) {
|
||||
return 3;
|
||||
}
|
||||
auto rep = verify_and_close(session);
|
||||
if (!rep.has_value() || !rep->ok()) {
|
||||
return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/HttpCodec.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/Net/Pool.hpp>
|
||||
#include <Void/Net/Server.hpp>
|
||||
#include <Void/Net/WebSocket.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct FakeConn final : Void::Net::PooledConnection {
|
||||
std::atomic<bool> open{true};
|
||||
std::atomic<int>* close_counter{nullptr};
|
||||
std::uint64_t id{0};
|
||||
|
||||
FakeConn(std::uint64_t cid, std::atomic<int>* closes)
|
||||
: close_counter(closes), id(cid)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept override
|
||||
{
|
||||
return open.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void close() noexcept override
|
||||
{
|
||||
if (open.exchange(false, std::memory_order_acq_rel) &&
|
||||
close_counter != nullptr) {
|
||||
close_counter->fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test net_http_codec_incremental_chunked_trailers_and_smuggling()
|
||||
{
|
||||
// 1. Feed chunked request with chunk extension + trailer byte-by-byte.
|
||||
const std::string raw_req =
|
||||
"POST /upload?x=1 HTTP/1.1\r\n"
|
||||
"Host: example.test\r\n"
|
||||
"Transfer-Encoding: chunked\r\n"
|
||||
"\r\n"
|
||||
"5;ext=1\r\n"
|
||||
"hello\r\n"
|
||||
"6\r\n"
|
||||
" world\r\n"
|
||||
"0;final=yes\r\n"
|
||||
"X-Checksum: abc123\r\n"
|
||||
"\r\n";
|
||||
|
||||
Void::Net::HttpRequestParser req_parser;
|
||||
std::size_t total_consumed = 0;
|
||||
for (std::size_t i = 0; i < raw_req.size(); ++i) {
|
||||
std::size_t c = 0;
|
||||
auto res = req_parser.feed(std::string_view{raw_req.data() + i, 1}, c);
|
||||
Void::Testing::require(res.has_value());
|
||||
total_consumed += c;
|
||||
if (i + 1 < raw_req.size()) {
|
||||
Void::Testing::expect(*res == Void::Net::HttpParseStatus::NeedMoreData);
|
||||
} else {
|
||||
Void::Testing::expect(*res == Void::Net::HttpParseStatus::Complete);
|
||||
}
|
||||
}
|
||||
Void::Testing::expect_eq(total_consumed, raw_req.size());
|
||||
Void::Testing::expect(req_parser.connection_reusable());
|
||||
const auto req = req_parser.take_request();
|
||||
Void::Testing::expect(req.method == Void::Net::Method::Post);
|
||||
Void::Testing::expect_eq(req.target, std::string{"/upload?x=1"});
|
||||
Void::Testing::expect_eq(req.body, std::string{"hello world"});
|
||||
Void::Testing::require(req.trailers.size() == 1U);
|
||||
Void::Testing::expect_eq(req.trailers[0].name, std::string{"X-Checksum"});
|
||||
Void::Testing::expect_eq(req.trailers[0].value, std::string{"abc123"});
|
||||
|
||||
// 2. Reject smuggling combinations (TE+CL, duplicate CL, bare LF, missing Host).
|
||||
const std::vector<std::string> bad_requests{
|
||||
"POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n",
|
||||
"POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\nContent-Length: 4\r\n\r\nabcd",
|
||||
"GET /a HTTP/1.1\r\nHost: x\nX-Bad: 1\r\n\r\n",
|
||||
"GET /a HTTP/1.1\r\nUser-Agent: test\r\n\r\n",
|
||||
};
|
||||
for (const auto& bad : bad_requests) {
|
||||
Void::Net::HttpRequestParser p;
|
||||
std::size_t c = 0;
|
||||
auto r = p.feed(bad, c);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect(!p.connection_reusable());
|
||||
}
|
||||
|
||||
// 3. Response parser: 100 Continue + 103 Early Hints + 200 OK with body.
|
||||
const std::string raw_resp =
|
||||
"HTTP/1.1 100 Continue\r\n\r\n"
|
||||
"HTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload\r\n\r\n"
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndone";
|
||||
Void::Net::HttpResponseParser resp_parser;
|
||||
std::size_t rc = 0;
|
||||
auto rr = resp_parser.feed(raw_resp, rc);
|
||||
Void::Testing::require(rr.has_value());
|
||||
Void::Testing::expect(*rr == Void::Net::HttpParseStatus::Complete);
|
||||
Void::Testing::expect(resp_parser.connection_reusable());
|
||||
const auto resp = resp_parser.take_response();
|
||||
Void::Testing::expect_eq(resp.status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(resp.body, std::string{"done"});
|
||||
Void::Testing::require(resp.informational_statuses.size() == 2U);
|
||||
Void::Testing::expect_eq(resp.informational_statuses[0], std::uint16_t{100});
|
||||
Void::Testing::expect_eq(resp.informational_statuses[1], std::uint16_t{103});
|
||||
|
||||
// 4. HEAD response with non-zero Content-Length completes with zero body.
|
||||
Void::Net::HttpResponseParser head_parser{{}, Void::Net::Method::Head};
|
||||
auto hr = head_parser.feed(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 9999\r\n\r\n", rc);
|
||||
Void::Testing::require(hr.has_value());
|
||||
Void::Testing::expect(*hr == Void::Net::HttpParseStatus::Complete);
|
||||
Void::Testing::expect(head_parser.response().body.empty());
|
||||
|
||||
// 5. Close-delimited response completes on EOF and is non-reusable.
|
||||
Void::Net::HttpResponseParser close_parser;
|
||||
auto cr = close_parser.feed("HTTP/1.1 200 OK\r\n\r\nstreamed", rc);
|
||||
Void::Testing::require(cr.has_value());
|
||||
Void::Testing::expect(*cr == Void::Net::HttpParseStatus::NeedMoreData);
|
||||
Void::Testing::require(close_parser.finish_eof().has_value());
|
||||
Void::Testing::expect(close_parser.complete());
|
||||
Void::Testing::expect(!close_parser.connection_reusable());
|
||||
Void::Testing::expect_eq(close_parser.response().body, std::string{"streamed"});
|
||||
}
|
||||
|
||||
Void::Testing::Test net_connection_pool_isolation_limits_and_clock_eviction()
|
||||
{
|
||||
Void::Time::ManualClock clock;
|
||||
Void::Net::PoolLimits limits;
|
||||
limits.max_total_connections = 3;
|
||||
limits.max_per_origin = 2;
|
||||
limits.max_idle_connections = 2;
|
||||
limits.idle_timeout = std::chrono::seconds{10};
|
||||
|
||||
Void::Net::ConnectionPool pool{limits, clock};
|
||||
std::atomic<std::uint64_t> next_id{1};
|
||||
std::atomic<int> closes{0};
|
||||
|
||||
auto factory = [&](const Void::Net::PoolKey&)
|
||||
-> Void::Result::Result<std::unique_ptr<Void::Net::PooledConnection>> {
|
||||
return std::make_unique<FakeConn>(
|
||||
next_id.fetch_add(1, std::memory_order_relaxed), &closes);
|
||||
};
|
||||
|
||||
const Void::Net::PoolKey k1{"https", "api.example", 443, "", 1};
|
||||
const Void::Net::PoolKey k1_gen2{"https", "api.example", 443, "", 2};
|
||||
const Void::Net::PoolKey k2{"https", "cdn.example", 443, "", 1};
|
||||
|
||||
// Acquire, mark reusable, return -> second acquire reuses same ID.
|
||||
std::uint64_t first_id = 0;
|
||||
{
|
||||
auto l1 = pool.acquire(k1, factory);
|
||||
Void::Testing::require(l1.has_value());
|
||||
Void::Testing::expect(!l1->reused());
|
||||
first_id = static_cast<FakeConn*>(l1->get())->id;
|
||||
l1->mark_reusable(true);
|
||||
}
|
||||
{
|
||||
auto l2 = pool.acquire(k1, factory);
|
||||
Void::Testing::require(l2.has_value());
|
||||
Void::Testing::expect(l2->reused());
|
||||
Void::Testing::expect_eq(static_cast<FakeConn*>(l2->get())->id, first_id);
|
||||
// Do NOT mark reusable -> closes dirty on release.
|
||||
}
|
||||
Void::Testing::expect_eq(closes.load(), 1);
|
||||
Void::Testing::expect_eq(pool.stats().closed_dirty, std::uint64_t{1});
|
||||
|
||||
// Different TLS generation must NOT reuse k1's idle connection.
|
||||
{
|
||||
auto a = pool.acquire(k1, factory);
|
||||
Void::Testing::require(a.has_value());
|
||||
a->mark_reusable(true);
|
||||
}
|
||||
{
|
||||
auto b = pool.acquire(k1_gen2, factory);
|
||||
Void::Testing::require(b.has_value());
|
||||
Void::Testing::expect(!b->reused());
|
||||
b->mark_reusable(true);
|
||||
}
|
||||
|
||||
// Deterministic idle timeout eviction via ManualClock.
|
||||
Void::Testing::expect_eq(pool.stats().idle_connections, std::size_t{2});
|
||||
Void::Testing::require(clock.advance(std::chrono::seconds{11}).has_value());
|
||||
Void::Testing::expect_eq(pool.evict_expired(), std::size_t{2});
|
||||
Void::Testing::expect_eq(pool.stats().idle_connections, std::size_t{0});
|
||||
|
||||
// Per-origin limit = 2 rejects 3rd simultaneous active lease on k2.
|
||||
auto c1 = pool.acquire(k2, factory);
|
||||
auto c2 = pool.acquire(k2, factory);
|
||||
auto c3 = pool.acquire(k2, factory);
|
||||
Void::Testing::require(c1.has_value());
|
||||
Void::Testing::require(c2.has_value());
|
||||
Void::Testing::expect(!c3.has_value());
|
||||
Void::Testing::expect(c3.error().kind() == Void::Result::ErrorKind::overloaded);
|
||||
|
||||
pool.shutdown();
|
||||
c1->release();
|
||||
c2->release();
|
||||
Void::Testing::expect_eq(pool.stats().total_connections, std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test net_static_file_resolver_open_safe_pins_root_and_rejects_symlinks()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_net_static_"};
|
||||
const auto root = tmp / "www";
|
||||
const auto secret = tmp / "secret.txt";
|
||||
std::filesystem::create_directories(root / "sub");
|
||||
{
|
||||
std::ofstream f{root / "sub" / "index.html"};
|
||||
f << "<h1>hello</h1>";
|
||||
}
|
||||
{
|
||||
std::ofstream f{secret};
|
||||
f << "top-secret";
|
||||
}
|
||||
std::filesystem::create_symlink(secret, root / "escape.txt");
|
||||
|
||||
auto resolver = Void::Net::StaticFileResolver::create(root);
|
||||
Void::Testing::require(resolver.has_value());
|
||||
|
||||
// Directory open resolves index.html beneath pinned descriptor.
|
||||
auto opened = resolver->open_safe("/sub/");
|
||||
Void::Testing::require(opened.has_value());
|
||||
Void::Testing::require(opened->has_value());
|
||||
Void::Testing::expect_eq((*opened)->content_type(),
|
||||
std::string_view{"text/html; charset=utf-8"});
|
||||
auto data = (*opened)->read_all();
|
||||
Void::Testing::require(data.has_value());
|
||||
Void::Testing::expect_eq(*data, std::string{"<h1>hello</h1>"});
|
||||
|
||||
// Missing file returns empty optional (not error).
|
||||
auto missing = resolver->open_safe("/nope.txt");
|
||||
Void::Testing::require(missing.has_value());
|
||||
Void::Testing::expect(!missing->has_value());
|
||||
|
||||
// Symlink inside root is rejected by O_NOFOLLOW.
|
||||
auto sym = resolver->open_safe("/escape.txt");
|
||||
Void::Testing::expect(!sym.has_value());
|
||||
|
||||
// Traversal rejected.
|
||||
auto trav = resolver->open_safe("/../secret.txt");
|
||||
Void::Testing::expect(!trav.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test net_http_client_redirects_303_307_and_cross_origin_strip()
|
||||
{
|
||||
Void::Net::HttpServer server1;
|
||||
Void::Net::HttpServer server2;
|
||||
|
||||
std::atomic<bool> got_auth_on_s2{false};
|
||||
Void::Testing::require(
|
||||
server2
|
||||
.add_route(Void::Net::Method::Get, "/landing",
|
||||
[&](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
if (req.header("Authorization").has_value()) {
|
||||
got_auth_on_s2.store(true);
|
||||
}
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200, .body = "from-s2"};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(server2.start().has_value());
|
||||
|
||||
// 303 on POST -> GET to relative location without body.
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Post, "/submit",
|
||||
[](const Void::Net::ServerRequest&)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 303,
|
||||
.headers = {{"Location", "/done"}},
|
||||
.body = ""};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Get, "/done",
|
||||
[](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200,
|
||||
.body = "get-done:" + req.body};
|
||||
})
|
||||
.has_value());
|
||||
// 307 on POST -> preserves POST + body.
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Post, "/temp",
|
||||
[](const Void::Net::ServerRequest&)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 307,
|
||||
.headers = {{"Location", "/temp-dst"}},
|
||||
.body = ""};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Post, "/temp-dst",
|
||||
[](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200, .body = "post:" + req.body};
|
||||
})
|
||||
.has_value());
|
||||
// Cross-origin redirect from server1 -> server2.
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Get, "/cross",
|
||||
[dst = server2.base_url() + "/landing"](
|
||||
const Void::Net::ServerRequest&)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 302,
|
||||
.headers = {{"Location", dst}},
|
||||
.body = ""};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(server1.start().has_value());
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
client.set_max_redirects(5);
|
||||
|
||||
auto r303 = client.post(server1.base_url() + "/submit", "payload");
|
||||
Void::Testing::require(r303.has_value());
|
||||
Void::Testing::expect_eq(r303->status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(r303->body, std::string{"get-done:"});
|
||||
|
||||
auto r307 = client.post(server1.base_url() + "/temp", "keepme");
|
||||
Void::Testing::require(r307.has_value());
|
||||
Void::Testing::expect_eq(r307->status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(r307->body, std::string{"post:keepme"});
|
||||
|
||||
auto rcross = client.get(server1.base_url() + "/cross",
|
||||
{{"Authorization", "Bearer top-secret"}});
|
||||
Void::Testing::require(rcross.has_value());
|
||||
Void::Testing::expect_eq(rcross->status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(rcross->body, std::string{"from-s2"});
|
||||
Void::Testing::expect(!got_auth_on_s2.load());
|
||||
|
||||
server1.shutdown();
|
||||
server2.shutdown();
|
||||
}
|
||||
|
||||
Void::Testing::Test net_websocket_rfc6455_codec_and_live_server_roundtrip()
|
||||
{
|
||||
// 1. RFC 6455 §1.3 official Sec-WebSocket-Accept vector.
|
||||
Void::Testing::expect_eq(
|
||||
Void::Net::compute_websocket_accept("dGhlIHNhbXBsZSBub25jZQ=="),
|
||||
std::string{"s3pPLMBiTxaQ9kYGzzhZRbK+xOo="});
|
||||
|
||||
// 2. Decoder enforces client masking & strict UTF-8 on text frames.
|
||||
Void::Net::WebSocketDecoder server_dec{true};
|
||||
Void::Net::WebSocketFrame unmasked;
|
||||
unmasked.opcode = Void::Net::WebSocketOpcode::Text;
|
||||
unmasked.masked = false;
|
||||
auto raw_unmasked = Void::Net::encode_websocket_frame(unmasked);
|
||||
Void::Testing::require(raw_unmasked.has_value());
|
||||
std::vector<Void::Net::WebSocketMessage> msgs;
|
||||
Void::Testing::expect(!server_dec.feed(*raw_unmasked, msgs).has_value());
|
||||
|
||||
Void::Net::WebSocketDecoder bad_utf8_dec{true};
|
||||
Void::Net::WebSocketFrame bad_txt;
|
||||
bad_txt.opcode = Void::Net::WebSocketOpcode::Text;
|
||||
bad_txt.masked = true;
|
||||
bad_txt.mask_key = {std::byte{1}, std::byte{2}, std::byte{3}, std::byte{4}};
|
||||
bad_txt.payload = {std::byte{0xFF}, std::byte{0xFE}};
|
||||
auto raw_bad_txt = Void::Net::encode_websocket_frame(bad_txt);
|
||||
Void::Testing::require(raw_bad_txt.has_value());
|
||||
Void::Testing::expect(!bad_utf8_dec.feed(*raw_bad_txt, msgs).has_value());
|
||||
|
||||
// 3. Live loopback HttpServer WebSocket upgrade + WebSocketClient.
|
||||
Void::Net::WebSocketSessions sessions;
|
||||
std::atomic<int> closed_count{0};
|
||||
sessions.set_events(Void::Net::WebSocketEvents{
|
||||
.opened = {},
|
||||
.text =
|
||||
[](const std::shared_ptr<Void::Net::WebSocketConnection>& conn,
|
||||
std::string_view text) {
|
||||
(void)conn->send_text("echo:" + std::string{text});
|
||||
},
|
||||
.binary =
|
||||
[](const std::shared_ptr<Void::Net::WebSocketConnection>& conn,
|
||||
std::span<const std::byte> data) {
|
||||
(void)conn->send_binary(data);
|
||||
},
|
||||
.closed =
|
||||
[&](Void::Net::WebSocketConnectionId,
|
||||
const Void::Net::WebSocketClose&) {
|
||||
closed_count.fetch_add(1, std::memory_order_relaxed);
|
||||
},
|
||||
.error = {},
|
||||
});
|
||||
|
||||
Void::Net::HttpServer server;
|
||||
Void::Net::WebSocketUpgradeOptions ws_opts;
|
||||
ws_opts.supported_subprotocols = {"void.rpc.v1", "chat"};
|
||||
Void::Testing::require(
|
||||
server.add_websocket_route("/ws/echo", sessions, ws_opts).has_value());
|
||||
Void::Testing::require(server.start().has_value());
|
||||
|
||||
const std::string ws_url =
|
||||
"ws://127.0.0.1:" + std::to_string(server.bound_port()) + "/ws/echo";
|
||||
Void::Net::WebSocketClient::ConnectOptions copts;
|
||||
copts.subprotocol = "void.rpc.v1";
|
||||
auto client = Void::Net::WebSocketClient::connect(ws_url, copts);
|
||||
Void::Testing::require(client.has_value());
|
||||
Void::Testing::require(client->selected_subprotocol().has_value());
|
||||
Void::Testing::expect_eq(*client->selected_subprotocol(),
|
||||
std::string{"void.rpc.v1"});
|
||||
|
||||
// Text round-trip.
|
||||
Void::Testing::require(client->send_text("hello ws").has_value());
|
||||
auto m1 = client->receive();
|
||||
Void::Testing::require(m1.has_value());
|
||||
Void::Testing::expect(m1->opcode == Void::Net::WebSocketOpcode::Text);
|
||||
Void::Testing::expect_eq(std::string{m1->text_view()},
|
||||
std::string{"echo:hello ws"});
|
||||
|
||||
// Fragmented UTF-8 text round-trip (split multi-byte UTF-8 sequence across
|
||||
// frames).
|
||||
const std::array<std::string_view, 3> frags{"frag-", "\xE2\x9C", "\x94!"};
|
||||
Void::Testing::require(client->send_fragmented_text(frags).has_value());
|
||||
auto m2 = client->receive();
|
||||
Void::Testing::require(m2.has_value());
|
||||
Void::Testing::expect_eq(std::string{m2->text_view()},
|
||||
std::string{"echo:frag-\xE2\x9C\x94!"});
|
||||
|
||||
// Binary round-trip.
|
||||
const std::array<std::byte, 4> bin{std::byte{0x00}, std::byte{0xDE},
|
||||
std::byte{0xAD}, std::byte{0xFF}};
|
||||
Void::Testing::require(client->send_binary(bin).has_value());
|
||||
auto m3 = client->receive();
|
||||
Void::Testing::require(m3.has_value());
|
||||
Void::Testing::expect(m3->opcode == Void::Net::WebSocketOpcode::Binary);
|
||||
Void::Testing::expect_eq(m3->payload.size(), std::size_t{4});
|
||||
Void::Testing::expect(m3->payload[1] == std::byte{0xDE});
|
||||
|
||||
// Ping -> automatic server Pong echoing payload.
|
||||
const std::array<std::byte, 3> ping_bytes{std::byte{'p'}, std::byte{'n'},
|
||||
std::byte{'g'}};
|
||||
Void::Testing::require(client->send_ping(ping_bytes).has_value());
|
||||
auto m4 = client->receive();
|
||||
Void::Testing::require(m4.has_value());
|
||||
Void::Testing::expect(m4->opcode == Void::Net::WebSocketOpcode::Pong);
|
||||
Void::Testing::expect_eq(m4->payload.size(), std::size_t{3});
|
||||
|
||||
// Graceful close handshake.
|
||||
Void::Testing::require(client->close({1000, "done"}).has_value());
|
||||
server.shutdown();
|
||||
Void::Testing::expect(closed_count.load() >= 1);
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
#include <Void/RPC/Codec.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::RPC::OwnedBytes to_bytes(std::string_view s)
|
||||
{
|
||||
Void::RPC::OwnedBytes out(s.size());
|
||||
if (!s.empty()) {
|
||||
std::memcpy(out.data(), s.data(), s.size());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string from_bytes(const Void::RPC::OwnedBytes& b)
|
||||
{
|
||||
return std::string(reinterpret_cast<const char*>(b.data()), b.size());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test rpc_wire_v1_codec_roundtrip_and_malformed_rejection()
|
||||
{
|
||||
using namespace Void::RPC;
|
||||
|
||||
WireEnvelope env;
|
||||
env.kind = FrameKind::UnaryRequest;
|
||||
env.call_id = CallId::generate();
|
||||
env.method = MethodId{0x0102030405060708ULL, 42U};
|
||||
env.schema_version = 3U;
|
||||
env.remaining_timeout_ms = 5000U;
|
||||
env.metadata = {{"trace-id", "t-123"}, {"tenant", "alpha"}};
|
||||
env.payload = to_bytes("hello-vrpc");
|
||||
|
||||
auto encoded = encode_envelope(env);
|
||||
Void::Testing::require(encoded.has_value());
|
||||
Void::Testing::expect(encoded->size() >= kWireFixedHeaderBytes);
|
||||
|
||||
auto decoded = decode_envelope(*encoded);
|
||||
Void::Testing::require(decoded.has_value());
|
||||
Void::Testing::expect(decoded->call_id == env.call_id);
|
||||
Void::Testing::expect(decoded->method == env.method);
|
||||
Void::Testing::expect_eq(decoded->schema_version, 3U);
|
||||
Void::Testing::expect_eq(decoded->remaining_timeout_ms, 5000U);
|
||||
Void::Testing::expect(decoded->metadata == env.metadata);
|
||||
Void::Testing::expect_eq(from_bytes(decoded->payload),
|
||||
std::string{"hello-vrpc"});
|
||||
|
||||
// 1. Bad magic rejected.
|
||||
auto bad_magic = *encoded;
|
||||
bad_magic[0] = std::byte{'X'};
|
||||
Void::Testing::expect(!decode_envelope(bad_magic).has_value());
|
||||
|
||||
// 2. Unknown major version rejected with IncompatibleVersion.
|
||||
auto bad_major = *encoded;
|
||||
bad_major[4] = std::byte{0};
|
||||
bad_major[5] = std::byte{2};
|
||||
auto r_maj = decode_envelope(bad_major);
|
||||
Void::Testing::expect(!r_maj.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_maj.error()) ==
|
||||
RpcStatusCode::IncompatibleVersion);
|
||||
|
||||
// 3. Non-zero reserved bytes rejected.
|
||||
auto bad_res = *encoded;
|
||||
bad_res[18] = std::byte{0x01};
|
||||
Void::Testing::expect(!decode_envelope(bad_res).has_value());
|
||||
|
||||
// 4. Unknown required flag fails closed.
|
||||
auto bad_flag = *encoded;
|
||||
bad_flag[17] = std::byte{0x10};
|
||||
auto r_flag = decode_envelope(bad_flag);
|
||||
Void::Testing::expect(!r_flag.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_flag.error()) ==
|
||||
RpcStatusCode::IncompatibleVersion);
|
||||
|
||||
// 5. Truncated frame rejected.
|
||||
auto trunc = *encoded;
|
||||
trunc.pop_back();
|
||||
Void::Testing::expect(!decode_envelope(trunc).has_value());
|
||||
|
||||
// 6. Oversized payload limit rejected before allocation.
|
||||
RpcLimits tiny;
|
||||
tiny.max_payload_bytes = 4;
|
||||
auto r_big = decode_envelope(*encoded, tiny);
|
||||
Void::Testing::expect(!r_big.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_big.error()) ==
|
||||
RpcStatusCode::ResourceExhausted);
|
||||
|
||||
// 7. Minor > 0 optional trailing header extension is length-skippable!
|
||||
auto minor_ext = *encoded;
|
||||
// Bump minor = 1, header_len += 4, total_len += 4, insert 4 extension bytes
|
||||
// right before payload.
|
||||
const std::size_t orig_hdr_len = encoded->size() - env.payload.size();
|
||||
minor_ext[7] = std::byte{1};
|
||||
const std::uint32_t new_hdr_len = static_cast<std::uint32_t>(orig_hdr_len + 4U);
|
||||
const std::uint32_t new_tot_len = static_cast<std::uint32_t>(encoded->size() + 4U);
|
||||
minor_ext[8] = static_cast<std::byte>((new_hdr_len >> 24U) & 0xFFU);
|
||||
minor_ext[9] = static_cast<std::byte>((new_hdr_len >> 16U) & 0xFFU);
|
||||
minor_ext[10] = static_cast<std::byte>((new_hdr_len >> 8U) & 0xFFU);
|
||||
minor_ext[11] = static_cast<std::byte>(new_hdr_len & 0xFFU);
|
||||
minor_ext[12] = static_cast<std::byte>((new_tot_len >> 24U) & 0xFFU);
|
||||
minor_ext[13] = static_cast<std::byte>((new_tot_len >> 16U) & 0xFFU);
|
||||
minor_ext[14] = static_cast<std::byte>((new_tot_len >> 8U) & 0xFFU);
|
||||
minor_ext[15] = static_cast<std::byte>(new_tot_len & 0xFFU);
|
||||
const std::array<std::byte, 4> ext_bytes{
|
||||
std::byte{0xAA}, std::byte{0xBB}, std::byte{0xCC}, std::byte{0xDD}};
|
||||
minor_ext.insert(
|
||||
minor_ext.begin() + static_cast<std::ptrdiff_t>(orig_hdr_len),
|
||||
ext_bytes.begin(), ext_bytes.end());
|
||||
auto dec_minor = decode_envelope(minor_ext);
|
||||
Void::Testing::require(dec_minor.has_value());
|
||||
Void::Testing::expect_eq(dec_minor->minor, std::uint16_t{1});
|
||||
Void::Testing::expect_eq(from_bytes(dec_minor->payload),
|
||||
std::string{"hello-vrpc"});
|
||||
}
|
||||
|
||||
Void::Testing::Test rpc_unary_http_dispatch_auth_schema_clamp_and_unregister_drain()
|
||||
{
|
||||
using namespace Void::RPC;
|
||||
|
||||
static constexpr MethodId kEcho{100, 1};
|
||||
static constexpr MethodId kThrow{100, 2};
|
||||
static constexpr MethodId kSlow{100, 3};
|
||||
|
||||
ServerOptions sopts;
|
||||
sopts.limits.max_server_timeout = std::chrono::seconds{5};
|
||||
sopts.auth.authenticate =
|
||||
[](const std::vector<Void::Net::Header>& hdrs,
|
||||
const std::vector<MetadataEntry>&)
|
||||
-> Void::Result::Result<PrincipalView> {
|
||||
for (const auto& h : hdrs) {
|
||||
if (h.name == "X-Test-Token" && h.value == "valid-admin") {
|
||||
return PrincipalView{
|
||||
.authenticated = true,
|
||||
.subject = "alice",
|
||||
.roles = {"admin"},
|
||||
};
|
||||
}
|
||||
if (h.name == "X-Test-Token" && h.value == "valid-guest") {
|
||||
return PrincipalView{
|
||||
.authenticated = true,
|
||||
.subject = "bob",
|
||||
.roles = {"guest"},
|
||||
};
|
||||
}
|
||||
}
|
||||
return std::unexpected{
|
||||
make_rpc_error(RpcStatusCode::Unauthenticated, "missing token")};
|
||||
};
|
||||
sopts.auth.authorize = [](const MethodDescriptor& m,
|
||||
const PrincipalView& p)
|
||||
-> Void::Result::Result<void> {
|
||||
if (m.id == kThrow &&
|
||||
std::find(p.roles.begin(), p.roles.end(), "admin") ==
|
||||
p.roles.end()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::PermissionDenied, "admin role required")};
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
Server server{std::move(sopts)};
|
||||
|
||||
std::atomic<long long> observed_timeout_ms{0};
|
||||
auto reg_echo = server.bind(
|
||||
MethodDescriptor{kEcho, "demo", "echo", 2, true},
|
||||
[&](const CallContext& ctx, OwnedBytes body)
|
||||
-> Void::Result::Result<OwnedBytes> {
|
||||
observed_timeout_ms.store(ctx.remaining_timeout().count(),
|
||||
std::memory_order_release);
|
||||
return to_bytes(ctx.principal.subject + ":" + from_bytes(body));
|
||||
});
|
||||
Void::Testing::require(reg_echo.has_value());
|
||||
|
||||
auto reg_throw = server.bind(
|
||||
MethodDescriptor{kThrow, "demo", "throw", 1, false},
|
||||
[](const CallContext&, OwnedBytes) -> Void::Result::Result<OwnedBytes> {
|
||||
throw std::runtime_error("sensitive-internal-secret");
|
||||
});
|
||||
Void::Testing::require(reg_throw.has_value());
|
||||
|
||||
std::atomic<bool> slow_entered{false};
|
||||
std::atomic<bool> slow_release{false};
|
||||
std::atomic<bool> slow_finished{false};
|
||||
auto reg_slow = server.bind(
|
||||
MethodDescriptor{kSlow, "demo", "slow", 1, false},
|
||||
[&](const CallContext&, OwnedBytes body)
|
||||
-> Void::Result::Result<OwnedBytes> {
|
||||
slow_entered.store(true, std::memory_order_release);
|
||||
while (!slow_release.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
slow_finished.store(true, std::memory_order_release);
|
||||
return body;
|
||||
});
|
||||
Void::Testing::require(reg_slow.has_value());
|
||||
|
||||
Void::Testing::require(server.start().has_value());
|
||||
|
||||
ClientOptions copts;
|
||||
copts.endpoint_base_url = server.base_url();
|
||||
Client client{std::move(copts)};
|
||||
|
||||
// 1. Authorized unary call succeeds and clamps excessive caller timeout
|
||||
// (60s -> <= 5s server max).
|
||||
CallOptions ok_opts;
|
||||
ok_opts.schema_version = 2;
|
||||
ok_opts.timeout = std::chrono::seconds{60};
|
||||
ok_opts.transport_headers = {{"X-Test-Token", "valid-admin"}};
|
||||
auto r_ok = client.call(kEcho, to_bytes("ping"), ok_opts);
|
||||
Void::Testing::require(r_ok.has_value());
|
||||
Void::Testing::expect_eq(from_bytes(*r_ok), std::string{"alice:ping"});
|
||||
Void::Testing::expect(observed_timeout_ms.load() <= 5000);
|
||||
Void::Testing::expect(observed_timeout_ms.load() > 0);
|
||||
|
||||
// 2. Schema version mismatch rejected with IncompatibleVersion.
|
||||
CallOptions bad_schema = ok_opts;
|
||||
bad_schema.schema_version = 99;
|
||||
auto r_ver = client.call(kEcho, to_bytes("ping"), bad_schema);
|
||||
Void::Testing::expect(!r_ver.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_ver.error()) ==
|
||||
RpcStatusCode::IncompatibleVersion);
|
||||
|
||||
// 3. Unauthenticated request denied before handler admission.
|
||||
CallOptions no_auth;
|
||||
no_auth.schema_version = 2;
|
||||
auto r_unauth = client.call(kEcho, to_bytes("x"), no_auth);
|
||||
Void::Testing::expect(!r_unauth.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_unauth.error()) ==
|
||||
RpcStatusCode::Unauthenticated);
|
||||
|
||||
// 4. Unauthorized guest denied on admin-only method.
|
||||
CallOptions guest_opts;
|
||||
guest_opts.schema_version = 1;
|
||||
guest_opts.transport_headers = {{"X-Test-Token", "valid-guest"}};
|
||||
auto r_perm = client.call(kThrow, to_bytes("x"), guest_opts);
|
||||
Void::Testing::expect(!r_perm.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_perm.error()) ==
|
||||
RpcStatusCode::PermissionDenied);
|
||||
|
||||
// 5. Handler exception returns sanitized Internal error without leaking
|
||||
// exception message.
|
||||
CallOptions admin_v1;
|
||||
admin_v1.schema_version = 1;
|
||||
admin_v1.transport_headers = {{"X-Test-Token", "valid-admin"}};
|
||||
auto r_throw = client.call(kThrow, to_bytes("x"), admin_v1);
|
||||
Void::Testing::expect(!r_throw.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_throw.error()) ==
|
||||
RpcStatusCode::Internal);
|
||||
Void::Testing::expect(r_throw.error().message().find("sensitive") ==
|
||||
std::string_view::npos);
|
||||
|
||||
// 6. Registration::unregister_and_drain() waits for in-flight call to
|
||||
// finish before returning, then rejects subsequent calls.
|
||||
Void::Result::Result<OwnedBytes> slow_out =
|
||||
std::unexpected{make_rpc_error(RpcStatusCode::Internal, "pending")};
|
||||
std::thread slow_caller(
|
||||
[&]() { slow_out = client.call(kSlow, to_bytes("drain-ok"), admin_v1); });
|
||||
|
||||
while (!slow_entered.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{2});
|
||||
}
|
||||
std::thread releaser([&]() {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{25});
|
||||
slow_release.store(true, std::memory_order_release);
|
||||
});
|
||||
reg_slow->unregister_and_drain();
|
||||
Void::Testing::expect(slow_finished.load(std::memory_order_acquire));
|
||||
releaser.join();
|
||||
slow_caller.join();
|
||||
Void::Testing::require(slow_out.has_value());
|
||||
Void::Testing::expect_eq(from_bytes(*slow_out), std::string{"drain-ok"});
|
||||
|
||||
auto after_unreg = client.call(kSlow, to_bytes("late"), admin_v1);
|
||||
Void::Testing::expect(!after_unreg.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(after_unreg.error()) ==
|
||||
RpcStatusCode::Unimplemented);
|
||||
|
||||
server.shutdown();
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
#include <Void/ShortUrl/V2.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
// Freeze checks on V1 enum ordinals & version constants.
|
||||
static_assert(Void::ShortUrl::V1::kServiceVersion == 1U);
|
||||
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::none) == 0U);
|
||||
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::unsupported) == 2U);
|
||||
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::revoked) == 13U);
|
||||
static_assert(static_cast<std::uint32_t>(Void::ShortUrl::V1::ErrorCode::response_too_large) == 15U);
|
||||
|
||||
Void::Testing::Test shorturl_v2_local_validation_expiry_revoke_and_idempotency()
|
||||
{
|
||||
using namespace Void::ShortUrl::V2;
|
||||
|
||||
Void::Time::ManualCivilClock clock{
|
||||
Void::Time::CivilClock::time_point{std::chrono::seconds{1'700'000'000}}};
|
||||
auto repo = std::make_shared<InMemoryLinkRepository>();
|
||||
Void::Testing::expect(!repo->is_durable());
|
||||
|
||||
LocalProvider::Options opts;
|
||||
opts.public_base_url = "https://sho.rt/s";
|
||||
opts.limits.max_entries = 10;
|
||||
opts.limits.max_retained_identities = 5;
|
||||
opts.host_policy = [](std::string_view host) {
|
||||
return host != "blocked.internal";
|
||||
};
|
||||
|
||||
auto provider = std::make_shared<LocalProvider>(repo, opts, clock);
|
||||
|
||||
// 1. Validation rejects userinfo, non-http, control chars, denied host,
|
||||
// reserved keys, and past expiry.
|
||||
Void::Testing::expect(
|
||||
!provider->shorten({.target_url = "https://user:pw@example.com/a"})
|
||||
.has_value());
|
||||
Void::Testing::expect(
|
||||
!provider->shorten({.target_url = "ftp://example.com/a"}).has_value());
|
||||
Void::Testing::expect(
|
||||
!provider->shorten({.target_url = "https://blocked.internal/x"})
|
||||
.has_value());
|
||||
Void::Testing::expect(
|
||||
!provider
|
||||
->shorten({.target_url = "https://example.com/a",
|
||||
.custom_key = "health"})
|
||||
.has_value());
|
||||
Void::Testing::expect(
|
||||
!provider
|
||||
->shorten({.target_url = "https://example.com/a",
|
||||
.expires_at_unix_seconds = 1'699'999'999})
|
||||
.has_value());
|
||||
|
||||
// 2. Generated 16-char base62 key + V2 idempotency replay within 24h.
|
||||
auto created = provider->shorten(
|
||||
{.target_url = "https://example.com/page"},
|
||||
ShortenOptions{.operation_id = "op-001"});
|
||||
Void::Testing::require(created.has_value());
|
||||
Void::Testing::expect_eq(created->key.size(), std::size_t{16});
|
||||
Void::Testing::expect_eq(created->short_url,
|
||||
"https://sho.rt/s/" + created->key);
|
||||
|
||||
auto replay = provider->shorten(
|
||||
{.target_url = "https://example.com/page"},
|
||||
ShortenOptions{.operation_id = "op-001"});
|
||||
Void::Testing::require(replay.has_value());
|
||||
Void::Testing::expect_eq(replay->key, created->key);
|
||||
|
||||
// 3. Custom key conflict & tombstone non-reuse after revoke.
|
||||
auto custom = provider->shorten({
|
||||
.target_url = "https://example.com/custom",
|
||||
.custom_key = "my_Link-1",
|
||||
.expires_at_unix_seconds = 1'700'003'600,
|
||||
});
|
||||
Void::Testing::require(custom.has_value());
|
||||
Void::Testing::expect_eq(custom->key, std::string{"my_Link-1"});
|
||||
|
||||
auto conflict = provider->shorten({
|
||||
.target_url = "https://example.com/other",
|
||||
.custom_key = "my_Link-1",
|
||||
});
|
||||
Void::Testing::expect(!conflict.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(conflict.error()) ==
|
||||
V2ErrorCode::Conflict);
|
||||
|
||||
auto resolved = provider->resolve("my_Link-1");
|
||||
Void::Testing::require(resolved.has_value());
|
||||
Void::Testing::expect_eq(resolved->target_url,
|
||||
std::string{"https://example.com/custom"});
|
||||
|
||||
// Revoke creates tombstone; resolve returns Revoked and key cannot be
|
||||
// reused.
|
||||
Void::Testing::require(provider->revoke("my_Link-1").has_value());
|
||||
auto after_revoke = provider->resolve("my_Link-1");
|
||||
Void::Testing::expect(!after_revoke.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(after_revoke.error()) ==
|
||||
V2ErrorCode::Revoked);
|
||||
|
||||
auto reuse = provider->shorten({
|
||||
.target_url = "https://example.com/reused",
|
||||
.custom_key = "my_Link-1",
|
||||
});
|
||||
Void::Testing::expect(!reuse.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(reuse.error()) ==
|
||||
V2ErrorCode::Conflict);
|
||||
|
||||
// 4. Expiry via ManualCivilClock + idempotency retention expiry.
|
||||
auto exp_link = provider->shorten({
|
||||
.target_url = "https://example.com/temp",
|
||||
.custom_key = "temp1",
|
||||
.expires_at_unix_seconds = 1'700'000'100,
|
||||
});
|
||||
Void::Testing::require(exp_link.has_value());
|
||||
Void::Testing::require(clock.advance(std::chrono::seconds{200}).has_value());
|
||||
auto exp_res = provider->resolve("temp1");
|
||||
Void::Testing::expect(!exp_res.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(exp_res.error()) ==
|
||||
V2ErrorCode::Expired);
|
||||
|
||||
Void::Testing::require(clock.advance(std::chrono::hours{25}).has_value());
|
||||
auto expired_idem = provider->shorten(
|
||||
{.target_url = "https://example.com/page"},
|
||||
ShortenOptions{.operation_id = "op-001"});
|
||||
Void::Testing::expect(!expired_idem.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(expired_idem.error()) ==
|
||||
V2ErrorCode::IdentityExpired);
|
||||
|
||||
// 5. V1Adapter bridges V2 provider to frozen V1::IShortener cleanly.
|
||||
V1Adapter v1{provider};
|
||||
Void::Testing::expect_eq(v1.service_name(), Void::ShortUrl::V1::kServiceId);
|
||||
Void::Testing::expect_eq(v1.service_version(), std::uint32_t{1});
|
||||
Void::Testing::expect(v1.supports_resolve());
|
||||
|
||||
auto s_v1 = v1.shorten({.target_url = "https://example.com/v1"});
|
||||
Void::Testing::require(s_v1.ok());
|
||||
auto r_v1 = v1.resolve({.key = s_v1.key});
|
||||
Void::Testing::require(r_v1.ok());
|
||||
Void::Testing::expect_eq(r_v1.target_url,
|
||||
std::string{"https://example.com/v1"});
|
||||
|
||||
auto r_revoked = v1.resolve({.key = "my_Link-1"});
|
||||
Void::Testing::expect(!r_revoked.ok());
|
||||
Void::Testing::expect(r_revoked.error.code ==
|
||||
Void::ShortUrl::V1::ErrorCode::revoked);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
#include <Void/Data/StrictJson.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/ShortUrlRemote/RemoteProvider.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
Void::Testing::Test shorturl_remote_provider_capabilities_retry_after_and_unknown()
|
||||
{
|
||||
using namespace Void::ShortUrl::V2;
|
||||
|
||||
Void::Net::HttpServer server;
|
||||
std::atomic<int> shorten_calls{0};
|
||||
std::atomic<bool> stall_next{false};
|
||||
std::atomic<bool> release_stall{false};
|
||||
|
||||
Void::Testing::require(
|
||||
server
|
||||
.add_route(
|
||||
Void::Net::Method::Post, "/v2/shorten",
|
||||
[&](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
const int n =
|
||||
shorten_calls.fetch_add(1, std::memory_order_relaxed);
|
||||
if (stall_next.load(std::memory_order_acquire)) {
|
||||
for (int i = 0; i < 200 &&
|
||||
!release_stall.load(
|
||||
std::memory_order_acquire);
|
||||
++i) {
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::milliseconds{20});
|
||||
}
|
||||
return Void::Net::ServerResponse{.status = 200,
|
||||
.body = "{}"};
|
||||
}
|
||||
if (n == 1) {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 429,
|
||||
.headers = {{"Retry-After", "45"}},
|
||||
.body = "slow down"};
|
||||
}
|
||||
auto parsed = Void::Json::Strict::parse(req.body);
|
||||
Void::Testing::require(parsed.has_value());
|
||||
const auto& obj =
|
||||
std::get<Void::Json::Strict::Value::Object>(
|
||||
parsed->value);
|
||||
const std::string target =
|
||||
std::get<std::string>(obj.at("target_url").value);
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200,
|
||||
.headers = {{"Content-Type", "application/json"}},
|
||||
.body = "{\"key\":\"rem01\",\"short_url\":\"https://"
|
||||
"rem.test/rem01\",\"target_url\":\"" +
|
||||
target + "\"}",
|
||||
};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
Void::Testing::require(
|
||||
server
|
||||
.add_route(
|
||||
Void::Net::Method::Get, "/v2/resolve/:key",
|
||||
[](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
const auto it = req.parameters.find("key");
|
||||
if (it == req.parameters.end() || it->second != "rem01") {
|
||||
return Void::Net::ServerResponse{.status = 404,
|
||||
.body = "missing"};
|
||||
}
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200,
|
||||
.headers = {{"Content-Type", "application/json"}},
|
||||
.body =
|
||||
"{\"target_url\":\"https://example.com/remote\","
|
||||
"\"short_url\":\"https://rem.test/rem01\"}",
|
||||
};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
Void::Testing::require(
|
||||
server
|
||||
.add_route(Void::Net::Method::Delete, "/v2/links/:key",
|
||||
[](const Void::Net::ServerRequest&)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{.status = 204,
|
||||
.body = ""};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
Void::Testing::require(server.start().has_value());
|
||||
|
||||
// 1. Unsupported capability rejected BEFORE any network call!
|
||||
{
|
||||
RemoteProviderOptions opts;
|
||||
opts.base_url = server.base_url();
|
||||
opts.capabilities.supports_custom_key = false;
|
||||
opts.capabilities.supports_expiry = false;
|
||||
opts.capabilities.supports_resolve = false;
|
||||
RemoteProvider restricted{opts};
|
||||
|
||||
auto no_custom = restricted.shorten({
|
||||
.target_url = "https://example.com/a",
|
||||
.custom_key = "nope",
|
||||
});
|
||||
Void::Testing::expect(!no_custom.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(no_custom.error()) ==
|
||||
V2ErrorCode::Unsupported);
|
||||
Void::Testing::expect_eq(shorten_calls.load(), 0);
|
||||
|
||||
auto no_resolve = restricted.resolve("rem01");
|
||||
Void::Testing::expect(!no_resolve.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(no_resolve.error()) ==
|
||||
V2ErrorCode::Unsupported);
|
||||
}
|
||||
|
||||
// 2. Full round-trip, 429 Retry-After preservation, and timeout ->
|
||||
// UnknownOutcome without blind replay.
|
||||
RemoteProviderOptions opts;
|
||||
opts.base_url = server.base_url();
|
||||
opts.timeout = std::chrono::seconds{1};
|
||||
auto provider = std::make_shared<RemoteProvider>(opts);
|
||||
|
||||
auto ok = provider->shorten({.target_url = "https://example.com/remote"},
|
||||
ShortenOptions{.operation_id = "rem-op-1"});
|
||||
Void::Testing::require(ok.has_value());
|
||||
Void::Testing::expect_eq(ok->key, std::string{"rem01"});
|
||||
|
||||
auto res = provider->resolve("rem01");
|
||||
Void::Testing::require(res.has_value());
|
||||
Void::Testing::expect_eq(res->target_url,
|
||||
std::string{"https://example.com/remote"});
|
||||
|
||||
Void::Testing::require(provider->revoke("rem01").has_value());
|
||||
|
||||
// Second shorten hits 429 with Retry-After: 45.
|
||||
auto rl = provider->shorten({.target_url = "https://example.com/rate"});
|
||||
Void::Testing::expect(!rl.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(rl.error()) ==
|
||||
V2ErrorCode::RateLimited);
|
||||
Void::Testing::expect_eq(provider->last_retry_after_seconds(),
|
||||
std::uint32_t{45});
|
||||
|
||||
// Third shorten stalls until 1s timeout -> UnknownOutcome (and V1Adapter
|
||||
// maps it to provider_error).
|
||||
stall_next.store(true, std::memory_order_release);
|
||||
auto unk = provider->shorten({.target_url = "https://example.com/lost"});
|
||||
Void::Testing::expect(!unk.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(unk.error()) ==
|
||||
V2ErrorCode::UnknownOutcome);
|
||||
|
||||
release_stall.store(true, std::memory_order_release);
|
||||
server.shutdown();
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
#include <Void/ShortUrlStorage/StorageRepository.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
Void::Testing::Test shorturl_storage_durable_persistence_tombstones_and_quota()
|
||||
{
|
||||
using namespace Void::ShortUrl::V2;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_shorturl_storage_"};
|
||||
Void::Time::ManualCivilClock clock{
|
||||
Void::Time::CivilClock::time_point{std::chrono::seconds{1'700'000'000}}};
|
||||
|
||||
std::string generated_key;
|
||||
{
|
||||
Void::Storage::OpenOptions sopt;
|
||||
sopt.directory = tmp.path() / "db";
|
||||
auto eng = Void::Storage::Engine::open(sopt);
|
||||
Void::Testing::require(eng.has_value());
|
||||
auto shared_eng =
|
||||
std::make_shared<Void::Storage::Engine>(std::move(*eng));
|
||||
|
||||
auto repo = std::make_shared<StorageLinkRepository>(shared_eng);
|
||||
Void::Testing::expect(repo->is_durable());
|
||||
auto rng = std::make_shared<SecurityRandomBytesPort>();
|
||||
|
||||
LocalProvider::Options lopt;
|
||||
lopt.public_base_url = "https://sho.rt";
|
||||
LocalProvider provider{repo, lopt, clock, rng};
|
||||
|
||||
auto a = provider.shorten({.target_url = "https://example.com/durable"},
|
||||
ShortenOptions{.operation_id = "dur-op-1"});
|
||||
Void::Testing::require(a.has_value());
|
||||
generated_key = a->key;
|
||||
Void::Testing::expect_eq(generated_key.size(), std::size_t{16});
|
||||
|
||||
auto b = provider.shorten({
|
||||
.target_url = "https://example.com/killme",
|
||||
.custom_key = "revokeme",
|
||||
});
|
||||
Void::Testing::require(b.has_value());
|
||||
Void::Testing::require(provider.revoke("revokeme").has_value());
|
||||
Void::Testing::require(shared_eng->close().has_value());
|
||||
}
|
||||
|
||||
// Reopen Storage::Engine from disk and verify durable link, idempotency
|
||||
// replay, and persisted tombstone non-reuse.
|
||||
{
|
||||
Void::Storage::OpenOptions sopt;
|
||||
sopt.directory = tmp.path() / "db";
|
||||
auto eng = Void::Storage::Engine::open(sopt);
|
||||
Void::Testing::require(eng.has_value());
|
||||
auto shared_eng =
|
||||
std::make_shared<Void::Storage::Engine>(std::move(*eng));
|
||||
|
||||
// Tight disk quota test on separate small repo instance check below,
|
||||
// first verify normal recovery.
|
||||
auto repo = std::make_shared<StorageLinkRepository>(shared_eng);
|
||||
LocalProvider::Options lopt;
|
||||
lopt.public_base_url = "https://sho.rt";
|
||||
LocalProvider provider{repo, lopt, clock,
|
||||
std::make_shared<SecurityRandomBytesPort>()};
|
||||
|
||||
auto res = provider.resolve(generated_key);
|
||||
Void::Testing::require(res.has_value());
|
||||
Void::Testing::expect_eq(res->target_url,
|
||||
std::string{"https://example.com/durable"});
|
||||
|
||||
// V2 idempotency replay survives restart!
|
||||
auto replay = provider.shorten(
|
||||
{.target_url = "https://example.com/durable"},
|
||||
ShortenOptions{.operation_id = "dur-op-1"});
|
||||
Void::Testing::require(replay.has_value());
|
||||
Void::Testing::expect_eq(replay->key, generated_key);
|
||||
|
||||
// Tombstone survives restart and blocks reuse!
|
||||
auto rev = provider.resolve("revokeme");
|
||||
Void::Testing::expect(!rev.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(rev.error()) ==
|
||||
V2ErrorCode::Revoked);
|
||||
auto reuse = provider.shorten({
|
||||
.target_url = "https://example.com/new",
|
||||
.custom_key = "revokeme",
|
||||
});
|
||||
Void::Testing::expect(!reuse.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(reuse.error()) ==
|
||||
V2ErrorCode::Conflict);
|
||||
|
||||
// Quota enforcement rejects insert once quota is exhausted.
|
||||
auto tiny_repo =
|
||||
std::make_shared<StorageLinkRepository>(shared_eng, 32ULL);
|
||||
LocalProvider tight_provider{
|
||||
tiny_repo, lopt, clock,
|
||||
std::make_shared<SecurityRandomBytesPort>()};
|
||||
auto over = tight_provider.shorten(
|
||||
{.target_url = "https://example.com/too-big",
|
||||
.custom_key = "quota1"});
|
||||
Void::Testing::expect(!over.has_value());
|
||||
Void::Testing::expect(v2_error_code_from(over.error()) ==
|
||||
V2ErrorCode::QuotaExceeded);
|
||||
Void::Testing::require(shared_eng->close().has_value());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/TestingMock/Matcher.hpp>
|
||||
#include <Void/TestingMock/MockFunction.hpp>
|
||||
#include <Void/TestingMock/Session.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct NonDefaultResult {
|
||||
int value;
|
||||
explicit NonDefaultResult(int v) : value(v) {}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test testing_mock_session_reentrant_move_only_and_sequences()
|
||||
{
|
||||
using namespace Void::TestingMock;
|
||||
|
||||
MockSession session;
|
||||
Sequence seq;
|
||||
|
||||
// 1. Same-thread reentrant mock action works because actions run outside
|
||||
// internal locks.
|
||||
MockFunction<int(int)> reentrant{session, "reentrant"};
|
||||
auto e1 = reentrant.try_expect(Eq(1));
|
||||
Void::Testing::require(e1.has_value());
|
||||
(*e1)->in_sequence(seq).invokes([&](int) -> int { return reentrant(2) + 1; });
|
||||
|
||||
auto e2 = reentrant.try_expect(Eq(2));
|
||||
Void::Testing::require(e2.has_value());
|
||||
(*e2)->in_sequence(seq).returns(41);
|
||||
|
||||
// 2. Move-only argument and move-only return value via returns_once /
|
||||
// invokes_once.
|
||||
MockFunction<std::unique_ptr<int>(std::unique_ptr<int>)> move_fn{session,
|
||||
"move_fn"};
|
||||
auto me1 = move_fn.try_expect(NotNull<std::unique_ptr<int>>());
|
||||
Void::Testing::require(me1.has_value());
|
||||
(*me1)->invokes_once([bonus = std::make_unique<int>(100)](
|
||||
std::unique_ptr<int> in) {
|
||||
return std::make_unique<int>(*in + *bonus);
|
||||
});
|
||||
|
||||
auto me2 = move_fn.try_expect(IsNull<std::unique_ptr<int>>());
|
||||
Void::Testing::require(me2.has_value());
|
||||
(*me2)->returns_once(std::make_unique<int>(7));
|
||||
|
||||
// 3. Matcher combinators: AllOf, AnyOf, NotOf, Ne, EndsWith.
|
||||
MockFunction<int(std::string)> combo{session, "combo"};
|
||||
auto ce = combo.try_expect(AllOf<std::string>(
|
||||
StartsWith<std::string>("pre_"), EndsWith<std::string>("_suf"),
|
||||
NotOf(Eq<std::string>("pre_bad_suf"))));
|
||||
Void::Testing::require(ce.has_value());
|
||||
(*ce)->returns(99).at_least(1);
|
||||
|
||||
// Freeze session in SingleThread mode.
|
||||
Void::Testing::require(freeze(session, Concurrency::SingleThread).has_value());
|
||||
|
||||
// Mutating a frozen session returns InvalidState.
|
||||
auto frozen_add = reentrant.try_expect(Eq(999));
|
||||
Void::Testing::expect(!frozen_add.has_value());
|
||||
|
||||
// Execute reentrant sequenced calls.
|
||||
Void::Testing::expect_eq(reentrant(1), 42);
|
||||
|
||||
// Execute move-only calls.
|
||||
auto r1 = move_fn(std::make_unique<int>(23));
|
||||
Void::Testing::require(r1 != nullptr);
|
||||
Void::Testing::expect_eq(*r1, 123);
|
||||
auto r2 = move_fn(nullptr);
|
||||
Void::Testing::require(r2 != nullptr);
|
||||
Void::Testing::expect_eq(*r2, 7);
|
||||
|
||||
// Execute combinator match.
|
||||
Void::Testing::expect_eq(combo("pre_ok_suf"), 99);
|
||||
|
||||
// verify_and_close() is idempotent and succeeds.
|
||||
auto v1 = verify_and_close(session);
|
||||
Void::Testing::require(v1.has_value());
|
||||
Void::Testing::expect(v1->ok());
|
||||
auto v2 = verify_and_close(session);
|
||||
Void::Testing::require(v2.has_value());
|
||||
Void::Testing::expect(v2->ok());
|
||||
}
|
||||
|
||||
Void::Testing::Test testing_mock_prohibited_never_non_default_and_deadlock_check()
|
||||
{
|
||||
using namespace Void::TestingMock;
|
||||
|
||||
MockSession session;
|
||||
MockFunction<NonDefaultResult(int)> fn{session, "strict_fn"};
|
||||
|
||||
// Explicit never() checked before ordinary wildcard matcher.
|
||||
auto p = fn.try_expect(Eq(13));
|
||||
Void::Testing::require(p.has_value());
|
||||
(*p)->never();
|
||||
|
||||
auto ok = fn.try_expect(_<int>());
|
||||
Void::Testing::require(ok.has_value());
|
||||
(*ok)->invokes([&](int x) -> NonDefaultResult {
|
||||
// Calling verify_and_close from inside an active action must return
|
||||
// WouldDeadlock instead of deadlocking.
|
||||
auto dl = verify_and_close(session);
|
||||
Void::Testing::expect(!dl.has_value());
|
||||
return NonDefaultResult{x * 2};
|
||||
}).times(1);
|
||||
|
||||
Void::Testing::require(freeze(session, Concurrency::SingleThread).has_value());
|
||||
|
||||
auto res = fn(5);
|
||||
Void::Testing::expect_eq(res.value, 10);
|
||||
|
||||
// Prohibited call with non-default-constructible return type records
|
||||
// prohibited failure and throws InvocationAbortException.
|
||||
bool aborted = false;
|
||||
try {
|
||||
(void)fn(13);
|
||||
} catch (const InvocationAbortException&) {
|
||||
aborted = true;
|
||||
}
|
||||
Void::Testing::expect(aborted);
|
||||
|
||||
auto report = verify_and_close(session);
|
||||
Void::Testing::require(report.has_value());
|
||||
Void::Testing::expect(!report->ok());
|
||||
Void::Testing::expect(!report->prohibited.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test testing_mock_concurrent_actions_and_bounds()
|
||||
{
|
||||
using namespace Void::TestingMock;
|
||||
|
||||
MockLimits lim;
|
||||
lim.max_expectations = 4;
|
||||
lim.max_events = 8;
|
||||
MockSession session{lim};
|
||||
|
||||
MockFunction<int(int)> fn{session, "concurrent_fn"};
|
||||
// Two separate expectations with 8 calls each, contested by 4 threads.
|
||||
auto e1 = fn.try_expect(Lt(100));
|
||||
auto e2 = fn.try_expect(Lt(100));
|
||||
Void::Testing::require(e1.has_value());
|
||||
Void::Testing::require(e2.has_value());
|
||||
(*e1)->invokes([](int x) { return x + 1; }).times(8);
|
||||
(*e2)->invokes([](int x) { return x + 2; }).times(8);
|
||||
|
||||
// Enforce max_expectations = 4.
|
||||
auto e3 = fn.try_expect(Eq(200));
|
||||
auto e4 = fn.try_expect(Eq(201));
|
||||
auto e5 = fn.try_expect(Eq(202));
|
||||
Void::Testing::require(e3.has_value());
|
||||
Void::Testing::require(e4.has_value());
|
||||
Void::Testing::expect(!e5.has_value());
|
||||
(*e3)->at_most(1);
|
||||
(*e4)->at_most(1);
|
||||
|
||||
Void::Testing::require(
|
||||
freeze(session, Concurrency::ConcurrentActions).has_value());
|
||||
|
||||
std::atomic<int> sum{0};
|
||||
std::vector<std::thread> threads;
|
||||
for (int t = 0; t < 4; ++t) {
|
||||
threads.emplace_back([&]() {
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
sum.fetch_add(fn(10), std::memory_order_relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& th : threads) {
|
||||
th.join();
|
||||
}
|
||||
|
||||
// 8 * 11 + 8 * 12 = 184
|
||||
Void::Testing::expect_eq(sum.load(), 184);
|
||||
|
||||
auto report = verify_and_close(session);
|
||||
Void::Testing::require(report.has_value());
|
||||
Void::Testing::expect(report->ok());
|
||||
Void::Testing::expect_eq(report->total_events, std::uint64_t{16});
|
||||
Void::Testing::expect(report->events_truncated);
|
||||
Void::Testing::expect(report->events.size() <= lim.max_events);
|
||||
}
|
||||
|
||||
Void::Testing::Test testing_mock_single_thread_detects_wrong_thread_and_matcher_exception()
|
||||
{
|
||||
using namespace Void::TestingMock;
|
||||
|
||||
MockSession session;
|
||||
MockFunction<int(int)> fn{session, "st_fn"};
|
||||
auto e = fn.try_expect(Pred<int>([](const int& v) -> bool {
|
||||
if (v < 0) {
|
||||
throw std::runtime_error("boom-matcher");
|
||||
}
|
||||
return v == 1;
|
||||
}));
|
||||
Void::Testing::require(e.has_value());
|
||||
(*e)->returns(7).at_most(1);
|
||||
|
||||
Void::Testing::require(freeze(session, Concurrency::SingleThread).has_value());
|
||||
|
||||
// Throwing matcher becomes MatcherFailure instead of crashing/aborting.
|
||||
(void)fn(-5);
|
||||
|
||||
// Wrong-thread call under Concurrency::SingleThread records threading error.
|
||||
std::thread other([&]() { (void)fn(1); });
|
||||
other.join();
|
||||
|
||||
auto report = verify_and_close(session);
|
||||
Void::Testing::require(report.has_value());
|
||||
Void::Testing::expect(!report->ok());
|
||||
Void::Testing::expect(!report->matcher_errors.empty());
|
||||
Void::Testing::expect(!report->threading_errors.empty());
|
||||
}
|
||||
Reference in new issue
Block a user