Author SHA1 Message Date
faumaray 549c7cfccb Text: bounded CommonMark-subset Markdown parser and safe HTML renderer
Add Void/Text/Markdown.hpp: a bounded CommonMark-subset parser with a safe
HTML renderer. Raw HTML is always escaped, link/image destinations are
allow-listed (http, https, mailto or relative), and unsafe schemes such as
javascript: and data: are dropped, including entity-smuggled variants.
Add html_escape to Void/Text/Html.hpp.

Closes #58
2026-12-04 13:29:25 +03:00
faumaray 1f98938061 DistributedApplications: multi-process acceptance with durable voter agents, kill/restart histories and acknowledged-write checks 2026-12-04 10:51:46 +03:00
faumaray b9dc055baa docs: record Applications-stack workload baseline 2026-12-04 10:48:30 +03:00
faumaray b70306fb3a DistributedApplications: workload baseline for replicated KV, queue and HTTP fixture with percentiles and confidence intervals (PERFORMANCE.md) 2026-12-04 10:48:26 +03:00
faumaray d5a2c9e718 docs: record Applications-stack example ASan/UBSan/TSan verification 2026-12-04 10:46:50 +03:00
faumaray 91e7a90213 DistributedApplications: queue workflow over the three-listener fixture with crash/partition histories (P-DISTRIBUTED-05 integration) 2026-12-04 10:44:34 +03:00
faumaray 57ebf3130b NetworkedApplications: Discovery-backed service directory with partition policy and optional registration (P-NETWORKED-08) 2026-12-04 10:42:44 +03:00
faumaray 504f259d02 DistributedApplications: range movement with freeze/verify/crash recovery and replicated directory persistence (P-DISTRIBUTED-07) 2026-12-04 10:40:09 +03:00
faumaray cdc55a594e DistributedApplications: backup/restore with identity retention, overlapping trust rotation and mixed-version rollout gates (P-DISTRIBUTED-06) 2026-12-04 10:38:10 +03:00
faumaray b386140899 DistributedApplications: replicated worker queue with inbox/outbox dedup, at-least-once retry, DLQ and consumer recovery (P-DISTRIBUTED-05) 2026-12-04 10:37:05 +03:00
faumaray 23a899a892 DistributedApplications: three-node networked KV fixture with quorum reads, durable replies and crash histories (P-DISTRIBUTED-04) 2026-12-04 10:34:33 +03:00
faumaray cfa860f944 DistributedApplications: deterministic replicated KV core with quorum commits, quorum reads and crash/partition histories (P-DISTRIBUTED-04 foundation) 2026-12-04 10:32:28 +03:00
faumaray 9ba4738415 ReloadableApplications: supervised out-of-process provider with bounded restart policy and explicit unknown effects (P-RELOADABLE-06) 2026-12-04 10:30:15 +03:00
faumaray aad91c7d01 NetworkedApplications: durable-job reference composition over Messaging with Scheduler-driven maintenance (P-NETWORKED-07) 2026-12-04 10:28:06 +03:00
faumaray 21b1c8422d NetworkedApplications: protocol/overload matrix with bounded timeouts and header limits (P-NETWORKED-06) 2026-12-04 10:26:09 +03:00
faumaray 2da3971760 ReloadableApplications: retained-resource ledger and failure-injection matrix; reject publish after failed drain (P-RELOADABLE-05) 2026-12-04 10:24:12 +03:00
faumaray 2489098478 DistributedApplications: single-node reference composition with authenticated peer fixture (P-DISTRIBUTED-03) 2026-12-04 10:21:43 +03:00
faumaray 1fec965c68 DistributedApplications: host graph composition with dependency-ordered lifecycle and readiness (P-DISTRIBUTED-02) 2026-12-04 10:19:19 +03:00
faumaray 0f1cf89cfc NetworkedApplications: auth-scoped operation outcome lookup endpoint (P-NETWORKED-03) 2026-12-04 10:17:19 +03:00
faumaray 50595bdabc ReloadableApplications: durable activation journal, crash recovery and read-only health window (P-RELOADABLE-04) 2026-12-04 10:15:38 +03:00
faumaray 03542d0d2f NetworkedApplications: live config generations and durable backup/restore (P-NETWORKED-05) 2026-12-04 10:13:31 +03:00
faumaray 3010b8a913 Text: add ICU-style message formatting, plural rules and catalog (#56) 2026-12-04 10:04:14 +03:00
faumaray 55a1399e01 Net: expose peer/client addresses and trusted-proxy policy on ServerRequest (#57) 2026-12-04 10:04:14 +03:00
faumaray b3c1246291 Log: color console output by default (NO_COLOR opt-out) 2026-12-04 08:20:14 +03:00
faumaray 3ce62c9cbd tests: cover colored Argparse help and NO_COLOR opt-out 2026-12-04 08:06:21 +03:00
faumaray 5e70ad2bc4 Argparse: colored help output by default (NO_COLOR aware) 2026-12-04 08:01:19 +03:00
faumaray b8e6e924a8 Merge issue-54-gzip: streaming gzip/deflate codec (closes #54) 2026-12-04 07:37:10 +03:00
faumaray ed4beba6e0 Text: streaming gzip/deflate inflate and stored-block deflate (closes #54) 2026-12-04 07:36:18 +03:00
faumaray 4a820748dd Net: pinned resolver callback and cancellation for HttpClient::send (closes #55) 2026-12-04 06:10:43 +03:00
faumaray 5c5fe96f11 Argparse: implement value_name/alias/hide accessors 2026-12-04 05:55:16 +03:00
faumaray 17a23bf88a Text: add checked patch apply and unified rendering (M-TEXT-06) 2026-12-04 05:38:16 +03:00
faumaray 48e5e223af Testing: add bounded fault-file plan port (M-TESTING-06) 2026-12-04 02:21:23 +03:00
faumaray 4b2bc8b25f Observability: bounded tail sampling with explicit eviction (S-OBSERVABILITY-06) 2026-12-04 02:14:32 +03:00
faumaray cc41e5b1d9 Observability: W3C traceparent/tracestate/baggage propagation (S-OBSERVABILITY-05) 2026-12-04 02:09:21 +03:00
faumaray 404bf4ce2f Testing: add subprocess resource limits (M-TESTING-05) 2026-12-04 02:03:24 +03:00
faumaray 80e6ed9afc Testing: add bounded corpus runner (M-TESTING-05) 2026-12-04 01:56:34 +03:00
faumaray d338305cc7 Testing: add composable property generators with shrinking (M-TESTING-04) 2026-12-04 01:52:27 +03:00
faumaray e40e2ca715 Argparse: add value_name, alias and hide customization 2026-12-04 01:40:25 +03:00
faumaray 3990c77155 Testing: add --shard i/n for CI splits 2026-12-04 01:29:53 +03:00
faumaray 546628c5b9 Argparse: derive optional and repeated numeric/enum fields 2026-12-04 01:24:18 +03:00
faumaray 4c0ebc76be Testing: add --fail-fast for sequential runs 2026-12-04 01:15:29 +03:00
faumaray 28e253b49c Argparse: derive enum option fields with possible values 2026-12-04 01:08:30 +03:00
faumaray 520849f82e Argparse: derive numeric option fields (int, unsigned, double) with strict validation 2026-12-04 01:02:06 +03:00
faumaray 1bd729147f Merge relapp-checkpoint: versioned checkpoint migration 2026-12-04 00:51:30 +03:00
faumaray 41e8c9c6ab ReloadableApplications: versioned checkpoint migration 2026-12-04 00:51:26 +03:00
faumaray b20425ded9 Merge cli-rich: Testing parallel auto and richer reporter 2026-12-04 00:48:13 +03:00
faumaray 7f861fa78f Testing: parallel auto mode, aligned timings and slowest/failure summaries 2026-12-04 00:48:10 +03:00
faumaray 96c5ddcb0c Merge cli-rich: richer Clap-like Argparse 2026-12-04 00:44:14 +03:00
faumaray af8757080f Argparse: richer Clap-like CLI (version, counts, checked values, required/conflicts/env, combined shorts, typo hints, aligned help) 2026-12-04 00:44:10 +03:00
faumaray d73a34d622 Merge issue-53-hasher: Hasher state export/import (closes #53) 2026-12-04 00:27:30 +03:00
faumaray 7d6834979e Crypto: Hasher state export/import for the built-in backend (closes #53) 2026-12-04 00:27:26 +03:00
faumaray 06e5bd5693 Merge issue-53-fileport: FilePort no-replace rename, hard link and free space (refs #53) 2026-12-04 00:19:24 +03:00
faumaray 217b20e37a Storage: add no-replace rename, hard link and free-space query to FilePort (refs #53) 2026-12-04 00:19:21 +03:00
faumaray ac30650266 Merge relapp-control: authenticated control endpoint 2026-12-03 23:53:33 +03:00
faumaray 30ba0159ee ReloadableApplications: authenticated bounded control endpoint 2026-12-03 23:53:31 +03:00
faumaray 92b30d2b14 Merge netapp-storage-wiring: durable SQLite profile selection 2026-12-03 20:49:05 +03:00
faumaray e6aec57ad8 NetworkedApplications: select the durable SQLite profile via storage_path 2026-12-03 20:48:21 +03:00
faumaray 686f73ec9d Merge relapp-releases: pinned release generations 2026-12-03 20:44:25 +03:00
faumaray 0f2cab97d5 ReloadableApplications: pinned release generations 2026-12-03 20:44:22 +03:00
faumaray 51bae9bfdf Merge netapp-kv-sqlite: SQLite-backed KV profile 2026-12-03 20:42:12 +03:00
faumaray c21dbf5c93 NetworkedApplications: SQLite-backed KV profile 2026-12-03 20:41:19 +03:00
faumaray 61582ea461 Merge netapp-admin-listener: separate administrative listener 2026-12-03 20:35:22 +03:00
faumaray c6d4a44394 NetworkedApplications: separate administrative listener 2026-12-03 20:35:19 +03:00
faumaray 6b9ccc5e9a Merge relapp-core: reload transaction and quiescence core 2026-12-03 20:32:20 +03:00
faumaray f9eeb34369 ReloadableApplications: reload transaction and quiescence core 2026-12-03 20:32:17 +03:00
faumaray 1f137f101d Merge netapp-kv-listener: Net HTTP listener wiring (NetworkedApplications) 2026-12-03 20:29:12 +03:00
faumaray 183b8033fd NetworkedApplications: serve KvApi behind a real Net HTTP listener 2026-12-03 20:29:09 +03:00
faumaray fd763e4feb Merge netapp-kv-http: HTTP application layer (NetworkedApplications) 2026-12-03 20:24:08 +03:00
faumaray 11fea2566a NetworkedApplications: HTTP application layer with auth and admin views 2026-12-03 20:23:22 +03:00
faumaray 0ef4e3b9ac Merge netapp-kv-domain: versioned KV domain (NetworkedApplications) 2026-12-03 20:19:27 +03:00
faumaray 3253b8b4d4 NetworkedApplications: versioned KV domain with idempotent outcomes 2026-12-03 20:19:25 +03:00
faumaray a2a0e1a4c3 Merge netapp-kv-manual: NetworkedApplications composition skeleton 2026-12-03 20:16:08 +03:00
faumaray 808b6d73df NetworkedApplications: networked-kv composition skeleton 2026-12-03 20:16:05 +03:00
faumaray a4c0bee501 Merge s-rpc-05-host: host adapter boundary (S-RPC-05) 2026-12-03 20:10:13 +03:00
faumaray c6c0303ef8 RPC: host adapter boundary for embedded and managed modes (S-RPC-05) 2026-12-03 20:10:11 +03:00
faumaray 1f92dd054e Merge s-rpc-05-version: Wire version negotiation and migration (S-RPC-05) 2026-12-03 20:03:20 +03:00
faumaray 9ab482dc5d RPC: Wire version negotiation and envelope migration (S-RPC-05) 2026-12-03 20:03:18 +03:00
faumaray 2c026ea30c Merge s-rpc-05-observations: bounded RPC observation sink (S-RPC-05) 2026-12-03 19:58:22 +03:00
faumaray dec48426ae RPC: bounded observation sink for hosts (S-RPC-05) 2026-12-03 19:58:20 +03:00
faumaray 3f71bfdd4a docs: mark VL-SQLITE-01/02/03/04 and VL-SEC-01 verified 2026-12-03 19:54:11 +03:00
faumaray a26ba70e48 Merge s-rpc-04: bounded RPC streaming (S-RPC-04) 2026-12-03 19:51:10 +03:00
faumaray 310fea8d7b RPC: bounded streaming with credit, half-close and cancellation (S-RPC-04) 2026-12-03 19:50:29 +03:00
faumaray 2532485b38 Merge vl-sqlite-03-manual: per-connection fault guard (VL-SQLITE-03) 2026-12-03 18:34:21 +03:00
faumaray 3b1ef4b028 Sqlite: per-connection phase-targetable fault guard (VL-SQLITE-03) 2026-12-03 18:34:19 +03:00
faumaray 103523f04a Merge vl-sqlite-02: unknown commit outcome after WAL I/O error (VL-SQLITE-02) 2026-12-03 18:25:05 +03:00
faumaray a1308a41f8 Merge vl-sqlite-04-manual: scoped busy-timeout override (VL-SQLITE-04) 2026-12-03 18:22:28 +03:00
faumaray 7e5cf7379a Sqlite: add a scoped per-call busy-timeout override (VL-SQLITE-04) 2026-12-03 18:22:26 +03:00
faumaray 7eaa96f9da Sqlite: report unknown commit outcome after WAL I/O error (VL-SQLITE-02)
- Add TransactionState::Unknown: a failed COMMIT whose outcome cannot be
  proven (WAL I/O error after the commit record may be durable) is never
  reported as RolledBack.
- Keep the transaction Active when SQLite leaves it open after the error;
  reject commit/rollback on an Unknown transaction with a clear error.
- Extend the fault guard with commit_applied_before_error to model a lost
  commit acknowledgement, and cover Unknown, Active-retry and
  rollback-journal RolledBack paths.
2026-12-03 18:17:17 +03:00
faumaray 797ea630a1 Merge vl-sqlite-01-manual: structural SQLite result codes (VL-SQLITE-01) 2026-12-03 18:15:30 +03:00
faumaray 0e8ee1848d Sqlite: expose native primary/extended result codes structurally (VL-SQLITE-01) 2026-12-03 18:15:26 +03:00
faumaray a29c9475f2 Merge vl-sec-01-manual: public CSPRNG bytes API (VL-SEC-01) 2026-12-03 18:10:21 +03:00
faumaray 54d143be93 Security: add a public CSPRNG bytes API (VL-SEC-01) 2026-12-03 18:10:18 +03:00
faumaray 0002e74a7d Merge issue-38-targets: Windows select backend foundation and Alpine/musl test qualification 2026-12-03 17:59:21 +03:00
faumaray 0751a4155b Merge issue-52-ed25519-manual: built-in Ed25519 backend (closes #52) 2026-12-03 17:58:18 +03:00
faumaray 86cb94c844 Crypto: add a built-in Ed25519 backend (closes #52) 2026-12-03 17:58:13 +03:00
faumaray f8c62c9851 Build: qualify Alpine/musl test suite (refs #38) 2026-12-03 17:51:20 +03:00
faumaray 7d25251e21 IO: add Windows select backend foundation (refs #38) 2026-12-03 17:49:09 +03:00
faumaray 06641947bd Merge issue-38-targets: wasm test-suite qualification 2026-12-03 17:43:23 +03:00
faumaray f0820b778f Build: qualify wasm test suite with portable libc++ fallbacks (refs #38) 2026-12-03 17:43:14 +03:00
faumaray 62df9b3d7f Merge issue-38-targets: Alpine/musl, wasm and reflection-gated qualification 2026-12-03 17:39:30 +03:00
faumaray 92d60231e5 tests: fix warnings exposed by -Werror and a non-recursive Storage copy 2026-12-03 17:37:14 +03:00
faumaray 2c8d853af0 Net: consume read/write/send results in the HTTP server (VL-NET-W01) 2026-12-03 17:37:14 +03:00
faumaray 1ba60d5d6a Build: gate reflection-only tests on VOID_HAS_CXX26_REFLECTION (refs #38) 2026-12-03 17:29:04 +03:00
faumaray b1933d9906 Build: qualify wasm library subset with Emscripten (refs #38) 2026-12-03 17:18:29 +03:00
faumaray 9f8c56a7ee Build: qualify Alpine/musl target support (refs #38) 2026-12-03 17:16:29 +03:00
faumaray 08a40ad5fc Merge issue-38-targets follow-up: Windows runtime qualification and MinGW portability 2026-12-03 17:10:16 +03:00
faumaray 35774f18cc docs: mark X-QA-01..04 verified in the roadmap task board 2026-12-03 17:08:21 +03:00
faumaray 5d4589056a Build: qualify Windows runtime and fix MinGW portability (refs #38) 2026-12-03 17:07:16 +03:00
faumaray df4103700e Merge xqa-03-scanner: discover wrapped test declarations (X-QA-03) 2026-12-03 17:05:33 +03:00
faumaray 4bc8a7c59b cmake: discover wrapped test declarations in the scanner (X-QA-03) 2026-12-03 17:04:20 +03:00
faumaray 898968d7c6 TestingMock: reset failure tally when clearing captured assertions (X-QA-02) 2026-12-03 17:03:35 +03:00
faumaray 6e636d23e3 Merge issue-45-mcp: MCP protocol and transport foundations (closes #45) 2026-12-03 16:58:25 +03:00
faumaray 77a2bce73f cmake: apply -Werror to generated test TUs and fix exposed warnings (X-QA-01) 2026-12-03 16:57:22 +03:00
faumaray 32569bbfef MCP: add reusable protocol and transport foundations (closes #45) 2026-12-03 16:55:20 +03:00
faumaray 65185f251c Async: cover retry stop interleavings and classifier failures (X-QA-04) 2026-12-03 16:50:03 +03:00
faumaray fe231b0149 Merge issue-38-targets: qualify target support (closes #38) 2026-12-03 16:44:26 +03:00
faumaray 1335fa86c3 Build: qualify target support (closes #38) 2026-12-03 16:43:25 +03:00
faumaray 2501c4d7ac Merge xqa-02-runner-count: count failures independently of retention (X-QA-02) 2026-12-03 16:42:31 +03:00
faumaray 430deab07a Testing: count failures independently of assertion retention (X-QA-02) 2026-12-03 16:41:16 +03:00
faumaray 7b3258a450 cmake: ignore comments and EXCLUDE_SOURCES in module dependency parsing 2026-12-03 16:41:08 +03:00
faumaray d51dd171ef Merge issue-48-tls-smtp: TLS client stream and SMTP submission (closes #48) 2026-12-03 16:39:02 +03:00
faumaray 44686a4444 Net: add TLS client stream and SMTP submission (closes #48) 2026-12-03 16:37:13 +03:00
faumaray f158d7b1cc Text: add Void::Text base32 encode/decode facade (closes #49) 2026-12-03 16:33:06 +03:00
faumaray 62c2082fb3 Merge issue-40-windows-process: Windows process and handle support (closes #40) 2026-12-03 16:11:40 +03:00
faumaray 29b46839fd System: Windows process and handle support for the runner subset (closes #40) 2026-12-03 16:11:23 +03:00
faumaray 72148da7b2 Merge issue-37-duplex-http: duplex HTTP response streaming (closes #37) 2026-12-03 16:03:51 +03:00
faumaray a6dd7fd927 Net: add duplex HTTP response streaming (closes #37) 2026-12-03 16:03:31 +03:00
faumaray 7cfd30e550 Merge issue-44-binary-session: binary subprocess session (closes #44) 2026-12-03 15:51:05 +03:00
faumaray 9b773a4553 Merge issue-41-hmac-pbkdf2: HMAC-SHA1 and PBKDF2-HMAC-SHA256 (closes #41) 2026-12-03 15:51:04 +03:00
faumaray 540c3d9117 System: add binary subprocess session (#44) 2026-12-03 15:50:28 +03:00
faumaray 74bd01aac5 Crypto: add HMAC-SHA1 and PBKDF2-HMAC-SHA256 (#41) 2026-12-03 15:50:15 +03:00
faumaray a14d063598 Merge issue-46-toml-limits: TOML parser limits (closes #46) 2026-12-03 15:49:39 +03:00
faumaray a535f352d6 Merge issue-47-sqlite-wal: WAL frame admission and rollback reporting (closes #47) 2026-12-03 15:49:27 +03:00
faumaray 9ccfbf7838 Data: qualify TOML parser limits (#46) 2026-12-03 15:49:25 +03:00
faumaray 963aface67 Merge issue-39-lua-adapter: bounded Lua adapter (closes #39) 2026-12-03 15:48:32 +03:00
faumaray a40882522a Sqlite: WAL frame admission and automatic rollback reporting (#47) 2026-12-03 15:48:31 +03:00
faumaray ae7bedb755 Script: add optional bounded Lua runtime adapter (#39) 2026-12-03 15:47:39 +03:00
faumaray be8dd73607 Merge issue-42-bounded-diff: bounded diff APIs (#42) 2026-12-03 15:46:43 +03:00
faumaray 4ad13ce94f Text: add bounded diff APIs (#42) 2026-12-03 15:46:30 +03:00
faumaray f146df97f4 Merge issue-36-ed25519: Ed25519 sign/verify (#36) 2026-12-03 15:46:14 +03:00
faumaray f5842b97c8 Crypto: add Ed25519 sign/verify (#36) 2026-12-03 15:46:05 +03:00
faumaray add599917c Merge issue-43-base32: Text base32 codecs (#43) 2026-12-03 15:44:26 +03:00
faumaray 2eb3bd230a Text: add base32 codecs (#43) 2026-12-03 15:44:14 +03:00
faumaray b3c566ed4d Merge pull request 'Build containers, toolchains and portability fixes' (#35) from chore/toolchains-and-portability into main 2026-12-03 08:10:30 +00:00
faumaray d5cfd9cd7a chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:22 +00:00
faumaray aebc38791a chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:18 +00:00
faumaray c8f0113d48 chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:14 +00:00
faumaray 12ba8d8e2c chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:10 +00:00
faumaray 496d9fc582 chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:07 +00:00
faumaray 5a74233a4d chore(build): containers, toolchains and portability fixes 2026-12-03 08:10:02 +00:00
faumaray 774df0fd1e chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:58 +00:00
faumaray f8e183b7ab chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:54 +00:00
faumaray 216a14e6fa chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:52 +00:00
faumaray 7686be1b23 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:47 +00:00
faumaray 71fcad80d3 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:44 +00:00
faumaray 905e44635e chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:42 +00:00
faumaray 5d5a8bf345 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:40 +00:00
faumaray fe6e2124ad chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:36 +00:00
faumaray f9bde1d19f chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:34 +00:00
faumaray 65595362e2 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:32 +00:00
faumaray 43d94e2837 chore(build): containers, toolchains and portability fixes 2026-12-03 08:09:30 +00:00
faumaray f6002c1996 Merge pull request 'Bounded PCM playback with owned samples and voice lifetimes (#18)' (#34) from issue/18-windows-pcm-playback into main 2026-12-03 08:08:41 +00:00
faumaray 706383e13f Merge pull request 'Bounded Lua evaluator with transactional host results (#17)' (#33) from issue/17-bounded-lua into main 2026-12-03 08:08:39 +00:00
faumaray 81e1d54ac3 Merge pull request 'Bounded admission gated on an exact retained publication (#16)' (#32) from issue/16-publication-gated-queue into main 2026-12-03 08:08:37 +00:00
faumaray f57b508b0a Merge pull request 'Deterministic completion-order helpers (#15)' (#31) from issue/15-completion-observer into main 2026-12-03 08:08:35 +00:00
faumaray b381d682c8 Merge pull request 'Bounded sparse 3D pages with atomic revision-checked batches (#14)' (#30) from issue/14-sparse-page-table into main 2026-12-03 08:08:33 +00:00
faumaray 8c576fdcbf Merge pull request 'Bounded epoch-qualified revision read sets (#13)' (#29) from issue/13-revision-read-set into main 2026-12-03 08:08:31 +00:00
faumaray 63eecc32c7 Merge pull request 'Bounded 3D grid-ray traversal with a documented tie policy (#12)' (#28) from issue/12-grid-ray into main 2026-12-03 08:08:29 +00:00
faumaray 86bde8b172 Merge pull request 'Checked Euclidean division for signed grid coordinates (#11)' (#27) from issue/11-euclidean-division into main 2026-12-03 08:08:26 +00:00
faumaray a0e4bfa941 Merge pull request 'Versioned deterministic random stream state and bounded draws (#10)' (#26) from issue/10-versioned-rng-state into main 2026-12-03 08:08:24 +00:00
faumaray 6c5c2dcd93 Merge pull request 'Atomic reservations and repeatable transfers in an account ledger (#8)' (#24) from issue/8-account-ledger into main 2026-12-03 08:08:22 +00:00
faumaray 86510f99f0 Merge pull request 'Instance-owned restorable id sequences with checked exhaustion (#7)' (#23) from issue/7-restorable-id-sequences into main 2026-12-03 08:08:21 +00:00
faumaray a5f21c6374 Merge pull request 'Epoch-scoped request ledger with conflicting-retry detection (#6)' (#22) from issue/6-request-ledger into main 2026-12-03 08:08:19 +00:00
faumaray 2474292462 Merge pull request 'Immutable snapshot publication with epoch/revision identity (#5)' (#21) from issue/5-immutable-publication into main 2026-12-03 08:08:17 +00:00
faumaray 34cfd9cb39 Merge pull request 'Deterministic package resolver with source diagnostics (#4)' (#20) from issue/4-package-resolver into main 2026-12-03 08:08:15 +00:00
faumaray 72733e2b93 Merge pull request 'Bounded Windows read coverage and sharing documentation (#9)' (#25) from issue/9-windows-bounded-read into main 2026-12-03 08:08:13 +00:00
faumaray dc18d64b18 Merge pull request 'Windows x64 transactional file replacement (#3)' (#19) from issue/3-windows-transactional-replace into main 2026-12-03 08:08:02 +00:00
faumaray caebb7f7f1 feat(System): bounded PCM playback with owned samples and voice lifetimes (#18) 2026-12-03 07:03:09 +00:00
faumaray df2ed107e2 feat(System): bounded PCM playback with owned samples and voice lifetimes (#18) 2026-12-03 07:03:05 +00:00
faumaray e8565c6857 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:57 +00:00
faumaray 2c6e4eab82 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:55 +00:00
faumaray 359e0630c7 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:53 +00:00
faumaray 025d97c6f6 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:50 +00:00
faumaray 08038000cc feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:48 +00:00
faumaray ba49098798 feat(Script): bounded Lua evaluator with transactional host results (#17) 2026-12-03 07:02:45 +00:00
faumaray 60860d167a feat(Async): bounded admission gated on an exact retained publication (#16) 2026-12-03 07:02:35 +00:00
faumaray 5a076cd8f2 feat(Async): bounded admission gated on an exact retained publication (#16) 2026-12-03 07:02:33 +00:00
faumaray 82c3558524 feat(Testing): deterministic completion-order helpers (#15) 2026-12-03 07:02:26 +00:00
faumaray 3953891511 feat(Testing): deterministic completion-order helpers (#15) 2026-12-03 07:02:24 +00:00
faumaray ba3c5a6734 feat(Containers): bounded sparse 3D pages with atomic revision-checked batches (#14) 2026-12-03 06:53:44 +00:00
faumaray 00eefe0521 feat(Containers): bounded sparse 3D pages with atomic revision-checked batches (#14) 2026-12-03 06:53:42 +00:00
faumaray b062e759ba feat(Algorithms): bounded epoch-qualified revision read sets (#13) 2026-12-03 06:53:36 +00:00
faumaray dddcc2b2f0 feat(Algorithms): bounded epoch-qualified revision read sets (#13) 2026-12-03 06:53:34 +00:00
faumaray 7d0ed43f76 feat(Algorithms): bounded 3D grid-ray traversal with a documented tie policy (#12) 2026-12-03 06:53:29 +00:00
faumaray acd4ff40f0 feat(Algorithms): bounded 3D grid-ray traversal with a documented tie policy (#12) 2026-12-03 06:53:27 +00:00
faumaray f100b4c89e feat(Math): checked Euclidean division for signed grid coordinates (#11) 2026-12-03 06:53:21 +00:00
faumaray 4f67fd2b93 feat(Math): checked Euclidean division for signed grid coordinates (#11) 2026-12-03 06:53:17 +00:00
selikhov 2e8afc471b feat(Math): versioned Xoshiro state and portable bounded draws (#10)
- Public, versioned State (algorithm identity "xoshiro256**", schema
  version 1, four words in s0..s3 order) so consumers can define their
  own wire format.
- restore() validates version and rejects the absorbing all-zero state
  without touching the current stream; from_state() builds a generator
  from saved state.
- bounded(n): unbiased rejection sampling in [0, n). Documented
  zero-bound policy: n == 0 and n == 1 return 0 without consuming
  randomness.
- 7 new tests freeze raw/bounded/state outputs for seed 42 (portable
  across targets), verify save/restore suffix equality, invalid-state
  rejection, zero/one bounds, large non-power-of-two ranges,
  independent interleaved streams and discard equivalence.
2026-12-03 09:46:15 +03:00
selikhov f3176c2b54 feat(System): bounded Windows read through one handle, with coverage (#9)
The Windows read_file_bounded path was implemented together with #3 using
a single CreateFileW handle. This adds the #9 acceptance coverage and
documents the contract:

- The size is checked before allocation and every chunk is re-checked, so
  growth after the initial size check still fails with limit_exceeded and
  never returns partial contents.
- Windows shares read/write/delete, so another process may append,
  rename or replace the path while a background read is pending; the
  read continues from the opened handle and sees one coherent version.
- Tests: empty, binary, Unicode path, exact limit, over limit before
  reading, and (POSIX) a stream that grows past the limit mid-read.
2026-12-03 09:45:14 +03:00
selikhov a4851c2c20 feat(Containers): restorable account ledger with atomic reservations (#8)
- AccountLedger: caller-keyed accounts (owner, balance, capacity) with
  atomic multi-account reserve, release without ownership change and
  transfer to the destination (next) owner.
- Explicit outcomes for insufficient balance, capacity exhaustion,
  overflow, unknown account/operation, invalid phase and limits.
- Every committed phase is recorded by operation id, so repeated
  requests replay the recorded outcome instead of applying twice;
  failed attempts change nothing and remain retryable.
- State is a plain value: save()/restore() survive a partially completed
  transfer and replay applies exactly once after restore.
- 11 tests: conservation, last-unit contention, atomic multi-key failure,
  cancellation before pickup and during delivery, restore/replay,
  overflow, operation-id conflict, account/operation limits and invalid
  restore state.
2026-12-03 09:44:21 +03:00
selikhov f2b002eb26 feat(Core): instance-owned restorable id sequences with checked exhaustion (#7)
- IdSequence<Tag, Rep> is per-instance, copyable and restorable, so two
  worlds in one process allocate independently and a saved high-water
  mark replays exactly.
- next()/next_batch() check exhaustion before mutating; failed requests
  leave the sequence and application records untouched. Batches are
  all-or-nothing.
- High-water only moves forward: erased records keep their ids retired.
- Fixed-width Rep (default uint64_t) plus an explicit exhausted flag make
  saved state canonical and portable; restore() rejects impossible state.
- 10 standalone tests cover independence, erase/restore, copy replay,
  atomic batches, exhaustion, final-boundary batches and invalid state.
2026-12-03 09:41:50 +03:00
selikhov afd4d99a2d feat(Messaging): epoch-scoped request ledger with conflict detection (#6)
- RequestLedger<Payload, Result, PayloadEqual> keys idempotent host
  requests by (epoch, trusted client, request id).
- check() admits the first request, replays a recorded result for an
  exact repeat (including a rejected outcome), reports in_progress while
  the request is still running, rejects a changed payload and rejects
  keys from an obsolete/future epoch before side effects.
- record() stores the caller-defined result exactly once; results are
  never overwritten.
- Capacity/admission/archival is explicit: entries are never evicted
  within an epoch (capacity_exceeded instead), and advancing the epoch
  clears memory. An old request number therefore cannot execute a second
  time after cleanup.
- 8 tests: replay, rejected outcome, payload conflict, delayed retry
  after newer operations, epoch rollover, capacity pressure, in-flight
  state/immutable result and non-advancing epoch rejection.
2026-12-03 09:40:47 +03:00
selikhov 37c3cd4383 feat(Core): immutable snapshot publication with epoch/revision identity (#5)
- Publication<T>: single-writer, multi-reader publication of complete
  immutable values. acquire() returns a retainable Snapshot; a retained
  snapshot stays coherent across any number of later publishes and keeps
  the value alive until the last reader releases it.
- publish() is compare-and-publish over one atomic (value + version)
  state: an expected epoch must match, and the new version must advance
  (higher epoch, or same epoch with higher revision). Rejected publishes
  leave the last good publication untouched, so a failed preparation
  cannot corrupt readers.
- publish_next()/publish_epoch() convenience helpers.
- 7 tests: retained snapshots, stale-epoch rejection, non-advancing
  revision, epoch reset, last-reader resource release, failed
  preparation preservation and concurrent reader coherence.
2026-12-03 09:39:56 +03:00
selikhov d30384d981 feat(Update): deterministic package resolver with diagnostics (#4)
- resolve_packages() takes caller-supplied package descriptions (id,
  exact version, content digest, exclusive capabilities, dependency
  ranges) plus selected root ids and returns an exact dependency set.
- Deterministic: canonical input ordering, descending SemVer candidate
  order and canonical requirement order make the result invariant under
  permutation of installed/selected input.
- Frozen PackageIdentity compares build metadata and content digest in
  addition to SemVer precedence, so equal-precedence rebuilds are never
  conflated; ambiguous same-id/same-precedence inputs are rejected.
- Actionable diagnostics carry kind, input package, field
  (e.g. dependencies[1].range) and related id: missing dependency,
  incompatible version, cycle, ambiguity, competing exclusive providers.
- Bounded package/edge/search-node limits with backtracking search.
- 13 standalone tests cover closure, order invariance, diagnostics,
  backtracking, cycles, capabilities, frozen identity and limits.
2026-12-03 09:38:27 +03:00
selikhov 51ceb081ac feat(System): transactional file replacement on Windows x64 (#3)
- replace_file/atomic_write gain a Win32 implementation: exclusive
  CREATE_NEW staging in the destination directory, WriteFile loop,
  FlushFileBuffers for durable_sync, MoveFileExW(MOVEFILE_REPLACE_EXISTING
  [| MOVEFILE_WRITE_THROUGH]) for atomic publication and a parent-directory
  flush for durability.
- read_file_bounded/write_file implemented on Windows so the contract is
  usable and testable there.
- Documented Windows guarantees per durability level, including the
  application-crash vs power-loss distinction and post-rename failure
  reporting (sync_parent + visible_on_disk + durability_unknown).
- Added a portable contract test (first creation, replacement, Unicode
  name, pre-publication faults preserving old contents, post-publication
  fault reporting, no staging leftovers, live destination never deleted)
  and a concurrent-writer atomicity test.
2026-12-03 09:34:50 +03:00
faumaray 7b0fea6095 Merge branch 'feat/roadmap-p2-wave11' (Wave 11 Async, Time, IO, Runtime execution-path completion) 2026-12-01 22:33:50 +03:00
265 changed files with 48631 additions and 593 deletions

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
{
"name": "VoidLibrary (GCC 16, CMake 4, Ninja)",
"build": {
"dockerfile": "../Dockerfile",
"context": ".."
},
"workspaceFolder": "/src",
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
"remoteUser": "root",
"customizations": {
"vscode": {
"extensions": [
"ms-vscode.cpptools",
"ms-vscode.cmake-tools",
"twxs.cmake"
],
"settings": {
"cmake.generator": "Ninja",
"cmake.configureSettings": {
"CMAKE_CXX_COMPILER": "g++-16",
"CMAKE_C_COMPILER": "gcc-16",
"CMAKE_BUILD_TYPE": "Debug"
},
"C_Cpp.default.cppStandard": "c++26"
}
}
},
"postCreateCommand": "cmake --version && g++-16 --version && ninja --version"
}
+64
View File
@@ -0,0 +1,64 @@
# Windows builds: MSYS2 (native) and MinGW-w64 (cross)
## MSYS2 (native Windows, recommended for a full build)
Install the MINGW64 toolchain and the optional libraries used by the modules:
```bash
pacman -S --needed base-devel \
mingw-w64-x86_64-toolchain \
mingw-w64-x86_64-cmake \
mingw-w64-x86_64-ninja \
mingw-w64-x86_64-boost \
mingw-w64-x86_64-openssl \
mingw-w64-x86_64-libsodium \
mingw-w64-x86_64-libarchive \
mingw-w64-x86_64-sqlite3 \
mingw-w64-x86_64-lua
```
Then, from a **MINGW64** shell (not the MSYS shell):
```bash
cmake -B build -S . -G Ninja -DCMAKE_BUILD_TYPE=Debug
cmake --build build
ctest --test-dir build --output-on-failure
```
Notes:
- C++26 reflection requires GCC 16 or newer (`-freflection`). The build
probes for it; on older GCC some reflection-only tests are skipped.
- `Void::IO` currently has a POSIX (epoll) backend only; select the modules
you need with `-DVOID_ENABLED_MODULES=...` if a module is not yet available
on Windows.
- The Windows branches of `Void::System` (paths, bounded reads, audio) are
compiled by this configuration.
## MinGW-w64 cross build (Linux container)
`Dockerfile.mingw` uses the LLVM-MinGW toolchain (Clang + libc++ + the
MinGW-w64 runtime) on top of Ubuntu, together with CMake 4 and Ninja. The
matching devcontainer is in `.devcontainer/mingw/`.
```bash
docker build -f Dockerfile.mingw -t voidlibrary-mingw .
docker run --rm -v "$PWD:/src" -w /src voidlibrary-mingw bash -lc '
cmake -B build-mingw -S . -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
-DCMAKE_BUILD_TYPE=Debug \
-DVOID_ENABLE_TESTING=OFF \
-DVOID_ENABLED_MODULES="Core;Functional;Containers;Math;Text;Algorithms;Unicode;Time;LogState"
cmake --build build-mingw
'
```
Cross-compiling cannot use the host's Boost/OpenSSL/libsodium/libarchive/SQLite/
Lua libraries. Modules that need them (or the POSIX-only IO backend) are
therefore excluded from a cross build; use MSYS2 on Windows for those.
- The toolchain file accepts GCC- or Clang-based MinGW prefixes and picks
whichever compiler exists.
- `CMAKE_CXX_STANDARD` can be pinned for older toolchains
(`-DCMAKE_CXX_STANDARD=23`); the build probes capabilities against the
selected standard.
+28
View File
@@ -0,0 +1,28 @@
{
"name": "VoidLibrary (MinGW-w64 cross build)",
"build": {
"dockerfile": "../../Dockerfile.mingw",
"context": "../.."
},
"workspaceFolder": "/src",
"workspaceMount": "source=${localWorkspaceFolder},target=/src,type=bind",
"remoteUser": "root",
"customizations": {
"vscode": {
"extensions": [
"ms-vscode.cpptools",
"ms-vscode.cmake-tools",
"twxs.cmake"
],
"settings": {
"cmake.generator": "Ninja",
"cmake.configureSettings": {
"CMAKE_TOOLCHAIN_FILE": "cmake/toolchains/mingw-w64.cmake",
"CMAKE_BUILD_TYPE": "Debug"
},
"C_Cpp.default.cppStandard": "c++26"
}
}
},
"postCreateCommand": "cmake --version && x86_64-w64-mingw32-g++ --version && ninja --version"
}
+6
View File
@@ -0,0 +1,6 @@
build*
.git
.gitea
.github
.dockerignore
Dockerfile
+30 -4
View File
@@ -14,11 +14,23 @@ option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF)
option(VOID_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (Clang/GCC)" OFF)
option(VOID_ENABLE_TSAN "Enable ThreadSanitizer (Clang/GCC)" OFF)
option(VOID_ENABLE_COVERAGE "Enable code coverage instrumentation" OFF)
option(VOID_SCRIPT_ENABLE_LUA "Build the optional bounded Lua adapter" ON)
option(VOID_FETCH_LUA "Fetch Lua 5.4 when no system package is found" ON)
set(CMAKE_CXX_STANDARD 26)
# C++26 is the default. Cross/toolchain-limited builds (e.g. MinGW-w64
# with an older GCC) may pin a lower standard explicitly.
if(NOT DEFINED CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 26)
endif()
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
if(NOT DEFINED CMAKE_CXX_MODULE_MAP_FORMAT)
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_MODULE_MAP_FORMAT "clang")
else()
set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc")
endif()
endif()
set(CXX_SCAN_FOR_MODULES OFF)
# <Void/Data/Reflect.hpp>, <Void/Configuration/Bind.hpp>, etc.
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
@@ -33,6 +45,7 @@ set(EXPORT_SET_NAME ${PROJECT_NAME}Targets)
include(cmake/Capabilities.cmake)
void_probe_capabilities()
include(cmake/Module.cmake)
include(cmake/Targets.cmake)
# Modules to configure, with the modules they need (INTERNAL_DEPS, followed
# transitively); empty configures every module. OPTIONAL_DEPS are used only
@@ -56,11 +69,14 @@ if(VOID_ENABLED_MODULES)
list(APPEND _void_selected ${_void_module})
if(EXISTS "${_void_module_file}")
file(READ "${_void_module_file}" _void_text)
# The words after INTERNAL_DEPS up to the next keyword or ')'.
# Drop comments so prose between keywords is never parsed as a
# dependency name, then read the words after INTERNAL_DEPS up to
# the next keyword or ')'.
string(REGEX REPLACE "#[^\n]*" "" _void_text "${_void_text}")
if(_void_text MATCHES "INTERNAL_DEPS([^)]*)")
separate_arguments(_void_words UNIX_COMMAND "${CMAKE_MATCH_1}")
foreach(_void_word IN LISTS _void_words)
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS)$")
if(_void_word MATCHES "^(INTERNAL_DEPS|EXTERNAL_DEPS|OPTIONAL_DEPS|DEPS_WIN32|DEPS_UNIX|OPTIONS_WIN32|OPTIONS_UNIX|EXTRA_HEADERS|EXCLUDE_HEADERS|EXCLUDE_SOURCES_WIN32|EXCLUDE_SOURCES_UNIX)$")
break()
endif()
list(APPEND _void_pending ${_void_word})
@@ -71,6 +87,12 @@ if(VOID_ENABLED_MODULES)
endif()
file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/*)
if(_void_selected)
# Fail on unsupported target/module combinations before resolving any
# dependency, so a browser engine requesting native networking gets the
# target message instead of a Boost/OpenSSL one.
void_validate_target_modules(${_void_selected})
endif()
foreach(module_path ${children})
if(_void_selected AND NOT module_path IN_LIST _void_selected)
continue()
@@ -84,6 +106,9 @@ foreach(module_path ${children})
endif()
endforeach()
void_finalize_modules()
void_validate_target_modules()
void_write_target_manifest(
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake")
void_report_capabilities()
if(VOID_ENABLE_TESTING)
@@ -132,6 +157,7 @@ install(EXPORT ${EXPORT_SET_NAME}
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/void-target-manifest.cmake"
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTesting.cmake"
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidTestScanner.cmake"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
+52
View File
@@ -0,0 +1,52 @@
# Development image for VoidLibrary.
#
# Toolchain: GCC 16 (C++26 reflection), CMake 4, Ninja.
# Optional dependencies used by the modules: Boost, OpenSSL, libsodium,
# libarchive, SQLite3 and Lua 5.4.
#
# The image does not copy or build the sources: mount the repository at /src
# (the devcontainer does this) and configure/build there.
FROM ubuntu:24.04
ARG DEBIAN_FRONTEND=noninteractive
ARG GCC_VERSION=16
ARG CMAKE_VERSION=4.2.3
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
build-essential \
ca-certificates \
curl \
git \
gnupg \
ninja-build \
pkg-config \
software-properties-common \
libboost-all-dev \
libssl-dev \
libsodium-dev \
libarchive-dev \
libsqlite3-dev \
liblua5.4-dev \
zlib1g-dev \
&& add-apt-repository -y ppa:ubuntu-toolchain-r/test \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
gcc-${GCC_VERSION} \
g++-${GCC_VERSION} \
&& update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${GCC_VERSION} 100 \
&& update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${GCC_VERSION} 100 \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL -o /tmp/cmake.tar.gz \
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
&& ln -s "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
&& rm /tmp/cmake.tar.gz
WORKDIR /src
CMD ["bash"]
+29
View File
@@ -0,0 +1,29 @@
# MinGW-w64 cross-build environment for VoidLibrary (Windows x64 from Linux).
#
# Uses the LLVM-MinGW toolchain (Clang + libc++ + MinGW-w64 runtime), which is
# new enough for the C++26 features this project uses. Reflection is not
# available on Clang, so the reflection-only tests are skipped exactly as on
# any non-reflecting compiler.
FROM mstorsjo/llvm-mingw:latest
ARG CMAKE_VERSION=4.2.3
# The base image is Ubuntu 24.04 with CMake 3.28; Void requires CMake 4.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl git \
&& rm -rf /var/lib/apt/lists/*
RUN curl -fsSL -o /tmp/cmake.tar.gz \
"https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-x86_64.tar.gz" \
&& tar -xzf /tmp/cmake.tar.gz -C /opt \
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cmake" /usr/local/bin/cmake \
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/ctest" /usr/local/bin/ctest \
&& ln -sf "/opt/cmake-${CMAKE_VERSION}-linux-x86_64/bin/cpack" /usr/local/bin/cpack \
&& rm /tmp/cmake.tar.gz
ENV PATH="/opt/llvm-mingw/bin:${PATH}"
WORKDIR /src
CMD ["bash"]
+13 -1
View File
@@ -48,6 +48,15 @@ ctest --test-dir build-asan
Format code with `clang-format -i <file>`.
## Supported targets
Void is qualified per target profile: Linux (reference), Linux/musl, the
Windows client subset, and a browser/Wasm subset of the pure computation
modules. The profile is detected from the toolchain, validated against the
selected modules, and recorded in `void-target-manifest.cmake`. See
[docs/targets.md](docs/targets.md) for the exact compiler/standard-library
tuples, module allowlists and qualification status.
## Modules
Functionality is grouped into umbrella modules (one CMake target each).
@@ -101,4 +110,7 @@ Tests are free functions or methods on a `Void::Testing::Fixture` subclass
returning `Void::Testing::Test` (or `Void::Testing::DisabledTest`).
Registration is automatic — the CMake test scanner parses each `.cpp` at
configure time and generates the registration shim. Free-function tests can
use `// @tag` and `// @skip` comment metadata.
use `// @tag` and `// @skip` comment metadata. A file whose tests all need
C++26 reflection can declare `// @requires-reflection`; it is skipped when
the compiler lacks the `VOID_HAS_CXX26_REFLECTION` capability, because the
scanner cannot evaluate `#ifdef` guards around test functions.
+6 -4
View File
@@ -33,7 +33,7 @@ function(void_probe_capabilities)
endif()
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
check_cxx_source_compiles(
"#include <expected>\nint main() { std::expected<int, int> e{0}; return *e; }\n"
VOID_HAS_STD_EXPECTED
@@ -46,10 +46,12 @@ function(void_probe_capabilities)
endif()
cmake_push_check_state(RESET)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
set(CMAKE_REQUIRED_FLAGS "-std=c++26 -freflection")
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND
CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16 AND
CMAKE_CXX_STANDARD GREATER_EQUAL 26)
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD} -freflection")
else()
set(CMAKE_REQUIRED_FLAGS "-std=c++26")
set(CMAKE_REQUIRED_FLAGS "-std=c++${CMAKE_CXX_STANDARD}")
endif()
check_cxx_source_compiles(
"#include <meta>\nconsteval bool probe() { constexpr auto r = ^^int; return std::meta::is_type(r); }\nstatic_assert(probe());\nint main() { return 0; }\n"
+41
View File
@@ -265,6 +265,47 @@ function(void_fetch_dependency DEP_NAME)
endif()
return()
endif()
if(DEP_NAME STREQUAL "Lua")
if(TARGET Lua::Lua)
return()
endif()
# Prefer a system Lua 5.4 development package.
find_package(Lua 5.4 QUIET)
if(LUA_FOUND)
add_library(Lua::Lua INTERFACE IMPORTED)
set_property(TARGET Lua::Lua PROPERTY
INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}")
set_property(TARGET Lua::Lua PROPERTY
INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}")
return()
endif()
if(NOT VOID_FETCH_LUA)
message(FATAL_ERROR
"[Void] Lua 5.4 not found and VOID_FETCH_LUA=OFF")
endif()
message(STATUS "[Void] Lua 5.4 not found - falling back to FetchContent")
FetchContent_Declare(Lua
URL https://www.lua.org/ftp/lua-5.4.9.tar.gz
URL_HASH SHA256=2335b6c582a52654f94612bf10d2f4672805d05329aa6568b1d8cd9e5c6fb8e6
SYSTEM
)
FetchContent_MakeAvailable(Lua)
file(GLOB _void_lua_sources "${lua_SOURCE_DIR}/src/*.c")
list(REMOVE_ITEM _void_lua_sources
"${lua_SOURCE_DIR}/src/lua.c"
"${lua_SOURCE_DIR}/src/luac.c")
add_library(void_lua STATIC ${_void_lua_sources})
set_target_properties(void_lua PROPERTIES
POSITION_INDEPENDENT_CODE ON
C_STANDARD 99
SYSTEM TRUE)
target_include_directories(void_lua SYSTEM PUBLIC
"${lua_SOURCE_DIR}/src")
add_library(Lua::Lua ALIAS void_lua)
return()
endif()
# FIXME: Add if needed external
# if(DEP_NAME STREQUAL "glaze")
# if(NOT glaze_POPULATED)
+18 -4
View File
@@ -5,13 +5,27 @@ set_property(GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "")
function(void_add_module MODULE_NAME)
cmake_parse_arguments(ARG "" ""
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS"
"INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS;DEPS_WIN32;DEPS_UNIX;OPTIONS_WIN32;OPTIONS_UNIX;EXTRA_HEADERS;EXCLUDE_HEADERS;EXCLUDE_SOURCES_WIN32;EXCLUDE_SOURCES_UNIX"
${ARGN})
set(TGT ${PROJECT_NAME}_${MODULE_NAME})
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
# Platform-specific source selection: a module may be fully portable at the
# header level while some translation units only build on one platform.
# Exclusions are relative to the module directory so callers do not depend
# on the global source layout.
if(WIN32 AND ARG_EXCLUDE_SOURCES_WIN32)
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_WIN32)
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
endforeach()
endif()
if(NOT WIN32 AND ARG_EXCLUDE_SOURCES_UNIX)
foreach(_excl IN LISTS ARG_EXCLUDE_SOURCES_UNIX)
list(REMOVE_ITEM SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_excl}")
endforeach()
endif()
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp"
"${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.h")
@@ -33,7 +47,7 @@ function(void_add_module MODULE_NAME)
set(LIB_TYPE "INTERFACE")
set(SCOPE "INTERFACE")
add_library(${TGT} INTERFACE)
target_compile_features(${TGT} INTERFACE cxx_std_26)
target_compile_features(${TGT} INTERFACE cxx_std_${CMAKE_CXX_STANDARD})
else()
set(SCOPE "PUBLIC")
if (MODULE_NAME STREQUAL "Testing")
@@ -45,7 +59,7 @@ function(void_add_module MODULE_NAME)
add_library(${TGT})
endif()
target_sources(${TGT} PRIVATE ${SRC})
target_compile_features(${TGT} PUBLIC cxx_std_26)
target_compile_features(${TGT} PUBLIC cxx_std_${CMAKE_CXX_STANDARD})
endif()
get_target_property(_module_target_type ${TGT} TYPE)
if(_module_target_type STREQUAL "SHARED_LIBRARY" OR
@@ -221,7 +235,7 @@ function(void_add_module MODULE_NAME)
endif()
set_target_properties(${TGT} PROPERTIES
CXX_STANDARD 26
CXX_STANDARD ${CMAKE_CXX_STANDARD}
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
EXPORT_NAME ${MODULE_NAME}
+241
View File
@@ -0,0 +1,241 @@
# Target qualification for VoidLibrary.
#
# A "target" is a platform profile with a known compiler/standard-library
# tuple and an explicit set of modules that are expected to work there. The
# profile is detected from the toolchain, can be overridden for
# qualification runs with -DVOID_TARGET=..., and is validated against the
# selected modules so unsupported combinations fail at configure time with a
# useful message instead of deep inside a cross build.
#
# See docs/targets.md for the recorded tuples and their qualification status.
set(VOID_KNOWN_TARGETS linux linux-musl windows wasm)
set(VOID_TARGET "auto" CACHE STRING
"Target profile: auto (detect from the toolchain), ${VOID_KNOWN_TARGETS}")
set_property(CACHE VOID_TARGET PROPERTY STRINGS auto ${VOID_KNOWN_TARGETS})
# Browser/Wasm subset: pure computation modules only. Nothing here performs
# native I/O, spawns processes, loads shared libraries, uses SQLite, or needs
# C++26 reflection. Keep this list fail-closed: a module is added only after
# it has been configured and compiled for wasm32-unknown-emscripten.
# Qualified with Emscripten 6.0.9 (Clang 22, libc++) for configure, build,
# install, consume and run under Node, including the test suite with
# -pthread (see docs/targets.md).
set(VOID_WASM_MODULES
Algorithms
Binary
Containers
Core
Data
Functional
LogState
Math
Memory
Testing
TestingMock
Text
Time
Unicode
)
# Windows client subset: modules qualified with x86_64-w64-mingw32 (MinGW-w64).
# Filled from the cross-build and Wine runtime observations in
# docs/targets.md. IO is deliberately absent: it builds on Windows but its
# native backend is Linux-only (EpollBackend), so only the mock backend works.
set(VOID_WINDOWS_MODULES
Algorithms
Async
Binary
Containers
Core
Data
Discovery
Fsm
Functional
IO
Log
LogState
Math
Memory
Messaging
Observability
ObservabilityHooks
Scheduler
Service
Testing
TestingMock
Text
Time
Unicode
)
function(void_detect_target out_var)
if(NOT VOID_TARGET STREQUAL "auto")
set(${out_var} "${VOID_TARGET}" PARENT_SCOPE)
return()
endif()
if(EMSCRIPTEN OR CMAKE_SYSTEM_NAME STREQUAL "Emscripten")
set(_target wasm)
elseif(WIN32)
set(_target windows)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
execute_process(
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
OUTPUT_VARIABLE _triple
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(_triple MATCHES "musl" OR
CMAKE_C_LIBRARY_ARCHITECTURE MATCHES "musl" OR
CMAKE_C_FLAGS MATCHES "musl")
set(_target linux-musl)
else()
set(_target linux)
endif()
else()
set(_target unsupported)
endif()
set(${out_var} "${_target}" PARENT_SCOPE)
endfunction()
function(_void_target_allowlist target out_var)
if(target STREQUAL "wasm")
set(${out_var} "${VOID_WASM_MODULES}" PARENT_SCOPE)
elseif(target STREQUAL "windows")
set(${out_var} "${VOID_WINDOWS_MODULES}" PARENT_SCOPE)
else()
# Linux and Linux/musl qualify every module: platform-specific code is
# selected inside the module sources.
set(${out_var} "" PARENT_SCOPE)
endif()
endfunction()
# Validate the detected/forced target against a module selection. Called
# from the top-level CMakeLists as soon as the selection is expanded (before
# any module dependency is resolved, so an unsupported browser-engine
# combination fails with the target message, not a missing-package error),
# and again after void_finalize_modules() for the all-modules default.
# With no arguments the configured module list is validated.
function(void_validate_target_modules)
void_detect_target(_target)
if(_target STREQUAL "unsupported")
message(FATAL_ERROR
"[Void] Unsupported target '${CMAKE_SYSTEM_NAME} "
"${CMAKE_SYSTEM_PROCESSOR}'. Known targets: ${VOID_KNOWN_TARGETS}. "
"Pass -DVOID_TARGET=<target> only for a qualification run; "
"see docs/targets.md.")
endif()
if(NOT _target IN_LIST VOID_KNOWN_TARGETS)
message(FATAL_ERROR
"[Void] Unknown VOID_TARGET='${_target}'. Known targets: "
"${VOID_KNOWN_TARGETS}.")
endif()
if(_target STREQUAL "wasm" AND VOID_ENABLE_TSAN)
message(FATAL_ERROR
"[Void] ThreadSanitizer is not supported on the wasm target; "
"run native sanitizer builds separately (docs/targets.md).")
endif()
if(ARGN)
set(_modules ${ARGN})
else()
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
endif()
_void_target_allowlist(${_target} _allowed)
if(_allowed)
set(_rejected "")
foreach(_module IN LISTS _modules)
if(NOT _module IN_LIST _allowed)
list(APPEND _rejected ${_module})
endif()
endforeach()
if(_rejected)
message(FATAL_ERROR
"[Void] Modules not supported on target '${_target}': "
"${_rejected}. Supported modules: ${_allowed}. "
"Select a supported subset with -DVOID_ENABLED_MODULES=... "
"or use a native target (docs/targets.md).")
endif()
endif()
if(NOT DEFINED VOID_TARGET_DETECTED OR
NOT VOID_TARGET_DETECTED STREQUAL _target)
set(VOID_TARGET_DETECTED "${_target}" CACHE INTERNAL
"Detected or forced Void target profile" FORCE)
if(NOT VOID_TARGET STREQUAL "auto")
message(STATUS "[Void] Target forced to '${_target}' by VOID_TARGET")
else()
message(STATUS "[Void] Target: ${_target}")
endif()
endif()
endfunction()
# Record the exact tuple this build was configured with. The manifest is
# installed next to VoidConfig.cmake so consumers can inspect what they got,
# and the qualification fixtures assert on it.
function(void_write_target_manifest path)
get_property(_modules GLOBAL PROPERTY VOID_MODULES)
list(JOIN _modules ";" _modules_value)
if(VOID_HAS_CXX26_REFLECTION)
set(_reflection yes)
else()
set(_reflection no)
endif()
if(VOID_HAS_STD_EXPECTED)
set(_expected yes)
else()
set(_expected no)
endif()
if(BUILD_SHARED_LIBS)
set(_linkage shared)
else()
set(_linkage static)
endif()
set(_sanitizers "")
if(VOID_ENABLE_ASAN)
list(APPEND _sanitizers ASan)
endif()
if(VOID_ENABLE_UBSAN)
list(APPEND _sanitizers UBSan)
endif()
if(VOID_ENABLE_TSAN)
list(APPEND _sanitizers TSan)
endif()
if(NOT _sanitizers)
set(_sanitizers none)
else()
string(REPLACE ";" "+" _sanitizers "${_sanitizers}")
endif()
execute_process(
COMMAND "${CMAKE_C_COMPILER}" -dumpmachine
OUTPUT_VARIABLE _triple
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
set(_content
"# Generated by VoidLibrary's build system (cmake/Targets.cmake).
# Describes the exact target tuple this build was configured with.
set(VOID_TARGET_MANIFEST_TARGET \"${VOID_TARGET_DETECTED}\")
set(VOID_TARGET_MANIFEST_TARGET_ORIGIN \"${VOID_TARGET}\")
set(VOID_TARGET_MANIFEST_TRIPLE \"${_triple}\")
set(VOID_TARGET_MANIFEST_SYSTEM_NAME \"${CMAKE_SYSTEM_NAME}\")
set(VOID_TARGET_MANIFEST_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")
set(VOID_TARGET_MANIFEST_COMPILER_ID \"${CMAKE_CXX_COMPILER_ID}\")
set(VOID_TARGET_MANIFEST_COMPILER_VERSION \"${CMAKE_CXX_COMPILER_VERSION}\")
set(VOID_TARGET_MANIFEST_CXX_STANDARD \"${CMAKE_CXX_STANDARD}\")
set(VOID_TARGET_MANIFEST_LINKAGE \"${_linkage}\")
set(VOID_TARGET_MANIFEST_REFLECTION \"${_reflection}\")
set(VOID_TARGET_MANIFEST_STD_EXPECTED \"${_expected}\")
set(VOID_TARGET_MANIFEST_SANITIZERS \"${_sanitizers}\")
set(VOID_TARGET_MANIFEST_TESTING \"${VOID_ENABLE_TESTING}\")
set(VOID_TARGET_MANIFEST_WARNINGS_AS_ERRORS \"${VOID_WARNINGS_AS_ERRORS}\")
set(VOID_TARGET_MANIFEST_MODULES \"${_modules_value}\")
")
file(WRITE "${path}" "${_content}")
endfunction()
+37 -2
View File
@@ -22,6 +22,15 @@ set(fixture_class_name "")
set(fixture_indent "")
set(line_number 0)
# A Test/DisabledTest declaration may wrap across lines. These patterns let
# the loop join such a declaration into one logical line instead of silently
# dropping it (X-QA-03).
set(_test_decl_regex "(Void::Testing::)?(Test|DisabledTest)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*\\(\\s*\\)")
set(_test_decl_start_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]|$)")
set(_test_decl_partial_regex "^[ \t]*(Void::Testing::)?(Test|DisabledTest)([ \t]+[A-Za-z_][A-Za-z0-9_]*)?[ \t]*\\(?[ \t]*$")
set(pending_decl "")
set(pending_decl_line 0)
# Accumulators for preceding comments
set(current_tags "")
set(current_skip "")
@@ -33,6 +42,32 @@ foreach(line IN LISTS lines)
string(REPLACE "__VOID_SCAN_SC__" ";" line "${line}")
string(REPLACE "__VOID_SCAN_BS__" "\\" line "${line}")
# Join a wrapped test declaration before any other per-line handling so
# tags/skip comments that precede it stay associated with it.
set(registration_line ${line_number})
if(pending_decl)
string(APPEND pending_decl " ${line}")
if(pending_decl MATCHES "${_test_decl_regex}")
# Complete: process the joined declaration as one logical line.
set(line "${pending_decl}")
set(registration_line ${pending_decl_line})
set(pending_decl "")
elseif(pending_decl MATCHES "${_test_decl_partial_regex}")
continue()
else()
# Not a wrapped test declaration after all; handle this line
# normally and drop the accumulated prefix.
set(pending_decl "")
endif()
elseif(line MATCHES "${_test_decl_start_regex}" AND NOT line MATCHES "${_test_decl_regex}")
set(pending_decl "${line}")
set(pending_decl_line ${line_number})
if(pending_decl MATCHES "${_test_decl_partial_regex}")
continue()
endif()
set(pending_decl "")
endif()
# Parse preceding comments for @tag and @skip
string(REGEX MATCH "//[ \t]*@tag[ \t]+(.*)" _tag_match "${line}")
if(_tag_match)
@@ -129,11 +164,11 @@ foreach(line IN LISTS lines)
if(in_fixture_class)
string(APPEND registrations
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
"static Void::Testing::Detail::test_registrar<&${fixture_class_name}::${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
)
else()
string(APPEND registrations
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${line_number}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
"static Void::Testing::Detail::test_registrar<&${func_name}> _auto_reg_${safe_func_name}{\"${SUITE_NAME}\", \"${INPUT_FILE_FORWARD}\", ${registration_line}, \"${func_name}\", std::vector<std::string>${tags_cpp}, ${is_skipped_str}, ${current_skip}};\n"
)
endif()
+33
View File
@@ -0,0 +1,33 @@
# CMake toolchain for cross-compiling to Windows x64 with MinGW-w64.
#
# Works with the GCC-based mingw-w64 package and with the LLVM-MinGW
# toolchain (Dockerfile.mingw). Override the compiler paths for your install.
#
# Usage:
# cmake -B build-mingw -S . -G Ninja \
# -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
# -DCMAKE_BUILD_TYPE=Debug
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
if(NOT DEFINED VOID_MINGW_PREFIX)
set(VOID_MINGW_PREFIX x86_64-w64-mingw32)
endif()
find_program(VOID_MINGW_CXX NAMES "${VOID_MINGW_PREFIX}-clang++"
"${VOID_MINGW_PREFIX}-g++" REQUIRED)
find_program(VOID_MINGW_C NAMES "${VOID_MINGW_PREFIX}-clang"
"${VOID_MINGW_PREFIX}-gcc" REQUIRED)
find_program(VOID_MINGW_RC NAMES "${VOID_MINGW_PREFIX}-windres")
set(CMAKE_CXX_COMPILER "${VOID_MINGW_CXX}")
set(CMAKE_C_COMPILER "${VOID_MINGW_C}")
if(VOID_MINGW_RC)
set(CMAKE_RC_COMPILER "${VOID_MINGW_RC}")
endif()
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
+9 -9
View File
@@ -176,11 +176,11 @@ specs' observed baselines (D-035); not separately scheduled.
| VL-TOML-01 | P1 | Qualify `Data/Toml` limits for dotted keys/table paths/inline tables; API change only with reproducer | PLANNED |
| VL-LUA-01 | P2 | Sandboxed Lua runtime (allocation/step budgets, no ambient IO) | PLANNED (backend decision needed) |
| VL-STORE-01 | P2 | Native Storage conformance support for Forge | PLANNED |
| VL-SQLITE-01 | P2 (non-blocking) | Structural SQLite primary/extended result codes (distinguish UNIQUE/CONSTRAINT vs BUSY/LOCKED) instead of message-only (`Sqlite/Types.hpp`, `Sqlite.cpp`) | PLANNED |
| VL-SQLITE-02 | P2 (non-blocking) | Documented `Unknown` commit outcome for failed COMMIT under WAL I/O error (like `Storage` `Outcome::Unknown`) | PLANNED |
| VL-SEC-01 | P2 (non-blocking) | Public CSPRNG bytes API (e.g. `Security::random_bytes(std::span<unsigned char>)`) | PLANNED |
| VL-SQLITE-03 | P3 (non-blocking) | Per-connection, phase-targetable `ScopedFaultGuard` (incl. "COMMIT succeeded but reported failure") | PLANNED |
| VL-SQLITE-04 | P3 (non-blocking) | Per-call busy-timeout override | PLANNED |
| VL-SQLITE-01 | P2 (non-blocking) | Structural SQLite primary/extended result codes (distinguish UNIQUE/CONSTRAINT vs BUSY/LOCKED) instead of message-only (`Sqlite/Types.hpp`, `Sqlite.cpp`) | VERIFIED (`0e8ee18`, merged `797ea63`): native primary/extended codes carried in `Error::system_code()` with a SQLite error category and `sqlite_native_code()` accessor |
| VL-SQLITE-02 | P2 (non-blocking) | Documented `Unknown` commit outcome for failed COMMIT under WAL I/O error (like `Storage` `Outcome::Unknown`) | VERIFIED (`7eaa96f`, merged `103523f`): `TransactionState::Unknown` for unprovable COMMIT outcomes, Active retained when SQLite leaves the transaction open, stale commit/rollback rejected |
| VL-SEC-01 | P2 (non-blocking) | Public CSPRNG bytes API (e.g. `Security::random_bytes(std::span<unsigned char>)`) | VERIFIED (`54d143b`, merged `a29c947`): `Security::random_bytes` fills from libsodium, wipes on fault, empty buffer is a no-op |
| VL-SQLITE-03 | P3 (non-blocking) | Per-connection, phase-targetable `ScopedFaultGuard` (incl. "COMMIT succeeded but reported failure") | VERIFIED (`3b1ef4b`, merged `2532485`): `FaultConfig::connection` and `FaultPhase` targeting prepare/step/exec/commit/checkpoint/close, isolation and phase-mismatch tests |
| VL-SQLITE-04 | P3 (non-blocking) | Per-call busy-timeout override | VERIFIED (`7e5cf73`, merged `a1308a4`): scoped `BusyTimeoutOverride` with exact nested restore and negative-timeout rejection |
| VL-NET-W01 | P2 (hygiene) | `src/Net/HttpServer.cpp:1797,1871` ignore `read()`/`write()` results (`-Wunused-result` under consumer flags, likely `_FORTIFY_SOURCE`); VoidLibrary's own `-Werror` build at `38436b1` passes | PLANNED |
| VL-SQLITE-05 | P2 (non-blocking) | Write admission and `wal_checkpoint_recommended` use on-disk `-wal` size, which passive checkpoints never shrink, so `begin(Immediate)` stays `overloaded`; admit on un-checkpointed frames or truncate on admission failure (`Sqlite.cpp` ~:417-423, :1756-1762, :1918-1923) | PLANNED |
| VL-SQLITE-06 | P2 (non-blocking) | `Statement::step`/`exec` do not detect SQLite automatic rollback (FULL/IOERR/NOMEM/BUSY/INTERRUPT) via `sqlite3_get_autocommit`, so `Transaction` stays `Active` and later statements run in autocommit (`Sqlite.cpp` ~:884-910) | PLANNED |
@@ -189,9 +189,9 @@ specs' observed baselines (D-035); not separately scheduled.
| ID | Finding | Source | State |
| --- | --- | --- | --- |
| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then fix in `tests/CMakeLists.txt`) |
| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | PLANNED (verify, then count failures independently of retention) |
| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | PLANNED (scanner hardening or lint) |
| X-QA-01 | `VOID_WARNINGS_AS_ERRORS=ON` does not reach the generated `VoidTests` translation units, so test code is not compiled with `-Werror` | M-FUNCTIONAL-03 implementer report | VERIFIED (`77a2bce`): `tests/CMakeLists.txt` applies `-Wall -Wextra -Wpedantic -Werror` to `VoidTests` (with `-Wno-subobject-linkage` for GCC coroutine-frame noise); exposed warnings fixed in `Core/Meta.hpp` and `Time/Bench.cpp` |
| X-QA-02 | `src/Testing/Runner.cpp` recomputes pass/fail from only the first 1,000 retained assertions per test (`kMaxRetainedAssertionsPerTest`); later failures in one test can pass silently | M-FUNCTIONAL-03 implementer report | VERIFIED (`430deab`, merged `2501c4d`): `TestResult::failed_assertions` is counted in `Assert.cpp` at record time and both Runner paths use it, keeping the bounded retention for reporting; regression test `testing_runner_counts_failure_after_retention_cap` failed before and passes after; follow-up `898968d` resets the tally in the TestingMock failure-capture helper |
| X-QA-03 | Test scanner is line-anchored; a wrapped test declaration is silently dropped | M-FUNCTIONAL-03 implementer report | VERIFIED (`4bc8a7c`, merged `df41037`): `VoidTestScanner.cmake` joins wrapped `Test`/`DisabledTest` declarations; `ScannerWrapped` fixture covers wrapped return type, name and fixture member (4/4 discovered) |
| X-WF-01 | Agent `isolation: worktree` checkouts start at `main` (`38436b1`), not the wave branch tip; dispatches must fast-forward the worktree to the stated HEAD first | Observed in A1 | RECORDED (dispatch rule) |
## VoidForge upstream requests — M04 identity batch (received 2026-11-29; D-041)
@@ -202,4 +202,4 @@ specs' observed baselines (D-035); not separately scheduled.
| VL-CRYPTO-02 | P1 | `pbkdf2_hmac_sha256(password, salt, iterations, out_len)` (RFC 8018 §5.2) on the builtin HMAC path; RFC 7914 §11 vectors; bounded iterations/output | PLANNED |
| VL-NET-02 | P1 (blocks Forge production email) | Public TLS client stream (TCP+TLS, CA + hostname verification, STARTTLS upgrade) + minimal SMTP submission client (EHLO, STARTTLS-required or implicit TLS, AUTH PLAIN over TLS only, MAIL/RCPT/DATA with dot-stuffing, bounded size, deadlines) | PLANNED |
| VL-TEXT-01 | P2 | RFC 4648 base32 + Crockford base32 encode/decode | PLANNED |
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | PLANNED |
| X-QA-04 | AsyncRetry follow-ups from W11-REVIEW-B1b: race test only exercises the late-stop interleaving (add handshake/alternation); add direct checks of `detail::retry_backoff_stop_reason`; add a throwing-classifier test | W11-REVIEW-B1b P3-1/2/4 | VERIFIED (`65185f2`): added `async_retry_backoff_stop_reason_mapping`, `async_retry_stop_poll_handshake_alternation` (stop-first and poll-first orders) and `async_retry_throwing_classifier_propagates` |
+14
View File
@@ -309,3 +309,17 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
| Wave 11 full Debug ASan+UBSan (`c6de784`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w11-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 55 modules | **PASSED**: `1,694` discovered (`1,690 ✔`, `4 ⊘` skipped, `0 ✘`) in `67.61s`, `0` leaks, `0` UB |
| Wave 11 Debug TSan + 3x stress loop (`c6de784`) | `dev cpp-gcc` Debug TSan (`-Werror`, `/tmp/void-w11-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 21 modules (`Async;IO;IPC;SystemAsync;Storage;Runtime;ConfigurationAsync;System;Testing`) | **PASSED**: unfiltered `1,035` (`1,032 ✔`, `3 ⊘` skipped, `0 ✘`) in `34.78s`; 3x Wave 11 stress loop `169/169 ✔` (`2.12s`, `3.07s`, `2.14s`), `0` data races / lock-order warnings |
| Post-W11 Benchmark (`c6de784`, `rev=c6de7842f732`) | `/tmp/void-w11-full/benchmarks/VoidFoundationBench --json /tmp/void-w11-full/post-w11.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 26.06ns, `core_uuid_to_string` 18.06ns, `core_hash_fnv1a64_256b` 186.38ns, `core_hash_murmur3_256b` 69.57ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 61.13ns, `math_checked_add_loop` 0.50ns, `containers_spsc_ring_push_pop` 9.33ns, `containers_lru_get_put` 22.02ns, `binary_reader_u64_be` 1.19ns, `data_json_parse_small_object` 302.08ns, `data_json_serialize_small_object` 170.90ns |
## Applications-stack example sanitizer matrix
Built as installed-package consumers against the local Void install; every suite run
with `halt_on_error=1` (ASan leak detection enabled).
| Check | Outcome |
| --- | --- |
| Distributed host-graph ASan+UBSan (`91e7a90`) | Debug `-fsanitize=address,undefined`, `ASAN_OPTIONS=detect_leaks=1`, `UBSAN_OPTIONS=halt_on_error=1`: ctest `8/8` passed, `0` leaks, `0` UB |
| Distributed host-graph TSan (`91e7a90`) | Debug `-fsanitize=thread`, `TSAN_OPTIONS=halt_on_error=1`: ctest `8/8` passed, `0` data races |
| Reloadable host ASan+UBSan (`2da3971`) | Debug ASan+UBSan, leak detection on: ctest `7/7` passed, `0` leaks, `0` UB (includes real subprocess supervision tests) |
| Networked KV ASan+UBSan (`57ebf31`) | Debug ASan+UBSan, leak detection on: ctest `7/7` passed, `0` leaks, `0` UB |
| Networked KV TSan (`57ebf31`) | Debug `-fsanitize=thread`: ctest `7/7` passed, `0` data races |
| Applications-stack workload baseline (`b70306f`) | `distributed_host_graph_bench --json <tmp>/host-graph-baseline.json` (Debug, warmup=3, 5 reps × 200 ops, p50/p95/p99 over all samples, 95% CI of the mean); ctest `9/9` | `kv_propose_3node` 2.74/9.25/15.67µs (mean 3.41µs, CI [3.25, 3.58]), `kv_quorum_read_3node` 0.43/0.49/0.52µs (mean 0.43µs), `queue_publish_claim_ack_3node` 66.7/117.3/125.0µs (mean 70.7µs), `http_peer_health_roundtrip` 255.6/395.7/1281.5µs (mean 292.8µs); no latency threshold asserted |
+249
View File
@@ -0,0 +1,249 @@
# Target support
VoidLibrary is qualified per **target profile**: a platform, a compiler and
standard library, the external dependencies that are expected to exist, and
the set of modules that are expected to build there. The profile is detected
from the toolchain at configure time, validated against the selected modules,
and recorded in `void-target-manifest.cmake` (installed next to
`VoidConfig.cmake`).
```bash
# Native Linux (default)
cmake -S . -B build -G Ninja -DVOID_ENABLE_TESTING=ON
# Force a profile for a qualification run (normally auto-detected)
cmake -S . -B build-wasm -G Ninja -DVOID_TARGET=wasm \
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
# Cross build (Windows client example)
cmake -S . -B build-mingw -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/mingw-w64.cmake \
-DVOID_ENABLED_MODULES="Core;Functional;Text;Data"
```
`VOID_TARGET` is `auto` by default. The recognized values are `linux`,
`linux-musl`, `windows` and `wasm`; anything else fails at configure time with
the list of known targets. `cmake/Targets.cmake` holds the allowlists and the
validation rules.
## Manifest
Every configure writes `void-target-manifest.cmake`:
| Field | Meaning |
|-------|---------|
| `VOID_TARGET_MANIFEST_TARGET` | detected/forced profile (`linux`, `linux-musl`, `windows`, `wasm`) |
| `VOID_TARGET_MANIFEST_TARGET_ORIGIN` | `auto` or the forced `VOID_TARGET` value |
| `VOID_TARGET_MANIFEST_TRIPLE` | `CMAKE_C_COMPILER -dumpmachine` |
| `VOID_TARGET_MANIFEST_SYSTEM_NAME` / `..._SYSTEM_PROCESSOR` | CMake system identification |
| `VOID_TARGET_MANIFEST_COMPILER_ID` / `..._COMPILER_VERSION` | compiler tuple |
| `VOID_TARGET_MANIFEST_CXX_STANDARD` | language standard |
| `VOID_TARGET_MANIFEST_LINKAGE` | `shared` or `static` |
| `VOID_TARGET_MANIFEST_REFLECTION` | C++26 reflection available (`yes`/`no`) |
| `VOID_TARGET_MANIFEST_STD_EXPECTED` | `<expected>` available |
| `VOID_TARGET_MANIFEST_SANITIZERS` | `none`, `ASan`, `UBSan`, `TSan` or a combination |
| `VOID_TARGET_MANIFEST_TESTING` | `VOID_ENABLE_TESTING` |
| `VOID_TARGET_MANIFEST_MODULES` | configured modules |
Consumers can read it after `find_package(Void)`:
```cmake
include("${Void_DIR}/void-target-manifest.cmake")
message(STATUS "Void target: ${VOID_TARGET_MANIFEST_TARGET}")
```
## Qualified tuples
### Linux (qualified)
| Item | Value |
|------|-------|
| Triple | `x86_64-unknown-linux-gnu` (NixOS, glibc) |
| Compiler | GCC 16.2.0 (`dev cpp-gcc`) |
| Standard library | libstdc++ 16 |
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
| Language | C++26, reflection `yes` (`-freflection`) |
| Dependencies | Boost (headers/url/beast/asio), OpenSSL, SQLite3, Lua 5.4 (optional) |
| Modules | all |
| Observed | `Testing;Core` configure/build clean; `ctest` 3/3 (VoidTests, installed consumers, target qualification) |
The Linux profile is the reference target: every module is allowed and the
per-module platform code selects the native implementation.
### Linux / musl (configure/build/install/consume qualified)
| Item | Value |
|------|-------|
| Triple | `x86_64-alpine-linux-musl` (Alpine 3.23.8, musl 1.2.5-r24) |
| Compiler | Alpine GCC 15.2.0 (Clang accepted by the allowlist) |
| Standard library | libstdc++ with musl 1.2.5 |
| CMake / generator | CMake 4.1.3, Ninja 1.13.2 |
| Dependencies | `boost-dev` 1.84.0, `openssl-dev` 3.5.10, `sqlite-dev` 3.53.4, `lua5.4-dev` 5.4.8, `linux-headers` from apk |
| Language | C++26, reflection `no` (GCC 15), `<expected>` `yes` |
| Modules | `Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System SystemAsync Text Time` |
| Observed | RelWithDebInfo with `-DVOID_WARNINGS_AS_ERRORS=ON` and `-DVOID_ENABLE_TESTING=OFF`: configure detected `linux-musl`, build passed, `cmake --install` to a prefix succeeded, and the isolated `TargetProfile` consumer configured, linked, and ran (`VoidTargetProfileConsumer` 1/1) recording `target=linux-musl triple=x86_64-alpine-linux-musl compiler=GNU-15.2.0 linkage=shared reflection=no`. Test suite with `-DVOID_ENABLE_TESTING=ON`: 1226 tests, 1221 passed, 5 skipped, 0 failed |
The test suite is qualified too: with `VOID_ENABLE_TESTING=ON` (modules
`Async Binary Containers Core Crypto Data Functional FunctionalCoreFormatting
IO IPC LogState Math Memory Net ObservabilityHooks Resilience Sqlite System
SystemAsync Testing Text Time`) the Alpine 3.23 container build ran
**1226 tests: 1221 passed, 5 skipped, 0 failed**. Reflection-only tests are
skipped through `// @requires-reflection`. The run also exposed a test bug in
`Net/HttpDuplex.cpp` (`recv_until` consumed body bytes past the header
marker); the helper now reads byte-wise and the duplex tests pass on musl and
glibc.
Detection uses `CMAKE_C_COMPILER -dumpmachine` (or
`CMAKE_C_LIBRARY_ARCHITECTURE`/`CMAKE_C_FLAGS`) matching `musl`. The profile is
recognized and configured like Linux; musl-specific behaviour (subprocess
`/proc`, `dl`, locale) must still be verified before claiming full support.
### Windows client (compile/install/consume + Wine runtime qualified)
| Item | Value |
|------|-------|
| Triple | `x86_64-w64-mingw32` |
| Compiler | MinGW-w64 GCC 16.2.0 |
| Standard library | libstdc++ + mingw-w64 CRT (mcfgthread threading in the Nix wrapper) |
| CMake / generator | CMake 4.5.0, Ninja 1.13.2 |
| Language | C++26, reflection `yes` |
| Runtime | Wine 11.0 (`wine64`), no native Windows runner available |
| Modules | `Algorithms Async Binary Containers Core Data Discovery Fsm Functional Log LogState Math Memory Messaging Observability ObservabilityHooks Scheduler Service Testing TestingMock Text Time Unicode` |
| Observed | configure, compile, `cmake --install`, consume (`TargetProfile.exe` linked); `VoidTests.exe` under Wine: **1364 tests, 1360 passed, 4 skipped, 0 failed** |
Notes from the runtime run:
- `IO` is **not** in the Windows allowlist. It builds, but its native backend
is Linux-only (`EpollBackend`); on Windows `Driver::create` returns
`IoErrorCode::unsupported` unless the mock backend is selected. A Windows
IO backend (IOCP) is a separate task.
- `Observability` links after replacing the namespace-scope
`inline thread_local` hook stack with a function-local `thread_local`
accessor (MinGW emitted duplicate TLS init functions).
- Test code is portable: POSIX-only descriptor assertions are guarded, the
Log hardening test closes its `ifstream` before removing the file, and the
subprocess-isolation test skips when `current_executable_path()` is not
implemented (Windows has no subprocess isolation yet).
- MinGW test builds need `-Wa,-mbig-obj`: the Fsm hardening test TU exceeds
the COFF section limit with the default object format.
- Runtime observations come from Wine, not a native Windows runner; a
Windows CI runner should confirm them.
The Nix MinGW wrapper needs the mcfgthread include/library paths explicitly:
```bash
MINGW=/nix/store/...-x86_64-w64-mingw32-gcc-wrapper-16.2.0/bin
MCFG=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1/lib
MCFGINC=/nix/store/...-mcfgthread-x86_64-w64-mingw32-2.5.1-dev/include
cmake -S . -B build-mingw -G Ninja \
-DCMAKE_SYSTEM_NAME=Windows \
-DCMAKE_C_COMPILER="$MINGW/x86_64-w64-mingw32-gcc" \
-DCMAKE_CXX_COMPILER="$MINGW/x86_64-w64-mingw32-g++" \
-DCMAKE_C_FLAGS="-I$MCFGINC" -DCMAKE_CXX_FLAGS="-I$MCFGINC" \
-DCMAKE_EXE_LINKER_FLAGS="-L$MCFG" \
-DCMAKE_SHARED_LINKER_FLAGS="-L$MCFG"
```
A regular MinGW-w64 installation with winpthreads does not need those extra
flags.
### Browser / Wasm subset (qualified)
| Item | Value |
|------|-------|
| Triple | `wasm32-unknown-emscripten` |
| Compiler | Emscripten 6.0.9 (Clang 22.1.8) |
| Standard library | libc++ + Emscripten libc |
| CMake / generator | CMake 4.5 via `emcmake`, Ninja, Node 24.22.3 as the test emulator |
| Language | C++26 without reflection (`VOID_HAS_CXX26_REFLECTION=no`) |
| Modules | `Algorithms Binary Containers Core Data Functional LogState Math Memory Testing TestingMock Text Time Unicode` |
| Observed | library: configure, compile, install, consume and run under Node; tests: **901 tests, 895 passed, 6 skipped, 0 failed** under Node |
The allowlist is fail-closed: native networking (`Net`, `RPC`), processes and
filesystem (`System`, `SystemAsync`), IPC, SQLite, plugins and anything that
needs threads or reflection stay out. Do not add a module until it has been
configured and compiled with `emcmake`.
Verified commands:
```bash
# Library subset
emcmake cmake -S . -B build-wasm -G Ninja -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
-DVOID_ENABLE_TESTING=OFF \
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
cmake --build build-wasm
cmake --install build-wasm --prefix "$PWD/build-wasm-install"
# Consumer (the install lives outside the Emscripten sysroot)
emcmake cmake -S tests/package/TargetProfile -B build-wasm-consumer -G Ninja \
-DCMAKE_PREFIX_PATH="$PWD/build-wasm-install" \
-DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH \
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
-DVOID_EXPECTED_TARGET=wasm
cmake --build build-wasm-consumer
node build-wasm-consumer/void_target_profile_consumer.js
```
`CMAKE_CXX_SCAN_FOR_MODULES=OFF` avoids CMake's C++20 module dependency
scanner calling Emscripten's `emscan-deps`, which is not shipped by every
Emscripten package. `CMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH` is needed
because the Emscripten toolchain restricts package lookup to its sysroot.
The **test suite** is qualified with pthreads, exception handling and a
larger stack:
```bash
emcmake cmake -S . -B build-wasm-tests -G Ninja -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_SCAN_FOR_MODULES=OFF \
-DBUILD_SHARED_LIBS=OFF \
-DCMAKE_CXX_FLAGS="-fexceptions -pthread" \
-DCMAKE_EXE_LINKER_FLAGS="-fexceptions -pthread -sSTACK_SIZE=16777216 \
-sINITIAL_MEMORY=134217728 -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1073741824" \
-DVOID_ENABLE_TESTING=ON \
-DVOID_ENABLED_MODULES="Algorithms;Binary;Containers;Core;Data;Functional;LogState;Math;Memory;Testing;TestingMock;Text;Time;Unicode"
cmake --build build-wasm-tests
node build-wasm-tests/tests/VoidTests.js --no-color
```
Static linking (`BUILD_SHARED_LIBS=OFF`) is required for exception handling
across the test binary; `-fexceptions` enables catching, `-pthread` enables
the threading tests, and the stack/memory flags accommodate the deepest
recursive tests.
Portable fallbacks added for libc++ without the C++23/26 pieces:
`Core/Publication` uses a mutex-protected `shared_ptr` when
`__cpp_lib_atomic_shared_ptr` is absent, and `TestingMock` uses an internal
move-only function wrapper when `__cpp_lib_move_only_function` is absent.
Reflection-dependent test files are gated with `// @requires-reflection`
(Core/Meta, Core/FlagsReflect, Data/CsvReflect, Data/Reflect*,
Functional/ResultReflectionFormat, Testing/ContainerFixture,
TestingMock/Reflect, Configuration/Fsm annotation tests) and are skipped when
`VOID_HAS_CXX26_REFLECTION` is false, so a non-reflecting compiler no longer
fails on scanner-generated registrations for functions hidden by `#ifdef`.
Runtime observations use Node; a browser runner should confirm them.
## Sanitizers
Sanitizer builds are native-only qualification configurations, not target
profiles: `VOID_ENABLE_ASAN`, `VOID_ENABLE_UBSAN` and `VOID_ENABLE_TSAN`
instrument the host build and are recorded in the manifest. Production
packages are built with sanitizers off. ASan+TSan is rejected; TSan is
rejected on `wasm`.
## Qualification test
`tests/package/TargetQualification.cmake` (ctest
`VoidTargetQualification`) installs the build tree and:
1. Consumes the install through `tests/package/TargetProfile`, asserting the
manifest target/triple/compiler/linkage/reflection fields and running one
Core behaviour.
2. Rejects an unknown `VOID_TARGET`.
3. Rejects a native module (`IPC`) and native networking (`Net`) on the
`wasm` profile.
4. Rejects a missing external dependency (`Sqlite` without SQLite3).
5. Configures the pure wasm subset and asserts the manifest records
`wasm`.
@@ -0,0 +1,71 @@
cmake_minimum_required(VERSION 4.0)
project(DistributedHostGraph LANGUAGES CXX)
# Reference platform component, built as an installed-package consumer so it
# cannot accidentally rely on whole-repository linkage.
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(Void CONFIG REQUIRED COMPONENTS Functional Net System)
add_library(distributed_host_graph STATIC
src/cluster_fixture.cpp
src/host_graph.cpp
src/range_placement.cpp
src/replicated_kv.cpp
src/replicated_queue.cpp
src/single_node.cpp)
target_include_directories(distributed_host_graph PUBLIC include)
target_link_libraries(distributed_host_graph PUBLIC Void::Functional Void::Net)
add_executable(distributed_host_graph_test tests/host_graph_test.cpp)
target_link_libraries(distributed_host_graph_test PRIVATE distributed_host_graph)
add_executable(distributed_single_node_test tests/single_node_test.cpp)
target_link_libraries(distributed_single_node_test PRIVATE distributed_host_graph)
add_executable(distributed_replicated_kv_test tests/replicated_kv_test.cpp)
target_link_libraries(distributed_replicated_kv_test PRIVATE distributed_host_graph)
add_executable(distributed_cluster_fixture_test tests/cluster_fixture_test.cpp)
target_link_libraries(distributed_cluster_fixture_test PRIVATE distributed_host_graph)
add_executable(distributed_replicated_queue_test tests/replicated_queue_test.cpp)
target_link_libraries(distributed_replicated_queue_test PRIVATE distributed_host_graph)
add_executable(distributed_operations_test tests/operations_test.cpp)
target_link_libraries(distributed_operations_test PRIVATE distributed_host_graph)
add_executable(distributed_range_placement_test tests/range_placement_test.cpp)
target_link_libraries(distributed_range_placement_test PRIVATE distributed_host_graph)
add_executable(distributed_cluster_queue_test tests/cluster_queue_test.cpp)
target_link_libraries(distributed_cluster_queue_test PRIVATE distributed_host_graph)
add_executable(distributed_host_graph_bench benchmarks/host_graph_bench.cpp)
target_link_libraries(distributed_host_graph_bench PRIVATE distributed_host_graph)
# Out-of-process voter agent and the multi-process acceptance harness that
# spawns three of them.
add_executable(distributed_voter_agent agents/voter_agent.cpp)
target_link_libraries(distributed_voter_agent PRIVATE Void::Net)
add_executable(distributed_multi_process_test tests/multi_process_test.cpp)
target_link_libraries(distributed_multi_process_test PRIVATE Void::Net Void::System)
enable_testing()
add_test(NAME distributed_host_graph COMMAND distributed_host_graph_test)
add_test(NAME distributed_single_node COMMAND distributed_single_node_test)
add_test(NAME distributed_replicated_kv COMMAND distributed_replicated_kv_test)
add_test(NAME distributed_cluster_fixture COMMAND distributed_cluster_fixture_test)
add_test(NAME distributed_replicated_queue COMMAND distributed_replicated_queue_test)
add_test(NAME distributed_operations COMMAND distributed_operations_test)
add_test(NAME distributed_range_placement COMMAND distributed_range_placement_test)
add_test(NAME distributed_cluster_queue COMMAND distributed_cluster_queue_test)
# Smoke-run the workload baseline; it reports numbers instead of asserting
# latency thresholds.
add_test(NAME distributed_host_graph_bench_smoke
COMMAND distributed_host_graph_bench --quick)
add_test(NAME distributed_multi_process
COMMAND distributed_multi_process_test $<TARGET_FILE:distributed_voter_agent>)
@@ -0,0 +1,611 @@
// Out-of-process voter agent for the multi-process acceptance harness.
//
// Each agent owns one directory and durably persists its Raft-style state
// (current term, vote, log, commit index) before replying to any RPC. The
// parent harness drives elections and replication over authenticated HTTP;
// killing an agent loses nothing acknowledged, and a restarted agent
// recovers from disk.
//
// distributed_voter_agent --dir <path> --port <port|0> --token <token>
//
// The bound port is written to `<dir>/port` once the listener is up.
// Keys and values are restricted to [A-Za-z0-9_.-] so the durable text format
// stays unambiguous.
#include <Void/Net/HttpServer.hpp>
#include <fcntl.h>
#include <unistd.h>
#include <algorithm>
#include <charconv>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <map>
#include <mutex>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
namespace
{
using Entry = std::pair<std::uint64_t, std::uint64_t>; // term, index
struct LogEntry {
std::uint64_t term{0};
std::uint64_t index{0};
std::string key;
std::string value;
[[nodiscard]] bool operator==(const LogEntry&) const noexcept =
default;
};
[[nodiscard]] bool safe_token(std::string_view text)
{
return !text.empty() &&
std::ranges::all_of(text, [](char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_' || c == '.' ||
c == '-';
});
}
void sync_directory(const std::filesystem::path& directory)
{
const int fd = ::open(directory.c_str(), O_RDONLY | O_DIRECTORY);
if (fd >= 0) {
(void)::fsync(fd);
(void)::close(fd);
}
}
/// Durable voter state. Every mutation is persisted (write, fsync, rename,
/// directory fsync) before the RPC returns success.
class VoterStore
{
public:
explicit VoterStore(std::filesystem::path directory)
: m_directory(std::move(directory))
, m_path(m_directory / "voter.state")
{
}
[[nodiscard]] bool load()
{
std::lock_guard lock{m_mutex};
if (!std::filesystem::exists(m_path)) {
return std::filesystem::create_directories(m_directory) ||
std::filesystem::exists(m_directory);
}
std::ifstream in{m_path};
if (!in.is_open()) {
return false;
}
std::string line;
while (std::getline(in, line)) {
std::istringstream fields{line};
std::string tag;
fields >> tag;
if (tag == "term") {
std::uint64_t term = 0;
std::string voted;
if (!(fields >> term >> voted)) {
return false;
}
m_term = term;
m_voted_for = voted == "-"
? std::nullopt
: std::optional<std::string>{voted};
} else if (tag == "entry") {
LogEntry entry;
if (!(fields >> entry.term >> entry.index >> entry.key >>
entry.value)) {
return false;
}
m_log.push_back(std::move(entry));
} else if (tag == "commit") {
if (!(fields >> m_commit)) {
return false;
}
} else {
return false;
}
}
reapply();
return true;
}
[[nodiscard]] std::uint64_t term() const
{
std::lock_guard lock{m_mutex};
return m_term;
}
[[nodiscard]] std::uint64_t last_index() const
{
std::lock_guard lock{m_mutex};
return m_log.empty() ? 0 : m_log.back().index;
}
[[nodiscard]] std::uint64_t last_term() const
{
std::lock_guard lock{m_mutex};
return m_log.empty() ? 0 : m_log.back().term;
}
[[nodiscard]] std::uint64_t commit() const
{
std::lock_guard lock{m_mutex};
return m_commit;
}
[[nodiscard]] std::size_t log_size() const
{
std::lock_guard lock{m_mutex};
return m_log.size();
}
[[nodiscard]] std::string voted_for() const
{
std::lock_guard lock{m_mutex};
return m_voted_for.value_or("-");
}
/// Grant a vote when the term allows it and the candidate's log is
/// at least as up to date.
[[nodiscard]] bool vote(std::uint64_t term, std::string_view candidate,
std::uint64_t candidate_last_index,
std::uint64_t candidate_last_term)
{
std::lock_guard lock{m_mutex};
if (term < m_term) {
return false;
}
if (term > m_term) {
m_term = term;
m_voted_for.reset();
if (!persist()) {
return false;
}
}
if (m_voted_for.has_value() && *m_voted_for != candidate) {
return false;
}
const std::uint64_t self_index =
m_log.empty() ? 0 : m_log.back().index;
const std::uint64_t self_term =
m_log.empty() ? 0 : m_log.back().term;
const bool up_to_date =
candidate_last_term > self_term ||
(candidate_last_term == self_term &&
candidate_last_index >= self_index);
if (!up_to_date) {
return false;
}
m_voted_for = std::string{candidate};
return persist();
}
/// AppendEntries: returns the matched index on success.
[[nodiscard]] std::optional<std::uint64_t> append(
std::uint64_t term, std::uint64_t prev_index,
std::uint64_t prev_term, std::uint64_t leader_commit,
const std::vector<LogEntry>& entries)
{
std::lock_guard lock{m_mutex};
if (term < m_term) {
return std::nullopt;
}
if (term > m_term) {
m_term = term;
m_voted_for.reset();
}
const std::uint64_t local_last =
m_log.empty() ? 0 : m_log.back().index;
if (prev_index > local_last) {
return std::nullopt;
}
const std::uint64_t local_term =
prev_index == 0 ? 0 : m_log[prev_index - 1].term;
if (local_term != prev_term) {
return std::nullopt;
}
std::size_t position = static_cast<std::size_t>(prev_index);
for (const auto& entry : entries) {
if (position < m_log.size() &&
m_log[position] == entry) {
++position;
continue;
}
m_log.resize(position);
m_log.push_back(entry);
++position;
}
if (leader_commit > m_commit) {
m_commit = std::min(leader_commit,
m_log.empty() ? 0 : m_log.back().index);
}
reapply();
if (!persist()) {
return std::nullopt;
}
return m_log.empty() ? 0 : m_log.back().index;
}
[[nodiscard]] std::vector<LogEntry> entries_from(
std::uint64_t index) const
{
std::lock_guard lock{m_mutex};
std::vector<LogEntry> out;
for (const auto& entry : m_log) {
if (entry.index >= index) {
out.push_back(entry);
}
}
return out;
}
[[nodiscard]] std::optional<std::string> value(
std::string_view key) const
{
std::lock_guard lock{m_mutex};
const auto found = m_kv.find(key);
if (found == m_kv.end()) {
return std::nullopt;
}
return found->second;
}
private:
void reapply()
{
m_kv.clear();
for (const auto& entry : m_log) {
if (entry.index > m_commit) {
break;
}
if (entry.value == "-") {
m_kv.erase(entry.key);
} else {
m_kv.insert_or_assign(entry.key, entry.value);
}
}
}
[[nodiscard]] bool persist()
{
std::string text;
text += "term " + std::to_string(m_term) + " " +
m_voted_for.value_or("-") + "\n";
for (const auto& entry : m_log) {
text += "entry " + std::to_string(entry.term) + " " +
std::to_string(entry.index) + " " + entry.key + " " +
entry.value + "\n";
}
text += "commit " + std::to_string(m_commit) + "\n";
const auto temporary = m_path.string() + ".tmp";
{
std::ofstream out{temporary, std::ios::trunc};
if (!out.is_open()) {
return false;
}
out << text;
out.flush();
if (!out.good()) {
return false;
}
}
const int fd = ::open(temporary.c_str(), O_RDONLY);
if (fd < 0) {
return false;
}
(void)::fsync(fd);
(void)::close(fd);
if (std::rename(temporary.c_str(), m_path.c_str()) != 0) {
return false;
}
sync_directory(m_directory);
return true;
}
mutable std::mutex m_mutex;
std::filesystem::path m_directory;
std::filesystem::path m_path;
std::uint64_t m_term{0};
std::optional<std::string> m_voted_for;
std::vector<LogEntry> m_log;
std::uint64_t m_commit{0};
std::map<std::string, std::string, std::less<>> m_kv;
};
[[nodiscard]] std::optional<std::string_view>
query(std::string_view text, std::string_view name)
{
std::size_t pos = 0;
while (pos <= text.size()) {
const std::size_t amp = text.find('&', pos);
const std::string_view pair =
text.substr(pos, amp == std::string_view::npos
? std::string_view::npos
: amp - pos);
const std::size_t eq = pair.find('=');
if (pair.substr(0, eq) == name) {
return eq == std::string_view::npos ? std::string_view{}
: pair.substr(eq + 1);
}
if (amp == std::string_view::npos) {
break;
}
pos = amp + 1;
}
return std::nullopt;
}
[[nodiscard]] std::optional<std::uint64_t> number(std::string_view text)
{
if (text.empty()) {
return std::nullopt;
}
std::uint64_t value = 0;
const auto parsed =
std::from_chars(text.data(), text.data() + text.size(), value);
if (parsed.ec != std::errc{}) {
return std::nullopt;
}
return value;
}
[[nodiscard]] Void::Net::ServerResponse text_response(int status,
std::string body)
{
Void::Net::ServerResponse response;
response.status = static_cast<std::uint16_t>(status);
response.headers.push_back(
Void::Net::Header{"content-type", "text/plain; charset=utf-8"});
response.body = std::move(body);
return response;
}
} // namespace
int main(int argc, char** argv)
{
std::filesystem::path directory;
std::uint16_t port = 0;
std::string token;
long long parent{0};
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
if (arg == "--dir" && i + 1 < argc) {
directory = argv[++i];
} else if (arg == "--parent" && i + 1 < argc) {
parent = std::strtoll(argv[++i], nullptr, 10);
} else if (arg == "--port" && i + 1 < argc) {
unsigned int value = 0;
const auto parsed = std::from_chars(argv[i + 1],
argv[i + 1] + std::strlen(argv[i + 1]),
value);
if (parsed.ec != std::errc{} || value > 65535U) {
std::fprintf(stderr, "invalid --port\n");
return 2;
}
port = static_cast<std::uint16_t>(value);
++i;
} else if (arg == "--token" && i + 1 < argc) {
token = argv[++i];
}
}
if (directory.empty() || token.empty()) {
std::fprintf(stderr,
"usage: distributed_voter_agent --dir <path> "
"--port <port|0> --token <token>\n");
return 2;
}
VoterStore store{directory};
if (!store.load()) {
std::fprintf(stderr, "voter agent: failed to load durable state\n");
return 3;
}
Void::Net::HttpServerOptions options;
options.bind_host = "127.0.0.1";
options.port = port;
options.max_concurrent_connections = 8;
options.max_body_bytes = 64ULL * 1024ULL;
Void::Net::HttpServer server{options};
auto guarded = [token](const Void::Net::ServerRequest& request)
-> std::optional<Void::Net::ServerResponse> {
const auto header = request.header("authorization");
const std::string expected = "Bearer " + token;
if (!header || *header != expected) {
return text_response(401, "unauthorized");
}
return std::nullopt;
};
auto add = [&](Void::Net::Method method, const char* pattern, auto fn) {
return server.add_route(
method, pattern,
[guarded, fn](const Void::Net::ServerRequest& request)
-> Void::Net::RouteResult {
if (auto denied = guarded(request)) {
return Void::Result::ok(std::move(*denied));
}
return Void::Result::ok(fn(request));
});
};
auto registered = add(
Void::Net::Method::Get, "/voter/state",
[&store](const Void::Net::ServerRequest&) {
return text_response(
200, "term=" + std::to_string(store.term()) +
" voted=" + store.voted_for() +
" last_index=" + std::to_string(store.last_index()) +
" last_term=" + std::to_string(store.last_term()) +
" commit=" + std::to_string(store.commit()) +
" entries=" + std::to_string(store.log_size()));
});
if (!registered) {
return 4;
}
registered = add(
Void::Net::Method::Post, "/voter/vote",
[&store](const Void::Net::ServerRequest& request) {
const auto term = number(query(request.query, "term").value_or(""));
const auto last_index =
number(query(request.query, "last_index").value_or(""));
const auto last_term =
number(query(request.query, "last_term").value_or(""));
const auto candidate = query(request.query, "candidate");
if (!term || !last_index || !last_term || !candidate ||
!safe_token(*candidate)) {
return text_response(400, "bad vote request");
}
if (!store.vote(*term, *candidate, *last_index, *last_term)) {
return text_response(409, "vote rejected");
}
return text_response(200, "granted");
});
if (!registered) {
return 4;
}
registered = add(
Void::Net::Method::Post, "/voter/append",
[&store](const Void::Net::ServerRequest& request) {
const auto term = number(query(request.query, "term").value_or(""));
const auto prev_index =
number(query(request.query, "prev_index").value_or(""));
const auto prev_term =
number(query(request.query, "prev_term").value_or(""));
const auto commit =
number(query(request.query, "commit").value_or(""));
if (!term || !prev_index || !prev_term || !commit) {
return text_response(400, "bad append request");
}
std::vector<LogEntry> entries;
std::size_t pos = 0;
while (pos < request.body.size()) {
const std::size_t end = request.body.find('\n', pos);
const std::string_view line = std::string_view{request.body}.substr(
pos, end == std::string::npos ? std::string::npos : end - pos);
if (!line.empty()) {
LogEntry entry;
std::string key;
std::string value;
const std::size_t first = line.find(',');
const std::size_t second =
first == std::string_view::npos
? std::string_view::npos
: line.find(',', first + 1);
const std::size_t third =
second == std::string_view::npos
? std::string_view::npos
: line.find(',', second + 1);
if (first == std::string_view::npos ||
second == std::string_view::npos ||
third == std::string_view::npos) {
return text_response(400, "bad entry");
}
const auto entry_term = number(line.substr(0, first));
const auto entry_index =
number(line.substr(first + 1, second - first - 1));
key = line.substr(second + 1, third - second - 1);
value = line.substr(third + 1);
if (!entry_term || !entry_index || !safe_token(key) ||
!(safe_token(value) || value == "-")) {
return text_response(400, "bad entry");
}
entry.term = *entry_term;
entry.index = *entry_index;
entry.key = key;
entry.value = value;
entries.push_back(std::move(entry));
}
if (end == std::string::npos) {
break;
}
pos = end + 1;
}
const auto matched =
store.append(*term, *prev_index, *prev_term, *commit, entries);
if (!matched) {
return text_response(409, "append rejected");
}
return text_response(200, "matched=" + std::to_string(*matched));
});
if (!registered) {
return 4;
}
registered = add(
Void::Net::Method::Get, "/voter/value",
[&store](const Void::Net::ServerRequest& request) {
const auto key = query(request.query, "key");
if (!key) {
return text_response(400, "key required");
}
const auto value = store.value(*key);
if (!value) {
return text_response(404, "not found");
}
return text_response(200, *value);
});
if (!registered) {
return 4;
}
registered = add(
Void::Net::Method::Get, "/voter/entries",
[&store](const Void::Net::ServerRequest& request) {
const auto from = number(query(request.query, "from").value_or("1"));
if (!from) {
return text_response(400, "from required");
}
std::string body;
for (const auto& entry : store.entries_from(*from)) {
body += std::to_string(entry.term) + "," +
std::to_string(entry.index) + "," + entry.key + "," +
entry.value + "\n";
}
return text_response(200, std::move(body));
});
if (!registered) {
return 4;
}
if (auto started = server.start(); !started) {
std::fprintf(stderr, "voter agent: failed to bind listener\n");
return 5;
}
{
const auto port_path = directory / "port";
std::ofstream out{port_path, std::ios::trunc};
out << server.bound_port() << "\n";
}
// Serve until the parent kills this process. An agent whose supervising
// parent disappeared exits on its own so it can never orphan and hold the
// harness's output pipes open.
while (parent == 0 || ::getppid() == parent) {
std::this_thread::sleep_for(std::chrono::milliseconds{200});
}
return 0;
}
@@ -0,0 +1,299 @@
// Applications-stack workload baseline.
//
// Measures the replicated KV propose/quorum-read paths, the replicated
// queue publish/claim/ack path and the three-listener HTTP fixture roundtrip.
// Each case runs warmup, several repetitions, and reports p50/p95/p99 plus a
// 95% confidence interval for the mean. No latency threshold is asserted:
// numbers are workload baselines, per PERFORMANCE.md.
//
// host_graph_bench [--quick] [--json <path>]
#include "distributed_host/cluster_fixture.hpp"
#include "distributed_host/replicated_kv.hpp"
#include "distributed_host/replicated_queue.hpp"
#include <Void/Net/Http.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <format>
#include <fstream>
#include <functional>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace
{
using Clock = std::chrono::steady_clock;
void check(bool condition, const char* what)
{
if (!condition) {
std::fprintf(stderr, "benchmark invariant failed: %s\n", what);
std::exit(1);
}
}
struct Stats {
std::string name;
std::size_t samples{0};
double p50_ns{0};
double p95_ns{0};
double p99_ns{0};
double mean_ns{0};
double ci95_low_ns{0};
double ci95_high_ns{0};
double ops_per_sec{0};
};
[[nodiscard]] double percentile(std::vector<double> values, double p)
{
if (values.empty()) {
return 0;
}
std::ranges::sort(values);
const double rank = (p / 100.0) * static_cast<double>(values.size());
auto index = static_cast<std::size_t>(std::ceil(rank));
index = index == 0 ? 0 : index - 1;
return values[std::min(index, values.size() - 1)];
}
class Bench {
public:
Bench(std::string name, std::size_t reps, std::size_t ops,
std::size_t warmup = 3)
: m_name(std::move(name)), m_reps(reps), m_ops(ops),
m_warmup(warmup)
{
}
/// `fn` runs outside the timer for setup/epoch resets; `op` is the
/// measured operation.
void run(const std::function<void()>& setup,
const std::function<void()>& op)
{
for (std::size_t i = 0; i < m_warmup; ++i) {
setup();
op();
}
m_samples.reserve(m_reps * m_ops);
for (std::size_t rep = 0; rep < m_reps; ++rep) {
std::size_t epoch = 0;
for (std::size_t i = 0; i < m_ops; ++i) {
if (epoch == 0) {
setup();
epoch = kEpochOps;
}
--epoch;
const auto begin = Clock::now();
op();
const auto elapsed = Clock::now() - begin;
m_samples.push_back(
static_cast<double>(
std::chrono::duration_cast<
std::chrono::nanoseconds>(elapsed)
.count()));
}
}
}
[[nodiscard]] Stats stats() const
{
Stats out;
out.name = m_name;
out.samples = m_samples.size();
double total = 0;
for (const double sample : m_samples) {
total += sample;
}
out.mean_ns = m_samples.empty() ? 0 : total / m_samples.size();
double variance = 0;
for (const double sample : m_samples) {
const double delta = sample - out.mean_ns;
variance += delta * delta;
}
variance = m_samples.size() > 1
? variance / (m_samples.size() - 1)
: 0;
const double standard_error =
std::sqrt(variance / static_cast<double>(m_samples.size()));
out.ci95_low_ns = std::max(0.0, out.mean_ns - 1.96 * standard_error);
out.ci95_high_ns = out.mean_ns + 1.96 * standard_error;
out.p50_ns = percentile(m_samples, 50);
out.p95_ns = percentile(m_samples, 95);
out.p99_ns = percentile(m_samples, 99);
out.ops_per_sec =
out.mean_ns > 0 ? 1e9 / out.mean_ns : 0;
return out;
}
private:
static constexpr std::size_t kEpochOps = 32;
std::string m_name;
std::size_t m_reps;
std::size_t m_ops;
std::size_t m_warmup;
std::vector<double> m_samples;
};
struct Options {
bool quick{false};
std::string json_path{};
};
[[nodiscard]] Options parse_options(int argc, char** argv)
{
Options options;
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
if (arg == "--quick") {
options.quick = true;
} else if (arg == "--json" && i + 1 < argc) {
options.json_path = argv[++i];
}
}
return options;
}
[[nodiscard]] DistributedHost::ReplicatedKvCluster
fresh_cluster(std::string& leader)
{
DistributedHost::ReplicatedKvCluster cluster{{"a", "b", "c"}};
check(cluster.elect("a").has_value(), "elect leader");
leader = "a";
return cluster;
}
void append_json(std::string& out, const Stats& stats)
{
out += std::format(
" \"{}\": {{\"samples\": {}, \"p50_ns\": {:.2f}, "
"\"p95_ns\": {:.2f}, \"p99_ns\": {:.2f}, \"mean_ns\": {:.2f}, "
"\"ci95_ns\": [{:.2f}, {:.2f}], \"ops_per_sec\": {:.2f}}}",
stats.name, stats.samples, stats.p50_ns, stats.p95_ns, stats.p99_ns,
stats.mean_ns, stats.ci95_low_ns, stats.ci95_high_ns,
stats.ops_per_sec);
}
} // namespace
int main(int argc, char** argv)
{
using namespace DistributedHost;
const Options options = parse_options(argc, argv);
const std::size_t reps = options.quick ? 1 : 5;
const std::size_t ops = options.quick ? 16 : 200;
std::vector<Stats> results;
// ── replicated KV propose ─────────────────────────────────────────────
{
std::optional<ReplicatedKvCluster> cluster;
std::string leader;
std::uint64_t sequence = 0;
Bench bench{"kv_propose_3node", reps, ops};
bench.run(
[&] {
cluster = fresh_cluster(leader);
sequence = 0;
},
[&] {
const auto reply = cluster->propose(
leader, "key-" + std::to_string(sequence), std::string{"value"});
check(reply.outcome == KvWriteOutcome::Applied,
"propose is majority-committed");
++sequence;
});
results.push_back(bench.stats());
}
// ── replicated KV quorum read ────────────────────────────────────────
{
std::string leader;
auto cluster = fresh_cluster(leader);
check(cluster.propose(leader, "hot", std::string{"value"}).outcome ==
KvWriteOutcome::Applied,
"seed value");
Bench bench{"kv_quorum_read_3node", reps, ops * 5};
bench.run([] {}, [&] {
auto read = cluster.quorum_read(leader, "hot");
check(read.has_value() && read->has_value(), "quorum read");
});
results.push_back(bench.stats());
}
// ── replicated queue publish/claim/ack ───────────────────────────────
{
std::optional<ReplicatedKvCluster> cluster;
std::optional<ReplicatedQueue> queue;
std::uint64_t sequence = 0;
QueueConfig config;
config.max_jobs = 1000000;
Bench bench{"queue_publish_claim_ack_3node", reps, ops};
bench.run(
[&] {
std::string leader;
cluster = fresh_cluster(leader);
queue.emplace(*cluster, leader, config);
sequence = 0;
},
[&] {
const std::string key = "job-" + std::to_string(sequence++);
auto id = queue->publish("payload", key);
check(id.has_value(), "publish");
auto claimed = queue->claim("worker");
check(claimed.has_value() && claimed->has_value(), "claim");
check(queue->ack("worker", *id).has_value(), "ack");
});
results.push_back(bench.stats());
}
// ── HTTP fixture roundtrip ────────────────────────────────────────────
{
auto fixture = ClusterFixture::create();
check(fixture.has_value(), "fixture create");
check((*fixture)->start().has_value(), "fixture start");
const std::string url = (*fixture)->endpoint("a") + "/peer/health";
Void::Net::HttpClient client;
const std::vector<Void::Net::Header> headers{
Void::Net::Header{"authorization", "Bearer peer-secret"}};
Bench bench{"http_peer_health_roundtrip", reps, ops};
bench.run([] {}, [&] {
auto response = client.get(url, headers);
check(response.has_value() && response->status == 200,
"http health roundtrip");
});
results.push_back(bench.stats());
(*fixture)->stop();
}
for (const auto& stats : results) {
std::printf(
"%-28s samples=%-6zu p50=%10.1fns p95=%10.1fns p99=%10.1fns "
"mean=%10.1fns ci95=[%.1f, %.1f] %.0f ops/s\n",
stats.name.c_str(), stats.samples, stats.p50_ns, stats.p95_ns,
stats.p99_ns, stats.mean_ns, stats.ci95_low_ns, stats.ci95_high_ns,
stats.ops_per_sec);
}
if (!options.json_path.empty()) {
std::ofstream out{options.json_path};
check(out.is_open(), "open json output");
out << "{\n \"reps\": " << reps << ", \"ops_per_rep\": " << ops
<< ",\n \"cases\": {\n";
for (std::size_t i = 0; i < results.size(); ++i) {
std::string line;
append_json(line, results[i]);
out << line << (i + 1 == results.size() ? "\n" : ",\n");
}
out << " }\n}\n";
}
return 0;
}
@@ -0,0 +1,104 @@
#pragma once
#include "distributed_host/replicated_kv.hpp"
#include "distributed_host/replicated_queue.hpp"
#include <Void/Functional/Result.hpp>
#include <Void/Net/HttpServer.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <string_view>
#include <vector>
namespace DistributedHost
{
struct ClusterFixtureConfig {
/// Required bearer token for every peer and admin route.
std::string token{"peer-secret"};
std::size_t max_connections{8};
std::chrono::milliseconds shutdown_grace{
std::chrono::seconds{2}};
/// Queue policy shared by every node handler.
QueueConfig queue{};
/// Bounded recorded outbox deliveries.
std::size_t max_delivered{1024};
};
/// Three-node replicated KV reference over real loopback HTTP listeners.
///
/// Each voter owns one `Void::Net::HttpServer`. Peer routes drive the
/// deterministic replication core (elect, propose, read, heartbeat); an
/// authenticated admin route models partitions for crash/partition
/// histories. The transport is real; consensus timing is deterministic.
///
/// Routes (all require `Authorization: Bearer <token>`):
/// GET /peer/health role/term/commit/applied
/// POST /peer/elect become a candidate
/// PUT /peer/propose?key=K body = value
/// DELETE /peer/propose?key=K erase
/// GET /peer/read?key=K consistent quorum read
/// POST /peer/heartbeat replicate log and commit index
/// POST /admin/partition?node=X&partition=N
/// POST /admin/crash?node=X
/// POST /admin/restart?node=X
///
/// Replicated worker queue over the same group:
/// POST /queue/publish?key=K body = payload
/// POST /queue/claim?consumer=C
/// POST /queue/ack?consumer=C&id=J
/// POST /queue/nack?consumer=C&id=J body = reason
/// POST /queue/recover?consumer=C
/// POST /queue/dispatch deliver pending outbox effects
/// GET /queue/status?id=J
/// GET /queue/dlq
/// GET /queue/delivered
class ClusterFixture
{
public:
ClusterFixture(const ClusterFixture&) = delete;
ClusterFixture& operator=(const ClusterFixture&) = delete;
ClusterFixture(ClusterFixture&&) = delete;
ClusterFixture& operator=(ClusterFixture&&) = delete;
~ClusterFixture();
[[nodiscard]] static Void::Result::Result<
std::unique_ptr<ClusterFixture>>
create(ClusterFixtureConfig config = {});
/// Bind and start every listener. Construction alone opens none.
[[nodiscard]] Void::Result::Result<void> start();
/// Bounded, idempotent shutdown of every listener.
void stop() noexcept;
/// `http://127.0.0.1:<port>` for one voter, or an empty string
/// when it is unknown or not listening.
[[nodiscard]] std::string endpoint(std::string_view node) const;
[[nodiscard]] const std::vector<std::string>& voters() const noexcept;
private:
struct PeerServer {
std::string id;
std::unique_ptr<Void::Net::HttpServer> server;
};
explicit ClusterFixture(ClusterFixtureConfig config);
[[nodiscard]] Void::Result::Result<void>
register_routes(PeerServer& peer);
ClusterFixtureConfig m_config;
ReplicatedKvCluster m_cluster;
mutable std::mutex m_mutex;
std::vector<std::unique_ptr<PeerServer>> m_peers;
std::vector<std::string> m_delivered;
};
} // namespace DistributedHost
@@ -0,0 +1,190 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <string_view>
#include <vector>
namespace DistributedHost
{
using NodeId = std::string;
struct HostConfig {
std::string cluster{"cluster"};
NodeId self{"node-1"};
std::vector<NodeId> peers{};
/// Require an available leader path before reporting write readiness.
bool require_leader_readiness{true};
/// Optional discovery publication; disabled means no adapter call.
bool publish_discovery{true};
std::chrono::milliseconds startup_deadline{
std::chrono::seconds{5}};
};
/// Readiness is per capability, not a single boolean:
/// a follower may be live and readable while not accepting writes.
enum class Readiness : std::uint8_t {
Starting,
/// Process is live but no leader path is known: reads by explicit
/// policy only, never writes.
FollowerHealthy,
/// Leader path available and local state recovered.
WriteReady,
Stopping,
Stopped,
Failed
};
enum class Role : std::uint8_t { Follower, Candidate, Leader };
[[nodiscard]] constexpr std::string_view
readiness_name(Readiness readiness) noexcept
{
switch (readiness) {
case Readiness::Starting: return "starting";
case Readiness::FollowerHealthy: return "follower-healthy";
case Readiness::WriteReady: return "write-ready";
case Readiness::Stopping: return "stopping";
case Readiness::Stopped: return "stopped";
case Readiness::Failed: return "failed";
}
return "failed";
}
struct HealthSnapshot {
Readiness readiness{Readiness::Starting};
Role role{Role::Follower};
bool quorum_available{false};
std::size_t started_components{0};
std::string last_error;
};
/// Storage boundary owned by the Storage subsystem in the real platform.
/// Tests supply deterministic fakes; the host graph never implements it.
class StorageBackend
{
public:
virtual ~StorageBackend() = default;
[[nodiscard]] virtual Void::Result::Result<void> open() = 0;
[[nodiscard]] virtual Void::Result::Result<void> recover() = 0;
virtual void close() noexcept = 0;
};
/// Authenticated peer transport boundary.
class PeerTransport
{
public:
virtual ~PeerTransport() = default;
[[nodiscard]] virtual Void::Result::Result<void> listen() = 0;
[[nodiscard]] virtual Void::Result::Result<void>
connect_peers(const std::vector<NodeId>& peers) = 0;
virtual void close() noexcept = 0;
};
/// Replication adapter supplying role and leader availability.
class ReplicationAdapter
{
public:
virtual ~ReplicationAdapter() = default;
[[nodiscard]] virtual Void::Result::Result<void> start() = 0;
[[nodiscard]] virtual Role role() const noexcept = 0;
[[nodiscard]] virtual bool leader_available() const noexcept = 0;
virtual void stop() noexcept = 0;
};
/// Optional directory publication (Discovery). Failures are observation
/// failures, never quorum votes.
class DirectoryPublisher
{
public:
virtual ~DirectoryPublisher() = default;
[[nodiscard]] virtual Void::Result::Result<void>
publish(const NodeId& self) = 0;
virtual void withdraw() noexcept = 0;
};
/// Borrowed resources. The graph never owns or destroys them; they must
/// outlive the graph through final join.
struct HostResources {
StorageBackend* storage{nullptr};
PeerTransport* transport{nullptr};
ReplicationAdapter* replication{nullptr};
/// Optional: null disables discovery even when configured on.
DirectoryPublisher* directory{nullptr};
};
/// Single-node composition skeleton for the distributed reference host.
///
/// Startup is a dependency-ordered transaction: storage open/recover,
/// peer transport, replication, readiness, then optional discovery. A
/// failure unwinds started components in reverse order and preserves the
/// original error. Construction starts nothing.
class DistributedHostGraph
{
public:
DistributedHostGraph(const DistributedHostGraph&) = delete;
DistributedHostGraph& operator=(const DistributedHostGraph&) = delete;
DistributedHostGraph(DistributedHostGraph&& other) noexcept;
DistributedHostGraph& operator=(DistributedHostGraph&&) = delete;
~DistributedHostGraph();
[[nodiscard]] static Void::Result::Result<DistributedHostGraph>
compose(HostResources resources, HostConfig config = {});
[[nodiscard]] Void::Result::Result<void> start();
/// Stop external admission first, then components in reverse
/// startup order. Idempotent and never destroys borrowed
/// resources.
void stop() noexcept;
[[nodiscard]] HealthSnapshot health() const;
[[nodiscard]] Readiness readiness() const noexcept
{
return m_readiness;
}
/// Deterministic records used by tests and inspect: the exact
/// order of component lifecycle calls.
[[nodiscard]] const std::vector<std::string>& history() const noexcept
{
return m_history;
}
private:
DistributedHostGraph(HostResources resources, HostConfig config);
[[nodiscard]] Void::Result::Result<void> start_storage();
[[nodiscard]] Void::Result::Result<void> start_transport();
[[nodiscard]] Void::Result::Result<void> start_replication();
[[nodiscard]] Void::Result::Result<void> publish_directory();
/// Reverse-order unwind of everything recorded as started.
void unwind() noexcept;
void record(std::string step);
HostResources m_resources;
HostConfig m_config;
std::vector<std::string> m_history;
std::size_t m_started{0};
bool m_storage_open{false};
bool m_transport_live{false};
bool m_replication_started{false};
bool m_directory_published{false};
bool m_stopped{false};
Readiness m_readiness{Readiness::Starting};
std::string m_last_error;
};
} // namespace DistributedHost
@@ -0,0 +1,261 @@
#pragma once
#include "distributed_host/replicated_kv.hpp"
#include <Void/Functional/Result.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <map>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace DistributedHost
{
// ── Backup / restore ────────────────────────────────────────────────────
/// Stable cluster identity that a backup carries. A restore rehearsal must
/// retain it: restoring into a differently identified cluster would merge
/// unrelated histories.
struct ClusterIdentity {
std::string cluster;
std::vector<std::string> voters;
[[nodiscard]] bool operator==(const ClusterIdentity& other) const
{
return cluster == other.cluster &&
std::ranges::is_permutation(voters, other.voters);
}
};
struct ClusterBackup {
ClusterIdentity identity;
/// Commit index observed when the backup was captured.
std::uint64_t commit_index{0};
/// Quorum-confirmed applied state at that point.
std::map<std::string, std::string, std::less<>> state;
};
/// Capture a consistent backup from a quorum-confirmed leader.
[[nodiscard]] inline Void::Result::Result<ClusterBackup> capture_backup(
ReplicatedKvCluster& cluster, std::string_view leader,
ClusterIdentity identity)
{
auto snapshot = cluster.quorum_snapshot(leader);
if (!snapshot) {
return std::unexpected{std::move(snapshot).error()};
}
ClusterBackup backup;
backup.identity = std::move(identity);
backup.commit_index = cluster.committed_index();
backup.state = std::move(*snapshot);
return backup;
}
/// Restore a backup into an empty, separately identified cluster.
///
/// The target identity must match the backup exactly. Every entry is
/// written through the leader and must be majority-committed; a failed
/// write stops the restore with the partial state left visible.
[[nodiscard]] inline Void::Result::Result<std::size_t> restore_backup(
ReplicatedKvCluster& cluster, std::string_view leader,
const ClusterBackup& backup, const ClusterIdentity& target)
{
if (!(backup.identity == target)) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"Restore: cluster identity does not match the backup"}};
}
std::size_t restored = 0;
for (const auto& [key, value] : backup.state) {
const KvWriteReply reply = cluster.propose(leader, key, value);
if (reply.outcome != KvWriteOutcome::Applied) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::exhausted,
"Restore: entry was not majority-committed"}};
}
++restored;
}
return restored;
}
// ── Trust rotation ──────────────────────────────────────────────────────
struct TrustGeneration {
std::uint64_t id{0};
std::vector<std::string> fingerprints;
};
/// Overlapping trust generations for credential rotation.
///
/// Rotation validates the new generation while the old one stays trusted,
/// so live connections drain without ever disabling verification. An empty
/// trust set trusts nothing (fail closed).
class TrustStore
{
public:
explicit TrustStore(std::vector<std::string> initial_fingerprints = {})
{
if (!initial_fingerprints.empty()) {
m_generations.push_back(
TrustGeneration{m_next_id++, std::move(initial_fingerprints)});
}
}
[[nodiscard]] bool trusted(std::string_view fingerprint) const noexcept
{
if (fingerprint.empty()) {
return false;
}
for (const auto& generation : m_generations) {
if (std::ranges::find(generation.fingerprints, fingerprint) !=
generation.fingerprints.end()) {
return true;
}
}
return false;
}
/// Add a new trusted generation while keeping the old ones.
/// Returns the new generation id.
[[nodiscard]] Void::Result::Result<std::uint64_t>
begin_rotation(std::vector<std::string> new_fingerprints)
{
if (new_fingerprints.empty()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"TrustStore: a rotation needs at least one fingerprint"}};
}
m_generations.push_back(
TrustGeneration{m_next_id++, std::move(new_fingerprints)});
return m_generations.back().id;
}
/// Revoke every generation older than `generation` after the
/// overlap drained. The chosen generation must be active.
[[nodiscard]] Void::Result::Result<void>
complete_rotation(std::uint64_t generation)
{
const auto found = std::ranges::find_if(
m_generations, [generation](const TrustGeneration& candidate) {
return candidate.id == generation;
});
if (found == m_generations.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"TrustStore: unknown trust generation"}};
}
std::erase_if(m_generations,
[generation](const TrustGeneration& candidate) {
return candidate.id < generation;
});
return {};
}
[[nodiscard]] std::size_t active_generations() const noexcept
{
return m_generations.size();
}
private:
std::vector<TrustGeneration> m_generations;
std::uint64_t m_next_id{1};
};
// ── Mixed-version rollout ──────────────────────────────────────────────
struct VersionPolicy {
/// Format version this binary writes.
std::uint32_t format_version{2};
/// Oldest node version that can still read existing durable data.
std::uint32_t min_reader{1};
};
/// Per-voter version advertisement gate.
///
/// Readers may roll out first (every node must still read the durable
/// format), and a new command is admitted only when every voter
/// advertises support. Unknown voters are rejected rather than assumed
/// current.
class RolloutGate
{
public:
RolloutGate(std::vector<std::string> voters, VersionPolicy policy)
: m_policy(policy)
{
for (auto& voter : voters) {
m_advertised.emplace(std::move(voter), 0);
}
}
[[nodiscard]] Void::Result::Result<void>
report_version(std::string_view node, std::uint32_t version)
{
const auto found = m_advertised.find(node);
if (found == m_advertised.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"RolloutGate: unknown voter"}};
}
found->second = version;
return {};
}
[[nodiscard]] Void::Result::Result<void>
admit_read(std::string_view node) const
{
const auto found = m_advertised.find(node);
if (found == m_advertised.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"RolloutGate: unknown voter"}};
}
if (found->second < m_policy.min_reader) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::unsupported,
"RolloutGate: node cannot read the durable format"}};
}
return {};
}
/// A new command requires every voter to advertise it.
[[nodiscard]] Void::Result::Result<void>
admit_new_command(std::string_view node) const
{
if (m_advertised.find(node) == m_advertised.end()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::not_found,
"RolloutGate: unknown voter"}};
}
for (const auto& [id, version] : m_advertised) {
(void)id;
if (version < m_policy.format_version) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::unsupported,
"RolloutGate: not every voter advertises the new "
"command"}};
}
}
return {};
}
[[nodiscard]] bool all_advertised() const noexcept
{
return std::ranges::all_of(
m_advertised, [this](const auto& entry) {
return entry.second >= m_policy.format_version;
});
}
private:
VersionPolicy m_policy;
std::map<std::string, std::uint32_t, std::less<>> m_advertised;
};
} // namespace DistributedHost
@@ -0,0 +1,163 @@
#pragma once
#include "distributed_host/replicated_kv.hpp"
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <string>
#include <string_view>
#include <vector>
namespace DistributedHost
{
/// Half-open key range `[start, end)`.
struct KeyRange {
std::string start;
std::string end;
[[nodiscard]] bool contains(std::string_view key) const noexcept
{
return key >= start && key < end;
}
[[nodiscard]] bool valid() const noexcept { return start < end; }
[[nodiscard]] bool operator==(const KeyRange&) const noexcept = default;
};
struct RangeOwnership {
KeyRange range;
std::string owner;
[[nodiscard]] bool operator==(const RangeOwnership&) const noexcept =
default;
};
enum class MovePhase : std::uint8_t {
None,
/// Writes for the range are rejected; reads stay with the source.
Frozen,
/// The target reported a complete verified copy; completing is safe.
Verified,
Completed,
Aborted
};
[[nodiscard]] std::string_view move_phase_name(MovePhase phase) noexcept;
struct MoveRecord {
std::uint64_t id{0};
KeyRange range;
std::string source;
std::string target;
MovePhase phase{MovePhase::None};
std::size_t transferred{0};
std::string note;
};
/// Range ownership, freeze-based movement and replicated directory
/// persistence.
///
/// Invariants:
/// * ranges never overlap and every range has exactly one owner;
/// * a range being moved rejects writes (reads remain with the source);
/// * ownership switches only after the target's copy is verified;
/// * crash recovery is deterministic: a verified move rolls forward,
/// anything earlier rolls back, so ownership is never ambiguous.
///
/// Not thread-safe: the host serializes directory operations.
class RangeDirectory
{
public:
explicit RangeDirectory(std::vector<std::string> voters);
[[nodiscard]] const std::vector<std::string>& voters() const noexcept
{
return m_voters;
}
[[nodiscard]] Void::Result::Result<void>
assign(KeyRange range, std::string owner);
[[nodiscard]] Void::Result::Result<std::string>
owner_of(std::string_view key) const;
[[nodiscard]] std::vector<RangeOwnership> ranges() const;
// ── movement ────────────────────────────────────────────────────
[[nodiscard]] Void::Result::Result<std::uint64_t>
begin_move(KeyRange range, std::string target);
/// Record entries copied to the target. Idempotent while frozen.
[[nodiscard]] Void::Result::Result<void>
transfer(std::uint64_t move_id, std::size_t entries);
/// The target certifies a complete copy of `entries` entries.
[[nodiscard]] Void::Result::Result<void>
verify(std::uint64_t move_id, std::size_t entries);
[[nodiscard]] Void::Result::Result<void> complete(std::uint64_t move_id);
void abort(std::uint64_t move_id, std::string reason) noexcept;
/// Write admission: rejected while the covering range is moving.
[[nodiscard]] Void::Result::Result<void>
admit_write(std::string_view key) const;
/// Reads stay with the source owner until completion.
[[nodiscard]] Void::Result::Result<void>
admit_read(std::string_view key) const;
// ── crash recovery ─────────────────────────────────────────────
enum class Recovery : std::uint8_t {
None,
RolledForward,
RolledBack
};
/// Resolve an interrupted move after a crash: verified copies are
/// completed, anything earlier is aborted.
[[nodiscard]] Void::Result::Result<Recovery>
recover(std::uint64_t move_id);
[[nodiscard]] Void::Result::Result<MoveRecord>
move(std::uint64_t move_id) const;
// ── replicated directory persistence ───────────────────────────
/// Largest number of directory bytes accepted on load.
static constexpr std::size_t max_directory_bytes = 64ULL * 1024ULL;
[[nodiscard]] Void::Result::Result<void>
persist(ReplicatedKvCluster& cluster, std::string_view leader,
std::string_view key = default_key);
/// Replace the local directory from the replicated state. The
/// loaded map is fully validated before it is installed.
[[nodiscard]] Void::Result::Result<void>
load(ReplicatedKvCluster& cluster, std::string_view leader,
std::string_view key = default_key);
inline static constexpr std::string_view default_key =
"__range_directory";
private:
struct ActiveMove {
MoveRecord record;
};
[[nodiscard]] bool known_voter(std::string_view owner) const;
[[nodiscard]] const ActiveMove* active_for(const KeyRange& range) const;
[[nodiscard]] ActiveMove* mutable_move(std::uint64_t move_id);
[[nodiscard]] std::string encode() const;
std::vector<std::string> m_voters;
std::map<std::string, RangeOwnership, std::less<>> m_ranges;
std::map<std::uint64_t, ActiveMove> m_moves;
std::uint64_t m_next_move{1};
};
} // namespace DistributedHost
@@ -0,0 +1,157 @@
#pragma once
#include "distributed_host/host_graph.hpp"
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace DistributedHost
{
/// One replicated log entry. A missing value is an erase.
struct KvLogEntry {
std::uint64_t term{0};
std::uint64_t index{0};
std::string key;
std::optional<std::string> value;
};
enum class KvWriteOutcome : std::uint8_t {
/// Majority-committed and applied: the only durable reply.
Applied,
/// The entry may exist locally but no majority acknowledged it. It is
/// not durable and a later leader may overwrite it.
NoQuorum,
NotLeader,
NodeDown
};
struct KvWriteReply {
KvWriteOutcome outcome{KvWriteOutcome::NoQuorum};
std::uint64_t index{0};
std::uint64_t term{0};
};
/// Immutable inspection copy of one voter.
struct KvNodeSnapshot {
std::string id;
bool alive{true};
Role role{Role::Follower};
std::uint64_t term{0};
std::uint64_t commit_index{0};
std::uint64_t applied_index{0};
std::size_t log_size{0};
std::optional<std::string> leader;
std::map<std::string, std::string, std::less<>> kv;
};
/// Deterministic single-group replicated key-value cluster.
///
/// Models the safety rules the reference distributed KV depends on
/// without sockets, threads or clocks:
/// * a write is replied Applied only after a majority of matching acks
/// (durable reply), never on local append alone;
/// * a leader in a minority cannot commit and is stepped down when it
/// observes a higher term;
/// * a consistent read is served only by a leader that confirms a
/// majority in its term and has applied every committed entry;
/// * committed entries survive crash/restart and are never overwritten.
///
/// The simulator is single-threaded; tests drive elections, proposals,
/// partitions and crashes explicitly.
class ReplicatedKvCluster
{
public:
explicit ReplicatedKvCluster(std::vector<std::string> voters);
[[nodiscard]] const std::vector<std::string>& voters() const noexcept
{
return m_voters;
}
/// Request a majority election for `candidate` in a new term.
/// Fails without changing the cluster when no majority is
/// reachable.
[[nodiscard]] Void::Result::Result<void>
elect(std::string_view candidate);
/// Append and replicate one command through `leader`. The reply is
/// Applied only when a majority acknowledged the matching entry.
[[nodiscard]] KvWriteReply propose(std::string_view leader,
std::string key,
std::optional<std::string> value);
/// Replicate the leader's log and commit index without appending a
/// new command (the AppendEntries heartbeat). Followers in a newer
/// term step the leader down.
[[nodiscard]] Void::Result::Result<void>
heartbeat(std::string_view leader);
/// Linearizable read: leader-only, majority-confirmed in the
/// leader's term, after applying every committed entry.
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
quorum_read(std::string_view node, std::string_view key);
/// Quorum-confirmed copy of the leader's applied state. Used by
/// compositions that must enumerate keys (e.g. the worker queue).
[[nodiscard]] Void::Result::Result<
std::map<std::string, std::string, std::less<>>>
quorum_snapshot(std::string_view node);
/// Crash/restart keep the durable log, term and vote.
void crash(std::string_view node);
void restart(std::string_view node);
/// Move a node to a partition id. Nodes only communicate within
/// the same partition id.
void set_partition(std::string_view node, int partition);
[[nodiscard]] std::optional<KvNodeSnapshot>
snapshot(std::string_view node) const;
/// Highest commit index across live nodes.
[[nodiscard]] std::uint64_t committed_index() const;
private:
struct Node {
std::string id;
bool alive{true};
int partition{0};
Role role{Role::Follower};
std::uint64_t term{0};
std::optional<std::string> voted_for;
std::optional<std::string> leader;
std::vector<KvLogEntry> log;
std::uint64_t commit_index{0};
std::uint64_t applied_index{0};
std::map<std::string, std::string, std::less<>> kv;
};
[[nodiscard]] Node* find(std::string_view id);
[[nodiscard]] const Node* find(std::string_view id) const;
[[nodiscard]] bool reachable(const Node& a, const Node& b) const;
[[nodiscard]] bool majority(std::size_t acks) const;
/// True when `candidate` has a log at least as up to date as `voter`.
[[nodiscard]] static bool log_up_to_date(const Node& candidate,
const Node& voter);
void apply_committed(Node& node);
/// Majority-confirm `node` as leader in its term, then apply pending
/// committed entries. Shared by quorum reads and snapshots.
[[nodiscard]] Void::Result::Result<void>
confirm_leader(Node& node);
/// Copy the leader's log to one reachable follower. False when the
/// follower cannot be brought in line (e.g. it is in a newer term).
[[nodiscard]] bool replicate_to(Node& leader, Node& follower);
std::vector<std::string> m_voters;
std::vector<Node> m_nodes;
};
} // namespace DistributedHost
@@ -0,0 +1,119 @@
#pragma once
#include "distributed_host/replicated_kv.hpp"
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <string_view>
#include <vector>
namespace DistributedHost
{
enum class JobState : std::uint8_t {
Pending,
InFlight,
Done,
Dead
};
[[nodiscard]] std::string_view job_state_name(JobState state) noexcept;
struct QueueJob {
std::string id;
std::string payload;
JobState state{JobState::Pending};
std::uint32_t attempts{0};
std::string consumer;
/// Set when the acknowledged effect still needs external
/// delivery (the outbox).
bool outbox_pending{false};
std::string reason;
};
struct QueueConfig {
std::uint32_t max_attempts{3};
std::size_t max_jobs{1024};
std::size_t max_payload_bytes{64ULL * 1024ULL};
};
/// Consumer-side effect delivery for dispatched outbox entries.
using OutboxSink = std::function<void(const QueueJob&)>;
/// Worker-queue reference backed by one replicated KV group.
///
/// Semantics are at-least-once by contract:
/// * `publish` is idempotent by caller key and replies only after the
/// record is majority-committed; a lost reply is retried with the
/// same key;
/// * `claim` leases one job to a consumer (attempts incremented);
/// * `ack` records the inbox outcome and the outbox entry in one
/// replicated job record, so a redelivered ack cannot duplicate the
/// effect;
/// * `nack` requeues or dead-letters after `max_attempts`;
/// * `recover_consumer` requeues or dead-letters a crashed
/// consumer's in-flight jobs;
/// * `dispatch_outbox` delivers effects externally. A crash between
/// delivery and marking duplicates the effect: consumers must dedup
/// on the job id.
class ReplicatedQueue
{
public:
ReplicatedQueue(ReplicatedKvCluster& cluster, std::string leader,
QueueConfig config = {});
[[nodiscard]] Void::Result::Result<std::string>
publish(std::string payload, std::string idempotency_key);
[[nodiscard]] Void::Result::Result<std::optional<QueueJob>>
claim(std::string_view consumer);
[[nodiscard]] Void::Result::Result<void>
ack(std::string_view consumer, std::string_view job_id);
[[nodiscard]] Void::Result::Result<QueueJob>
nack(std::string_view consumer, std::string_view job_id,
std::string reason);
/// Requeue (or dead-letter) every in-flight job of a crashed
/// consumer. Returns the affected count.
[[nodiscard]] Void::Result::Result<std::size_t>
recover_consumer(std::string_view consumer);
/// Deliver pending outbox effects and mark them delivered.
/// Returns the delivered count.
[[nodiscard]] Void::Result::Result<std::size_t>
dispatch_outbox(const OutboxSink& sink);
[[nodiscard]] Void::Result::Result<std::vector<QueueJob>>
dead_letters();
[[nodiscard]] Void::Result::Result<QueueJob>
status(std::string_view job_id);
/// The leader endpoint used for every replicated operation.
void set_leader(std::string leader)
{
m_leader = std::move(leader);
}
private:
[[nodiscard]] static std::string key_for(std::string_view id);
[[nodiscard]] Void::Result::Result<void>
store(const QueueJob& job);
[[nodiscard]] Void::Result::Result<std::optional<QueueJob>>
load(std::string_view job_id);
[[nodiscard]] Void::Result::Result<
std::vector<std::pair<std::string, QueueJob>>>
all_jobs();
ReplicatedKvCluster& m_cluster;
std::string m_leader;
QueueConfig m_config;
};
} // namespace DistributedHost
@@ -0,0 +1,161 @@
#pragma once
#include "distributed_host/host_graph.hpp"
#include <Void/Net/HttpServer.hpp>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <string_view>
#include <vector>
namespace DistributedHost
{
/// Validated single-node configuration. Construction opens nothing.
struct SingleNodeConfig {
std::string peer_address{"127.0.0.1:0"};
/// Required peer credential; an empty token fails closed.
std::string peer_token{};
std::chrono::milliseconds shutdown_grace{
std::chrono::seconds{5}};
std::size_t max_connections{16};
std::size_t max_append_bytes{64ULL * 1024ULL};
/// Bounded retained peer log entries.
std::size_t max_log_entries{1024};
[[nodiscard]] Void::Result::Result<void> validate() const;
};
/// Bounded in-memory replicated log served by the peer fixture. The
/// single-node composition owns it; durable storage arrives with the
/// multi-node reference in a later task.
class PeerLog
{
public:
explicit PeerLog(std::size_t max_entries = 1024);
/// Append one opaque entry. Returns the assigned index (1-based).
[[nodiscard]] Void::Result::Result<std::uint64_t>
append(std::string entry);
[[nodiscard]] std::size_t size() const;
[[nodiscard]] std::uint64_t last_index() const;
private:
mutable std::mutex m_mutex;
std::size_t m_max_entries;
std::vector<std::string> m_entries;
};
/// Real authenticated peer transport over Void::Net::HttpServer.
///
/// Routes: `GET /peer/health` (bounded status, no secrets) and
/// `POST /peer/append` (bearer-authenticated, bounded body). A missing or
/// empty configured token rejects every request.
class HttpPeerTransport final : public PeerTransport
{
public:
HttpPeerTransport(std::string address, std::string token,
PeerLog& log, std::size_t max_connections,
std::size_t max_append_bytes);
~HttpPeerTransport() noexcept override;
HttpPeerTransport(const HttpPeerTransport&) = delete;
HttpPeerTransport& operator=(const HttpPeerTransport&) = delete;
[[nodiscard]] Void::Result::Result<void> listen() override;
[[nodiscard]] Void::Result::Result<void>
connect_peers(const std::vector<NodeId>& peers) override;
void close() noexcept override;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::size_t connected_peers() const noexcept
{
return m_connected_peers;
}
private:
[[nodiscard]] bool authorized(const Void::Net::ServerRequest& req)
const noexcept;
std::string m_address;
std::string m_token;
PeerLog& m_log;
std::size_t m_max_connections;
std::size_t m_max_append_bytes;
std::size_t m_connected_peers{0};
std::unique_ptr<Void::Net::HttpServer> m_server{};
};
/// Single-node replication adapter: a sole voter is always the leader
/// while started. Multi-node election belongs to the Coordination plan.
class SingleNodeReplication final : public ReplicationAdapter
{
public:
[[nodiscard]] Void::Result::Result<void> start() override;
[[nodiscard]] Role role() const noexcept override
{
return m_running ? Role::Leader : Role::Follower;
}
[[nodiscard]] bool leader_available() const noexcept override
{
return m_running;
}
void stop() noexcept override { m_running = false; }
private:
bool m_running{false};
};
/// Single-node reference composition: the host graph wired with the
/// authenticated HTTP peer fixture and a leader-available replication
/// adapter. Startup is bounded and rolls back in reverse order.
class SingleNodeHost
{
public:
SingleNodeHost(const SingleNodeHost&) = delete;
SingleNodeHost& operator=(const SingleNodeHost&) = delete;
/// Movable: every component the host graph points at is heap-owned,
/// so a move transfers ownership without changing addresses.
SingleNodeHost(SingleNodeHost&&) noexcept = default;
SingleNodeHost& operator=(SingleNodeHost&&) noexcept = default;
~SingleNodeHost();
[[nodiscard]] static Void::Result::Result<SingleNodeHost>
create(SingleNodeConfig config);
[[nodiscard]] Void::Result::Result<void> start();
void stop() noexcept;
[[nodiscard]] HealthSnapshot health() const;
[[nodiscard]] std::uint16_t peer_port() const noexcept;
[[nodiscard]] const std::vector<std::string>& history() const noexcept;
private:
struct NoopStorage final : StorageBackend {
Void::Result::Result<void> open() override { return {}; }
Void::Result::Result<void> recover() override { return {}; }
void close() noexcept override {}
};
explicit SingleNodeHost(SingleNodeConfig config);
SingleNodeConfig m_config;
std::unique_ptr<PeerLog> m_log;
std::unique_ptr<NoopStorage> m_storage;
std::unique_ptr<HttpPeerTransport> m_transport;
std::unique_ptr<SingleNodeReplication> m_replication;
std::unique_ptr<DistributedHostGraph> m_graph;
};
} // namespace DistributedHost
@@ -0,0 +1,610 @@
#include "distributed_host/cluster_fixture.hpp"
#include <charconv>
#include <format>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
namespace DistributedHost
{
namespace
{
[[nodiscard]] Void::Net::ServerResponse text_response(int status,
std::string body)
{
Void::Net::ServerResponse response;
response.status = static_cast<std::uint16_t>(status);
response.headers.push_back(
Void::Net::Header{"content-type", "text/plain; charset=utf-8"});
response.headers.push_back(
Void::Net::Header{"cache-control", "no-store"});
response.body = std::move(body);
return response;
}
[[nodiscard]] int status_for(const Void::Result::Error& error) noexcept
{
using Kind = Void::Result::ErrorKind;
switch (error.kind()) {
case Kind::invalid_argument: return 400;
case Kind::not_found: return 404;
case Kind::conflict: return 409;
case Kind::overloaded: return 503;
case Kind::timeout: return 504;
default: return 500;
}
}
[[nodiscard]] bool authorized(const Void::Net::ServerRequest& request,
std::string_view token) noexcept
{
if (token.empty()) {
return false;
}
const auto header = request.header("authorization");
if (!header) {
return false;
}
constexpr std::string_view scheme{"bearer "};
if (header->size() <= scheme.size()) {
return false;
}
const std::string_view word = header->substr(0, scheme.size() - 1);
if (!(word == "Bearer" || word == "bearer") ||
(*header)[scheme.size() - 1] != ' ') {
return false;
}
return header->substr(scheme.size()) == token;
}
[[nodiscard]] std::optional<std::string_view>
query_value(std::string_view query, std::string_view name) noexcept
{
std::size_t pos = 0;
while (pos <= query.size()) {
const std::size_t amp = query.find('&', pos);
const std::string_view pair = query.substr(
pos, amp == std::string_view::npos ? std::string_view::npos
: amp - pos);
const std::size_t equals = pair.find('=');
const std::string_view key = pair.substr(0, equals);
if (key == name) {
return equals == std::string_view::npos
? std::string_view{}
: pair.substr(equals + 1);
}
if (amp == std::string_view::npos) {
break;
}
pos = amp + 1;
}
return std::nullopt;
}
[[nodiscard]] std::string_view role_name(Role role) noexcept
{
switch (role) {
case Role::Leader: return "leader";
case Role::Candidate: return "candidate";
case Role::Follower: return "follower";
}
return "follower";
}
[[nodiscard]] std::string_view
outcome_name(KvWriteOutcome outcome) noexcept
{
switch (outcome) {
case KvWriteOutcome::Applied: return "applied";
case KvWriteOutcome::NoQuorum: return "no-quorum";
case KvWriteOutcome::NotLeader: return "not-leader";
case KvWriteOutcome::NodeDown: return "node-down";
}
return "no-quorum";
}
[[nodiscard]] int outcome_status(KvWriteOutcome outcome) noexcept
{
switch (outcome) {
case KvWriteOutcome::Applied: return 200;
case KvWriteOutcome::NotLeader: return 409;
case KvWriteOutcome::NoQuorum: return 503;
case KvWriteOutcome::NodeDown: return 503;
}
return 503;
}
} // namespace
ClusterFixture::ClusterFixture(ClusterFixtureConfig config)
: m_config(std::move(config)), m_cluster({"a", "b", "c"})
{
}
ClusterFixture::~ClusterFixture()
{
stop();
}
Void::Result::Result<std::unique_ptr<ClusterFixture>>
ClusterFixture::create(ClusterFixtureConfig config)
{
if (config.token.empty()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"ClusterFixture: a peer token is required (fail closed)"}};
}
auto fixture = std::unique_ptr<ClusterFixture>{
new ClusterFixture{std::move(config)}};
for (const auto& id : fixture->m_cluster.voters()) {
auto peer = std::make_unique<PeerServer>();
peer->id = id;
Void::Net::HttpServerOptions options;
options.bind_host = "127.0.0.1";
options.port = 0;
options.max_concurrent_connections =
fixture->m_config.max_connections;
peer->server = std::make_unique<Void::Net::HttpServer>(options);
if (auto routes = fixture->register_routes(*peer); !routes) {
return std::unexpected{std::move(routes).error()};
}
fixture->m_peers.push_back(std::move(peer));
}
return fixture;
}
Void::Result::Result<void>
ClusterFixture::register_routes(PeerServer& peer)
{
const std::string id = peer.id;
Void::Net::HttpServer& server = *peer.server;
const std::string token = m_config.token;
auto guarded = [this, token](
const Void::Net::ServerRequest& request)
-> std::optional<Void::Net::ServerResponse> {
if (!authorized(request, token)) {
return text_response(401, "unauthorized");
}
return std::nullopt;
};
auto add = [&](Void::Net::Method method, const char* pattern, auto fn)
-> Void::Result::Result<void> {
return server.add_route(
method, pattern,
[this, id, pattern, fn, guarded](
const Void::Net::ServerRequest& request)
-> Void::Net::RouteResult {
if (auto denied = guarded(request)) {
return Void::Result::ok(std::move(*denied));
}
std::lock_guard lock{m_mutex};
return Void::Result::ok(fn(id, request, *this));
});
};
auto registered = add(
Void::Net::Method::Get, "/peer/health",
[](const std::string& self,
const Void::Net::ServerRequest&,
ClusterFixture& fixture) {
const auto state = fixture.m_cluster.snapshot(self);
if (!state) {
return text_response(404, "unknown node");
}
return text_response(
200,
std::format(
"id={} role={} term={} commit={} applied={} alive={}",
state->id, role_name(state->role), state->term,
state->commit_index, state->applied_index,
state->alive ? "true" : "false"));
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/peer/elect",
[](const std::string& self,
const Void::Net::ServerRequest&,
ClusterFixture& fixture) {
auto elected = fixture.m_cluster.elect(self);
if (!elected) {
return text_response(status_for(elected.error()),
elected.error().message());
}
return text_response(200, "elected");
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/peer/heartbeat",
[](const std::string& self,
const Void::Net::ServerRequest&,
ClusterFixture& fixture) {
auto beat = fixture.m_cluster.heartbeat(self);
if (!beat) {
return text_response(status_for(beat.error()),
beat.error().message());
}
return text_response(200, "ok");
});
if (!registered) {
return registered;
}
auto propose = [](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture,
std::optional<std::string> value) {
const auto key = query_value(request.query, "key");
if (!key || key->empty()) {
return text_response(400, "key required");
}
const KvWriteReply reply = fixture.m_cluster.propose(
self, std::string{*key}, std::move(value));
return text_response(
outcome_status(reply.outcome),
std::format("{} index={} term={}", outcome_name(reply.outcome),
reply.index, reply.term));
};
registered = add(
Void::Net::Method::Put, "/peer/propose",
[propose](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
return propose(self, request, fixture,
std::optional<std::string>{request.body});
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Delete, "/peer/propose",
[propose](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
return propose(self, request, fixture, std::nullopt);
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Get, "/peer/read",
[](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto key = query_value(request.query, "key");
if (!key || key->empty()) {
return text_response(400, "key required");
}
auto read =
fixture.m_cluster.quorum_read(self, *key);
if (!read) {
return text_response(status_for(read.error()),
read.error().message());
}
if (!read->has_value()) {
return text_response(404, "not found");
}
return text_response(200, **read);
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/admin/partition",
[](const std::string&,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto node = query_value(request.query, "node");
const auto partition = query_value(request.query, "partition");
if (!node || !partition) {
return text_response(400, "node and partition required");
}
unsigned int value = 0;
const auto parsed = std::from_chars(
partition->data(), partition->data() + partition->size(),
value);
if (parsed.ec != std::errc{}) {
return text_response(400, "invalid partition");
}
fixture.m_cluster.set_partition(*node,
static_cast<int>(value));
return text_response(200, "ok");
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/admin/crash",
[](const std::string&,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto node = query_value(request.query, "node");
if (!node) {
return text_response(400, "node required");
}
fixture.m_cluster.crash(*node);
return text_response(200, "ok");
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/admin/restart",
[](const std::string&,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto node = query_value(request.query, "node");
if (!node) {
return text_response(400, "node required");
}
fixture.m_cluster.restart(*node);
return text_response(200, "ok");
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/queue/publish",
[](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto key = query_value(request.query, "key");
if (!key || key->empty()) {
return text_response(400, "key required");
}
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto id = queue.publish(request.body, std::string{*key});
if (!id) {
return text_response(status_for(id.error()),
id.error().message());
}
return text_response(200, "job=" + *id);
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/queue/claim",
[](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto consumer = query_value(request.query, "consumer");
if (!consumer) {
return text_response(400, "consumer required");
}
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto claimed = queue.claim(*consumer);
if (!claimed) {
return text_response(status_for(claimed.error()),
claimed.error().message());
}
if (!claimed->has_value()) {
return text_response(204, "");
}
return text_response(
200,
std::format("job={} payload={} attempts={}",
(**claimed).id, (**claimed).payload,
(**claimed).attempts));
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/queue/ack",
[](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto consumer = query_value(request.query, "consumer");
const auto id = query_value(request.query, "id");
if (!consumer || !id) {
return text_response(400, "consumer and id required");
}
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto acknowledged = queue.ack(*consumer, *id);
if (!acknowledged) {
return text_response(status_for(acknowledged.error()),
acknowledged.error().message());
}
return text_response(200, "done");
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/queue/nack",
[](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto consumer = query_value(request.query, "consumer");
const auto id = query_value(request.query, "id");
if (!consumer || !id) {
return text_response(400, "consumer and id required");
}
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto rejected = queue.nack(*consumer, *id, request.body);
if (!rejected) {
return text_response(status_for(rejected.error()),
rejected.error().message());
}
return text_response(
200, std::format("state={} attempts={}",
job_state_name(rejected->state),
rejected->attempts));
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/queue/recover",
[](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto consumer = query_value(request.query, "consumer");
if (!consumer) {
return text_response(400, "consumer required");
}
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto recovered = queue.recover_consumer(*consumer);
if (!recovered) {
return text_response(status_for(recovered.error()),
recovered.error().message());
}
return text_response(200,
"recovered=" + std::to_string(*recovered));
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Post, "/queue/dispatch",
[](const std::string& self, const Void::Net::ServerRequest&,
ClusterFixture& fixture) {
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto dispatched = queue.dispatch_outbox(
[&fixture](const QueueJob& job) {
if (fixture.m_delivered.size() <
fixture.m_config.max_delivered) {
fixture.m_delivered.push_back(job.id);
}
});
if (!dispatched) {
return text_response(status_for(dispatched.error()),
dispatched.error().message());
}
return text_response(200,
"delivered=" + std::to_string(*dispatched));
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Get, "/queue/status",
[](const std::string& self,
const Void::Net::ServerRequest& request,
ClusterFixture& fixture) {
const auto id = query_value(request.query, "id");
if (!id) {
return text_response(400, "id required");
}
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto job = queue.status(*id);
if (!job) {
return text_response(status_for(job.error()),
job.error().message());
}
return text_response(
200, std::format("state={} attempts={} outbox={} reason={}",
job_state_name(job->state), job->attempts,
job->outbox_pending ? 1 : 0, job->reason));
});
if (!registered) {
return registered;
}
registered = add(
Void::Net::Method::Get, "/queue/dlq",
[](const std::string& self, const Void::Net::ServerRequest&,
ClusterFixture& fixture) {
ReplicatedQueue queue{fixture.m_cluster, self,
fixture.m_config.queue};
auto dead = queue.dead_letters();
if (!dead) {
return text_response(status_for(dead.error()),
dead.error().message());
}
std::string body;
for (const auto& job : *dead) {
body += std::format("id={} attempts={} reason={}\n",
job.id, job.attempts, job.reason);
}
return text_response(200, std::move(body));
});
if (!registered) {
return registered;
}
return add(
Void::Net::Method::Get, "/queue/delivered",
[](const std::string&, const Void::Net::ServerRequest&,
ClusterFixture& fixture) {
std::string body;
for (const auto& id : fixture.m_delivered) {
body += id;
body += '\n';
}
return text_response(200, std::move(body));
});
}
Void::Result::Result<void> ClusterFixture::start()
{
std::size_t started = 0;
for (auto& peer : m_peers) {
if (auto listening = peer->server->start(); !listening) {
for (std::size_t i = 0; i < started; ++i) {
m_peers[i]->server->shutdown(m_config.shutdown_grace);
}
return listening;
}
++started;
}
return {};
}
void ClusterFixture::stop() noexcept
{
for (auto& peer : m_peers) {
if (peer->server) {
peer->server->shutdown(m_config.shutdown_grace);
peer->server.reset();
}
}
}
std::string ClusterFixture::endpoint(std::string_view node) const
{
for (const auto& peer : m_peers) {
if (peer->id == node && peer->server &&
peer->server->bound_port() != 0) {
return "http://127.0.0.1:" +
std::to_string(peer->server->bound_port());
}
}
return {};
}
const std::vector<std::string>& ClusterFixture::voters() const noexcept
{
return m_cluster.voters();
}
} // namespace DistributedHost
@@ -0,0 +1,299 @@
#include "distributed_host/host_graph.hpp"
#include <string>
#include <utility>
namespace DistributedHost
{
namespace
{
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{
Void::Result::ErrorKind::invalid_argument, std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] Void::Result::Error unready(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::timeout,
std::move(message)};
}
[[nodiscard]] std::string validate(const HostConfig& config)
{
if (config.cluster.empty()) {
return "HostConfig: cluster must not be empty";
}
if (config.self.empty()) {
return "HostConfig: self node id must not be empty";
}
for (const auto& peer : config.peers) {
if (peer.empty()) {
return "HostConfig: peer node id must not be empty";
}
if (peer == config.self) {
return "HostConfig: self must not appear in the peer list";
}
}
if (config.startup_deadline.count() <= 0) {
return "HostConfig: startup_deadline must be positive";
}
return {};
}
} // namespace
DistributedHostGraph::DistributedHostGraph(HostResources resources,
HostConfig config)
: m_resources(resources), m_config(std::move(config))
{
}
DistributedHostGraph::~DistributedHostGraph()
{
stop();
}
DistributedHostGraph::DistributedHostGraph(
DistributedHostGraph&& other) noexcept
: m_resources(other.m_resources)
, m_config(std::move(other.m_config))
, m_history(std::move(other.m_history))
, m_started(other.m_started)
, m_storage_open(other.m_storage_open)
, m_transport_live(other.m_transport_live)
, m_replication_started(other.m_replication_started)
, m_directory_published(other.m_directory_published)
, m_stopped(other.m_stopped)
, m_readiness(other.m_readiness)
, m_last_error(std::move(other.m_last_error))
{
// The moved-from graph no longer owns any live component, so its
// destructor must not stop anything twice.
other.m_started = 0;
other.m_storage_open = false;
other.m_transport_live = false;
other.m_replication_started = false;
other.m_directory_published = false;
other.m_stopped = true;
}
Void::Result::Result<DistributedHostGraph>
DistributedHostGraph::compose(HostResources resources, HostConfig config)
{
if (const std::string error = validate(config); !error.empty()) {
return std::unexpected{invalid(error)};
}
if (resources.storage == nullptr || resources.transport == nullptr ||
resources.replication == nullptr) {
return std::unexpected{invalid(
"HostResources: storage, transport and replication are "
"required")};
}
return DistributedHostGraph{resources, std::move(config)};
}
void DistributedHostGraph::record(std::string step)
{
m_history.push_back(std::move(step));
}
Void::Result::Result<void> DistributedHostGraph::start_storage()
{
if (auto opened = m_resources.storage->open(); !opened) {
return opened;
}
record("storage.open");
m_storage_open = true;
++m_started;
if (auto recovered = m_resources.storage->recover(); !recovered) {
return recovered;
}
record("storage.recover");
return {};
}
Void::Result::Result<void> DistributedHostGraph::start_transport()
{
if (auto listening = m_resources.transport->listen(); !listening) {
return listening;
}
record("transport.listen");
m_transport_live = true;
++m_started;
if (auto connected =
m_resources.transport->connect_peers(m_config.peers);
!connected) {
return connected;
}
record("transport.connect_peers");
return {};
}
Void::Result::Result<void> DistributedHostGraph::start_replication()
{
if (auto started = m_resources.replication->start(); !started) {
return started;
}
record("replication.start");
m_replication_started = true;
++m_started;
const Role role = m_resources.replication->role();
const bool leader = m_resources.replication->leader_available();
if (m_config.require_leader_readiness && !leader) {
m_readiness = Readiness::FollowerHealthy;
return std::unexpected{unready(
"DistributedHost: no leader path within the startup deadline")};
}
m_readiness = leader ? Readiness::WriteReady
: Readiness::FollowerHealthy;
record("replication.readiness");
return {};
}
Void::Result::Result<void> DistributedHostGraph::publish_directory()
{
if (!m_config.publish_discovery || m_resources.directory == nullptr) {
return {};
}
// Discovery is an observation adapter: a failure is recorded but
// never weakens quorum or readiness.
auto published = m_resources.directory->publish(m_config.self);
record("directory.publish");
if (!published) {
m_last_error = published.error().message();
return {};
}
m_directory_published = true;
return {};
}
Void::Result::Result<void> DistributedHostGraph::start()
{
if (m_stopped) {
return std::unexpected{
conflict("DistributedHost: graph was already stopped")};
}
if (m_started != 0) {
return std::unexpected{
conflict("DistributedHost: graph is already started")};
}
m_readiness = Readiness::Starting;
m_last_error.clear();
auto storage = start_storage();
if (!storage) {
m_last_error = storage.error().message();
m_readiness = Readiness::Failed;
unwind();
return storage;
}
auto transport = start_transport();
if (!transport) {
m_last_error = transport.error().message();
m_readiness = Readiness::Failed;
unwind();
return transport;
}
auto replication = start_replication();
if (!replication) {
m_last_error = replication.error().message();
m_readiness = Readiness::Failed;
unwind();
return replication;
}
if (auto directory = publish_directory(); !directory) {
m_last_error = directory.error().message();
m_readiness = Readiness::Failed;
unwind();
return directory;
}
return {};
}
void DistributedHostGraph::stop() noexcept
{
if (m_stopped) {
return;
}
if (m_readiness != Readiness::Starting &&
m_readiness != Readiness::Failed) {
m_readiness = Readiness::Stopping;
}
// Reverse startup order, never destroying borrowed resources.
if (m_directory_published) {
m_resources.directory->withdraw();
record("directory.withdraw");
m_directory_published = false;
}
if (m_replication_started) {
m_resources.replication->stop();
record("replication.stop");
m_replication_started = false;
}
if (m_transport_live) {
m_resources.transport->close();
record("transport.close");
m_transport_live = false;
}
if (m_storage_open) {
m_resources.storage->close();
record("storage.close");
m_storage_open = false;
}
m_stopped = true;
m_started = 0;
if (m_readiness != Readiness::Failed) {
m_readiness = Readiness::Stopped;
}
}
void DistributedHostGraph::unwind() noexcept
{
// Rollback keeps the original failure visible in health().last_error.
const std::string preserved = m_last_error;
if (m_directory_published) {
m_resources.directory->withdraw();
record("directory.withdraw");
m_directory_published = false;
}
if (m_replication_started) {
m_resources.replication->stop();
record("replication.stop");
m_replication_started = false;
}
if (m_transport_live) {
m_resources.transport->close();
record("transport.close");
m_transport_live = false;
}
if (m_storage_open) {
m_resources.storage->close();
record("storage.close");
m_storage_open = false;
}
m_started = 0;
m_last_error = preserved;
}
HealthSnapshot DistributedHostGraph::health() const
{
HealthSnapshot snapshot;
snapshot.readiness = m_readiness;
snapshot.role = m_resources.replication != nullptr
? m_resources.replication->role()
: Role::Follower;
snapshot.quorum_available =
m_resources.replication != nullptr &&
m_resources.replication->leader_available();
snapshot.started_components = m_started;
snapshot.last_error = m_last_error;
return snapshot;
}
} // namespace DistributedHost
@@ -0,0 +1,395 @@
#include "distributed_host/range_placement.hpp"
#include <algorithm>
#include <format>
#include <string>
#include <utility>
namespace DistributedHost
{
namespace
{
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{
Void::Result::ErrorKind::invalid_argument, std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] Void::Result::Error not_found(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::not_found,
std::move(message)};
}
[[nodiscard]] Void::Result::Error corrupt(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
std::move(message)};
}
[[nodiscard]] bool overlapping(const KeyRange& a,
const KeyRange& b) noexcept
{
return a.start < b.end && b.start < a.end;
}
[[nodiscard]] bool has_separator(std::string_view text) noexcept
{
return text.find_first_of("\t\n") != std::string_view::npos;
}
} // namespace
std::string_view move_phase_name(MovePhase phase) noexcept
{
switch (phase) {
case MovePhase::None: return "none";
case MovePhase::Frozen: return "frozen";
case MovePhase::Verified: return "verified";
case MovePhase::Completed: return "completed";
case MovePhase::Aborted: return "aborted";
}
return "none";
}
RangeDirectory::RangeDirectory(std::vector<std::string> voters)
: m_voters(std::move(voters))
{
}
bool RangeDirectory::known_voter(std::string_view owner) const
{
return std::ranges::find(m_voters, owner) != m_voters.end();
}
Void::Result::Result<void>
RangeDirectory::assign(KeyRange range, std::string owner)
{
if (!range.valid() || has_separator(range.start) ||
has_separator(range.end)) {
return std::unexpected{
invalid("RangeDirectory: invalid range bounds")};
}
if (!known_voter(owner)) {
return std::unexpected{
invalid("RangeDirectory: owner is not a configured voter")};
}
for (const auto& [start, ownership] : m_ranges) {
if (overlapping(range, ownership.range)) {
return std::unexpected{conflict(std::format(
"RangeDirectory: range overlaps the existing [{}, {})",
ownership.range.start, ownership.range.end))};
}
}
m_ranges.emplace(range.start, RangeOwnership{range, std::move(owner)});
return {};
}
Void::Result::Result<std::string>
RangeDirectory::owner_of(std::string_view key) const
{
// Highest range start <= key.
auto candidate = m_ranges.upper_bound(std::string{key});
if (candidate == m_ranges.begin()) {
return std::unexpected{
not_found("RangeDirectory: no range owns the key")};
}
--candidate;
if (!candidate->second.range.contains(key)) {
return std::unexpected{
not_found("RangeDirectory: no range owns the key")};
}
return candidate->second.owner;
}
std::vector<RangeOwnership> RangeDirectory::ranges() const
{
std::vector<RangeOwnership> out;
out.reserve(m_ranges.size());
for (const auto& [start, ownership] : m_ranges) {
(void)start;
out.push_back(ownership);
}
return out;
}
const RangeDirectory::ActiveMove*
RangeDirectory::active_for(const KeyRange& range) const
{
for (const auto& [id, move] : m_moves) {
(void)id;
if (move.record.range == range &&
(move.record.phase == MovePhase::Frozen ||
move.record.phase == MovePhase::Verified)) {
return &move;
}
}
return nullptr;
}
RangeDirectory::ActiveMove*
RangeDirectory::mutable_move(std::uint64_t move_id)
{
const auto found = m_moves.find(move_id);
return found == m_moves.end() ? nullptr : &found->second;
}
Void::Result::Result<std::uint64_t>
RangeDirectory::begin_move(KeyRange range, std::string target)
{
if (!known_voter(target)) {
return std::unexpected{
invalid("RangeDirectory: target is not a configured voter")};
}
if (active_for(range) != nullptr) {
return std::unexpected{conflict(
"RangeDirectory: the range already has an active move")};
}
auto owner = owner_of(range.start);
if (!owner) {
return std::unexpected{std::move(owner).error()};
}
const auto found = m_ranges.find(range.start);
if (found == m_ranges.end() || !(found->second.range == range)) {
return std::unexpected{not_found(
"RangeDirectory: the range must match one assigned range")};
}
if (*owner == target) {
return std::unexpected{
conflict("RangeDirectory: target already owns the range")};
}
MoveRecord record;
record.id = m_next_move++;
record.range = std::move(range);
record.source = *owner;
record.target = std::move(target);
record.phase = MovePhase::Frozen;
m_moves.emplace(record.id, ActiveMove{record});
return record.id;
}
Void::Result::Result<void>
RangeDirectory::transfer(std::uint64_t move_id, std::size_t entries)
{
ActiveMove* move = mutable_move(move_id);
if (move == nullptr || move->record.phase != MovePhase::Frozen) {
return std::unexpected{
conflict("RangeDirectory: move is not frozen")};
}
move->record.transferred = entries;
return {};
}
Void::Result::Result<void>
RangeDirectory::verify(std::uint64_t move_id, std::size_t entries)
{
ActiveMove* move = mutable_move(move_id);
if (move == nullptr || move->record.phase != MovePhase::Frozen) {
return std::unexpected{
conflict("RangeDirectory: move is not frozen")};
}
if (entries != move->record.transferred) {
return std::unexpected{conflict(
"RangeDirectory: verified entry count does not match the "
"transfer")};
}
move->record.phase = MovePhase::Verified;
return {};
}
Void::Result::Result<void> RangeDirectory::complete(std::uint64_t move_id)
{
ActiveMove* move = mutable_move(move_id);
if (move == nullptr || move->record.phase != MovePhase::Verified) {
return std::unexpected{
conflict("RangeDirectory: move is not verified")};
}
const auto found = m_ranges.find(move->record.range.start);
if (found == m_ranges.end() ||
found->second.owner != move->record.source) {
return std::unexpected{
conflict("RangeDirectory: source no longer owns the range")};
}
found->second.owner = move->record.target;
move->record.phase = MovePhase::Completed;
return {};
}
void RangeDirectory::abort(std::uint64_t move_id, std::string reason) noexcept
{
if (ActiveMove* move = mutable_move(move_id); move != nullptr) {
if (move->record.phase == MovePhase::Frozen ||
move->record.phase == MovePhase::Verified) {
move->record.phase = MovePhase::Aborted;
move->record.note = std::move(reason);
}
}
}
Void::Result::Result<void>
RangeDirectory::admit_write(std::string_view key) const
{
if (auto owned = owner_of(key); !owned) {
return std::unexpected{std::move(owned).error()};
}
for (const auto& [id, move] : m_moves) {
(void)id;
if (move.record.range.contains(key) &&
(move.record.phase == MovePhase::Frozen ||
move.record.phase == MovePhase::Verified)) {
return std::unexpected{conflict(
"RangeDirectory: range is frozen for movement")};
}
}
return {};
}
Void::Result::Result<void>
RangeDirectory::admit_read(std::string_view key) const
{
if (auto owned = owner_of(key); !owned) {
return std::unexpected{std::move(owned).error()};
}
return {};
}
Void::Result::Result<RangeDirectory::Recovery>
RangeDirectory::recover(std::uint64_t move_id)
{
ActiveMove* move = mutable_move(move_id);
if (move == nullptr) {
return std::unexpected{
not_found("RangeDirectory: unknown move")};
}
if (move->record.phase == MovePhase::Verified) {
// The copy was verified before the crash: roll forward.
if (auto completed = complete(move_id); !completed) {
return std::unexpected{std::move(completed).error()};
}
return Recovery::RolledForward;
}
if (move->record.phase == MovePhase::Frozen) {
// No complete copy is proven: roll back to the source.
abort(move_id, "recovered after crash before verification");
return Recovery::RolledBack;
}
return Recovery::None;
}
Void::Result::Result<MoveRecord>
RangeDirectory::move(std::uint64_t move_id) const
{
const auto found = m_moves.find(move_id);
if (found == m_moves.end()) {
return std::unexpected{not_found("RangeDirectory: unknown move")};
}
return found->second.record;
}
std::string RangeDirectory::encode() const
{
std::string out;
for (const auto& [start, ownership] : m_ranges) {
(void)start;
out += ownership.range.start;
out += '\t';
out += ownership.range.end;
out += '\t';
out += ownership.owner;
out += '\n';
}
return out;
}
Void::Result::Result<void>
RangeDirectory::persist(ReplicatedKvCluster& cluster,
std::string_view leader, std::string_view key)
{
const std::string encoded = encode();
if (encoded.size() > max_directory_bytes) {
return std::unexpected{invalid(
"RangeDirectory: directory exceeds max_directory_bytes")};
}
const KvWriteReply reply =
cluster.propose(leader, std::string{key}, encoded);
if (reply.outcome != KvWriteOutcome::Applied) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::exhausted,
"RangeDirectory: directory write was not majority-committed"}};
}
return {};
}
Void::Result::Result<void>
RangeDirectory::load(ReplicatedKvCluster& cluster,
std::string_view leader, std::string_view key)
{
auto stored = cluster.quorum_read(leader, key);
if (!stored) {
return std::unexpected{std::move(stored).error()};
}
if (!stored->has_value()) {
return std::unexpected{
not_found("RangeDirectory: no persisted directory")};
}
const std::string& encoded = **stored;
if (encoded.size() > max_directory_bytes) {
return std::unexpected{
corrupt("RangeDirectory: persisted directory is too large")};
}
// Validate everything into a candidate map before installing it.
std::map<std::string, RangeOwnership, std::less<>> candidate;
std::size_t line_begin = 0;
while (line_begin < encoded.size()) {
const std::size_t line_end = encoded.find('\n', line_begin);
if (line_end == std::string::npos) {
return std::unexpected{
corrupt("RangeDirectory: unterminated record")};
}
const std::string_view line = std::string_view{encoded}.substr(
line_begin, line_end - line_begin);
const std::size_t first = line.find('\t');
const std::size_t second =
first == std::string_view::npos ? std::string_view::npos
: line.find('\t', first + 1);
if (first == std::string_view::npos ||
second == std::string_view::npos ||
line.find('\t', second + 1) != std::string_view::npos) {
return std::unexpected{
corrupt("RangeDirectory: malformed record")};
}
RangeOwnership ownership;
ownership.range.start = std::string{line.substr(0, first)};
ownership.range.end =
std::string{line.substr(first + 1, second - first - 1)};
ownership.owner = std::string{line.substr(second + 1)};
if (!ownership.range.valid() ||
!known_voter(ownership.owner) ||
candidate.contains(ownership.range.start)) {
return std::unexpected{
corrupt("RangeDirectory: invalid record")};
}
for (const auto& [start, existing] : candidate) {
(void)start;
if (overlapping(ownership.range, existing.range)) {
return std::unexpected{
corrupt("RangeDirectory: overlapping ranges")};
}
}
candidate.emplace(ownership.range.start, std::move(ownership));
line_begin = line_end + 1;
}
m_ranges = std::move(candidate);
// Interrupted moves do not survive a directory load.
m_moves.clear();
return {};
}
} // namespace DistributedHost
@@ -0,0 +1,411 @@
#include "distributed_host/replicated_kv.hpp"
#include <algorithm>
#include <string>
#include <utility>
namespace DistributedHost
{
namespace
{
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{
Void::Result::ErrorKind::invalid_argument, std::move(message)};
}
[[nodiscard]] Void::Result::Error no_quorum(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::overloaded,
std::move(message)};
}
[[nodiscard]] Void::Result::Error not_found(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::not_found,
std::move(message)};
}
[[nodiscard]] Void::Result::Error not_leader(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
} // namespace
ReplicatedKvCluster::ReplicatedKvCluster(std::vector<std::string> voters)
: m_voters(std::move(voters))
{
m_nodes.reserve(m_voters.size());
for (const auto& id : m_voters) {
Node node;
node.id = id;
// Sentinel entry keeps log indices 1-based and match the entry
// index directly.
node.log.push_back(KvLogEntry{.term = 0, .index = 0});
m_nodes.push_back(std::move(node));
}
}
ReplicatedKvCluster::Node* ReplicatedKvCluster::find(std::string_view id)
{
for (auto& node : m_nodes) {
if (node.id == id) {
return &node;
}
}
return nullptr;
}
const ReplicatedKvCluster::Node*
ReplicatedKvCluster::find(std::string_view id) const
{
for (const auto& node : m_nodes) {
if (node.id == id) {
return &node;
}
}
return nullptr;
}
bool ReplicatedKvCluster::reachable(const Node& a, const Node& b) const
{
return a.alive && b.alive && a.partition == b.partition;
}
bool ReplicatedKvCluster::majority(std::size_t acks) const
{
return acks > m_voters.size() / 2;
}
bool ReplicatedKvCluster::log_up_to_date(const Node& candidate,
const Node& voter)
{
const auto& last_candidate = candidate.log.back();
const auto& last_voter = voter.log.back();
if (last_candidate.term != last_voter.term) {
return last_candidate.term > last_voter.term;
}
return last_candidate.index >= last_voter.index;
}
void ReplicatedKvCluster::apply_committed(Node& node)
{
while (node.applied_index < node.commit_index &&
node.applied_index + 1 < node.log.size()) {
const KvLogEntry& entry = node.log[node.applied_index + 1];
if (entry.value.has_value()) {
node.kv.insert_or_assign(entry.key, *entry.value);
} else {
node.kv.erase(entry.key);
}
node.applied_index = entry.index;
}
}
Void::Result::Result<void>
ReplicatedKvCluster::elect(std::string_view candidate)
{
Node* self = find(candidate);
if (self == nullptr) {
return std::unexpected{
not_found("ReplicatedKv: unknown voter")};
}
if (!self->alive) {
return std::unexpected{
no_quorum("ReplicatedKv: candidate is down")};
}
self->term += 1;
self->role = Role::Candidate;
self->voted_for = self->id;
self->leader.reset();
std::size_t votes = 1;
for (auto& voter : m_nodes) {
if (voter.id == self->id || !reachable(*self, voter)) {
continue;
}
if (voter.term < self->term) {
voter.term = self->term;
voter.voted_for.reset();
voter.role = Role::Follower;
voter.leader.reset();
}
const bool can_vote =
voter.term == self->term && !voter.voted_for.has_value();
if (can_vote && log_up_to_date(*self, voter)) {
voter.voted_for = self->id;
++votes;
}
}
if (!majority(votes)) {
self->role = Role::Follower;
return std::unexpected{no_quorum(
"ReplicatedKv: election did not reach a majority")};
}
self->role = Role::Leader;
self->leader = self->id;
for (auto& node : m_nodes) {
if (node.id != self->id && reachable(*self, node) &&
node.term <= self->term) {
node.leader = self->id;
}
}
return {};
}
bool ReplicatedKvCluster::replicate_to(Node& leader, Node& follower)
{
if (!reachable(leader, follower)) {
return false;
}
if (follower.term > leader.term) {
leader.role = Role::Follower;
leader.leader.reset();
return false;
}
if (follower.term < leader.term) {
follower.term = leader.term;
follower.voted_for.reset();
follower.role = Role::Follower;
}
follower.leader = leader.id;
// Highest index where both logs agree, then overwrite the suffix.
std::size_t match = 0;
const std::size_t shared =
std::min(follower.log.size(), leader.log.size()) - 1;
for (std::size_t i = shared + 1; i-- > 0;) {
if (follower.log[i].term == leader.log[i].term) {
match = i;
break;
}
}
follower.log.resize(match + 1);
for (std::size_t i = match + 1; i < leader.log.size(); ++i) {
follower.log.push_back(leader.log[i]);
}
// AppendEntries carries the leader commit index: a follower that was
// behind applies everything now proven committed.
if (leader.commit_index > follower.commit_index) {
follower.commit_index = std::min(
leader.commit_index,
static_cast<std::uint64_t>(follower.log.size() - 1));
apply_committed(follower);
}
return true;
}
KvWriteReply ReplicatedKvCluster::propose(std::string_view leader_id,
std::string key,
std::optional<std::string> value)
{
Node* leader = find(leader_id);
if (leader == nullptr || !leader->alive) {
return KvWriteReply{.outcome = KvWriteOutcome::NodeDown,
.index = 0,
.term = leader ? leader->term : 0};
}
if (leader->role != Role::Leader) {
return KvWriteReply{.outcome = KvWriteOutcome::NotLeader,
.index = 0,
.term = leader->term};
}
KvLogEntry entry;
entry.term = leader->term;
entry.index = static_cast<std::uint64_t>(leader->log.size());
entry.key = std::move(key);
entry.value = std::move(value);
leader->log.push_back(entry);
std::size_t acks = 1;
for (auto& follower : m_nodes) {
if (follower.id == leader->id) {
continue;
}
if (replicate_to(*leader, follower)) {
++acks;
}
if (leader->role != Role::Leader) {
// A higher term was observed: the local append is not durable.
return KvWriteReply{.outcome = KvWriteOutcome::NotLeader,
.index = entry.index,
.term = leader->term};
}
}
if (!majority(acks)) {
// Uncommitted: a later leader may truncate it. Never applied.
return KvWriteReply{.outcome = KvWriteOutcome::NoQuorum,
.index = entry.index,
.term = leader->term};
}
leader->commit_index = entry.index;
apply_committed(*leader);
for (auto& node : m_nodes) {
if (node.id == leader->id || !reachable(*leader, node)) {
continue;
}
// Only nodes whose log matches the committed entry may apply it.
if (node.log.size() > entry.index &&
node.log[entry.index].term == entry.term) {
node.commit_index =
std::max(node.commit_index, entry.index);
apply_committed(node);
}
}
return KvWriteReply{
.outcome = KvWriteOutcome::Applied,
.index = entry.index,
.term = leader->term};
}
Void::Result::Result<void>
ReplicatedKvCluster::heartbeat(std::string_view leader_id)
{
Node* leader = find(leader_id);
if (leader == nullptr) {
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
}
if (!leader->alive || leader->role != Role::Leader) {
return std::unexpected{
not_leader("ReplicatedKv: heartbeat requires a leader")};
}
for (auto& follower : m_nodes) {
if (follower.id != leader->id) {
(void)replicate_to(*leader, follower);
}
}
if (leader->role != Role::Leader) {
return std::unexpected{not_leader(
"ReplicatedKv: stepped down after a higher term")};
}
return {};
}
Void::Result::Result<void>
ReplicatedKvCluster::confirm_leader(Node& node)
{
if (!node.alive) {
return std::unexpected{no_quorum("ReplicatedKv: node is down")};
}
if (node.role != Role::Leader) {
return std::unexpected{not_leader(
"ReplicatedKv: consistent reads require a leader")};
}
// Confirm leadership in this term with a majority heartbeat.
std::size_t acks = 1;
for (auto& peer : m_nodes) {
if (peer.id == node.id || !reachable(node, peer)) {
continue;
}
if (peer.term > node.term) {
node.role = Role::Follower;
node.leader.reset();
return std::unexpected{not_leader(
"ReplicatedKv: stepped down after a higher term")};
}
++acks;
}
if (!majority(acks)) {
return std::unexpected{no_quorum(
"ReplicatedKv: no majority to confirm the read")};
}
// A quorum-confirmed leader has every committed entry; apply them.
apply_committed(node);
return {};
}
Void::Result::Result<std::optional<std::string>>
ReplicatedKvCluster::quorum_read(std::string_view node_id,
std::string_view key)
{
Node* node = find(node_id);
if (node == nullptr) {
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
}
if (auto confirmed = confirm_leader(*node); !confirmed) {
return std::unexpected{std::move(confirmed).error()};
}
const auto found = node->kv.find(key);
if (found == node->kv.end()) {
return std::optional<std::string>{};
}
return std::optional<std::string>{found->second};
}
Void::Result::Result<std::map<std::string, std::string, std::less<>>>
ReplicatedKvCluster::quorum_snapshot(std::string_view node_id)
{
Node* node = find(node_id);
if (node == nullptr) {
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
}
if (auto confirmed = confirm_leader(*node); !confirmed) {
return std::unexpected{std::move(confirmed).error()};
}
return node->kv;
}
void ReplicatedKvCluster::crash(std::string_view node_id)
{
if (Node* node = find(node_id); node != nullptr) {
node->alive = false;
node->role = Role::Follower;
node->leader.reset();
}
}
void ReplicatedKvCluster::restart(std::string_view node_id)
{
if (Node* node = find(node_id); node != nullptr) {
// Log, term, vote and applied state are durable.
node->alive = true;
node->role = Role::Follower;
node->leader.reset();
}
}
void ReplicatedKvCluster::set_partition(std::string_view node_id,
int partition)
{
if (Node* node = find(node_id); node != nullptr) {
node->partition = partition;
}
}
std::optional<KvNodeSnapshot>
ReplicatedKvCluster::snapshot(std::string_view node_id) const
{
const Node* node = find(node_id);
if (node == nullptr) {
return std::nullopt;
}
KvNodeSnapshot out;
out.id = node->id;
out.alive = node->alive;
out.role = node->role;
out.term = node->term;
out.commit_index = node->commit_index;
out.applied_index = node->applied_index;
out.log_size = node->log.size();
out.leader = node->leader;
out.kv = node->kv;
return out;
}
std::uint64_t ReplicatedKvCluster::committed_index() const
{
std::uint64_t highest = 0;
for (const auto& node : m_nodes) {
if (node.alive) {
highest = std::max(highest, node.commit_index);
}
}
return highest;
}
} // namespace DistributedHost
@@ -0,0 +1,495 @@
#include "distributed_host/replicated_queue.hpp"
#include <algorithm>
#include <array>
#include <map>
#include <string>
#include <utility>
#include <vector>
namespace DistributedHost
{
namespace
{
constexpr std::array<std::byte, 4> kMagic{
std::byte{'V'}, std::byte{'J'}, std::byte{'O'}, std::byte{'B'}};
constexpr std::uint32_t kVersion{1};
constexpr std::size_t kMaxIdBytes{128};
constexpr std::size_t kMaxConsumerBytes{128};
constexpr std::size_t kMaxReasonBytes{512};
constexpr std::string_view kJobPrefix{"job/"};
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{
Void::Result::ErrorKind::invalid_argument, std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] Void::Result::Error not_found(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::not_found,
std::move(message)};
}
[[nodiscard]] Void::Result::Error exhausted(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
std::move(message)};
}
[[nodiscard]] Void::Result::Error corrupt(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
std::move(message)};
}
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
{
for (int shift = 24; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
std::size_t& pos, std::uint32_t& value) noexcept
{
if (pos + 4 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 4; ++i) {
value = (value << 8) |
std::to_integer<std::uint32_t>(in[pos + i]);
}
pos += 4;
return true;
}
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
std::size_t& pos, std::uint64_t& value) noexcept
{
if (pos + 8 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 8; ++i) {
value = (value << 8) |
std::to_integer<std::uint64_t>(in[pos + i]);
}
pos += 8;
return true;
}
void append_string(std::vector<std::byte>& out, std::string_view text)
{
append_u32(out, static_cast<std::uint32_t>(text.size()));
for (const char c : text) {
out.push_back(static_cast<std::byte>(
static_cast<unsigned char>(c)));
}
}
[[nodiscard]] bool read_string(std::span<const std::byte> in,
std::size_t& pos, std::string& out,
std::size_t max_bytes) noexcept
{
std::uint32_t length = 0;
if (!read_u32(in, pos, length) || length > max_bytes ||
pos + length > in.size()) {
return false;
}
out.clear();
out.reserve(length);
for (std::uint32_t i = 0; i < length; ++i) {
out.push_back(static_cast<char>(
std::to_integer<unsigned char>(in[pos + i])));
}
pos += length;
return true;
}
[[nodiscard]] std::uint64_t checksum(std::span<const std::byte> bytes)
{
std::uint64_t hash = 0xCBF29CE484222325ULL;
for (const std::byte byte : bytes) {
hash ^= std::to_integer<std::uint64_t>(byte);
hash *= 0x100000001B3ULL;
}
return hash;
}
[[nodiscard]] std::vector<std::byte> encode_job(const QueueJob& job)
{
std::vector<std::byte> out;
out.insert(out.end(), kMagic.begin(), kMagic.end());
append_u32(out, kVersion);
append_string(out, job.id);
append_string(out, job.payload);
out.push_back(static_cast<std::byte>(job.state));
append_u32(out, job.attempts);
append_string(out, job.consumer);
out.push_back(std::byte{job.outbox_pending ? 1 : 0});
append_string(out, job.reason);
append_u64(out, checksum(out));
return out;
}
[[nodiscard]] std::optional<QueueJob>
decode_job(std::span<const std::byte> bytes)
{
if (bytes.size() < kMagic.size() + 4 + 8 ||
!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
return std::nullopt;
}
const std::size_t payload = bytes.size() - 8;
std::uint64_t stored = 0;
{
std::size_t check_pos = payload;
if (!read_u64(bytes, check_pos, stored) ||
checksum(bytes.first(payload)) != stored) {
return std::nullopt;
}
}
std::size_t pos = kMagic.size();
std::uint32_t version = 0;
if (!read_u32(bytes, pos, version) || version != kVersion) {
return std::nullopt;
}
QueueJob job;
if (!read_string(bytes, pos, job.id, kMaxIdBytes) ||
!read_string(bytes, pos, job.payload, 1024ULL * 1024ULL) ||
pos >= payload) {
return std::nullopt;
}
job.state = static_cast<JobState>(
std::to_integer<unsigned char>(bytes[pos++]));
if (job.state != JobState::Pending &&
job.state != JobState::InFlight &&
job.state != JobState::Done && job.state != JobState::Dead) {
return std::nullopt;
}
if (!read_u32(bytes, pos, job.attempts) ||
!read_string(bytes, pos, job.consumer, kMaxConsumerBytes) ||
pos >= payload) {
return std::nullopt;
}
job.outbox_pending = std::to_integer<unsigned char>(bytes[pos++]) != 0;
if (!read_string(bytes, pos, job.reason, kMaxReasonBytes) ||
pos != payload) {
return std::nullopt;
}
return job;
}
[[nodiscard]] std::string to_string(std::span<const std::byte> bytes)
{
return std::string{
reinterpret_cast<const char*>(bytes.data()), bytes.size()};
}
} // namespace
std::string_view job_state_name(JobState state) noexcept
{
switch (state) {
case JobState::Pending: return "pending";
case JobState::InFlight: return "in-flight";
case JobState::Done: return "done";
case JobState::Dead: return "dead";
}
return "pending";
}
ReplicatedQueue::ReplicatedQueue(ReplicatedKvCluster& cluster,
std::string leader, QueueConfig config)
: m_cluster(cluster), m_leader(std::move(leader)), m_config(config)
{
}
std::string ReplicatedQueue::key_for(std::string_view id)
{
return std::string{kJobPrefix} + std::string{id};
}
Void::Result::Result<void> ReplicatedQueue::store(const QueueJob& job)
{
const auto encoded = encode_job(job);
const KvWriteReply reply = m_cluster.propose(
m_leader, key_for(job.id), to_string(encoded));
switch (reply.outcome) {
case KvWriteOutcome::Applied:
return {};
case KvWriteOutcome::NoQuorum:
return std::unexpected{exhausted(
"ReplicatedQueue: write was not majority-committed")};
case KvWriteOutcome::NotLeader:
return std::unexpected{
conflict("ReplicatedQueue: endpoint is not the leader")};
case KvWriteOutcome::NodeDown:
return std::unexpected{exhausted(
"ReplicatedQueue: leader is down")};
}
return std::unexpected{
exhausted("ReplicatedQueue: unknown commit outcome")};
}
Void::Result::Result<std::optional<QueueJob>>
ReplicatedQueue::load(std::string_view job_id)
{
auto stored = m_cluster.quorum_read(m_leader, key_for(job_id));
if (!stored) {
return std::unexpected{std::move(stored).error()};
}
if (!stored->has_value()) {
return std::optional<QueueJob>{};
}
const auto bytes =
std::as_bytes(std::span{(*stored)->data(), (*stored)->size()});
auto decoded = decode_job(bytes);
if (!decoded) {
return std::unexpected{corrupt("ReplicatedQueue: corrupt job record")};
}
return std::optional<QueueJob>{std::move(*decoded)};
}
Void::Result::Result<std::vector<std::pair<std::string, QueueJob>>>
ReplicatedQueue::all_jobs()
{
auto snapshot = m_cluster.quorum_snapshot(m_leader);
if (!snapshot) {
return std::unexpected{std::move(snapshot).error()};
}
std::vector<std::pair<std::string, QueueJob>> jobs;
for (const auto& [key, value] : *snapshot) {
if (!key.starts_with(kJobPrefix)) {
continue;
}
const auto bytes = std::as_bytes(std::span{value.data(), value.size()});
auto decoded = decode_job(bytes);
if (!decoded) {
return std::unexpected{
corrupt("ReplicatedQueue: corrupt job record")};
}
jobs.emplace_back(key, std::move(*decoded));
}
return jobs;
}
Void::Result::Result<std::string>
ReplicatedQueue::publish(std::string payload,
std::string idempotency_key)
{
if (idempotency_key.empty() || idempotency_key.size() > kMaxIdBytes) {
return std::unexpected{
invalid("ReplicatedQueue: invalid idempotency key")};
}
if (payload.size() > m_config.max_payload_bytes) {
return std::unexpected{
invalid("ReplicatedQueue: payload exceeds max_payload_bytes")};
}
auto jobs = all_jobs();
if (!jobs) {
return std::unexpected{std::move(jobs).error()};
}
for (const auto& [key, job] : *jobs) {
(void)key;
if (job.id == idempotency_key) {
// Deduplicated: the caller's retry resolves to the same job.
return idempotency_key;
}
}
if (jobs->size() >= m_config.max_jobs) {
return std::unexpected{
exhausted("ReplicatedQueue: job cap reached")};
}
QueueJob job;
job.id = idempotency_key;
job.payload = std::move(payload);
if (auto written = store(job); !written) {
return std::unexpected{std::move(written).error()};
}
return idempotency_key;
}
Void::Result::Result<std::optional<QueueJob>>
ReplicatedQueue::claim(std::string_view consumer)
{
if (consumer.empty()) {
return std::unexpected{
invalid("ReplicatedQueue: consumer must not be empty")};
}
auto jobs = all_jobs();
if (!jobs) {
return std::unexpected{std::move(jobs).error()};
}
for (auto& [key, job] : *jobs) {
(void)key;
if (job.state != JobState::Pending) {
continue;
}
job.state = JobState::InFlight;
job.consumer = std::string{consumer};
++job.attempts;
if (auto written = store(job); !written) {
return std::unexpected{std::move(written).error()};
}
return std::optional<QueueJob>{std::move(job)};
}
return std::optional<QueueJob>{};
}
Void::Result::Result<void>
ReplicatedQueue::ack(std::string_view consumer, std::string_view job_id)
{
auto job = load(job_id);
if (!job) {
return std::unexpected{std::move(job).error()};
}
if (!job->has_value()) {
return std::unexpected{
not_found("ReplicatedQueue: unknown job")};
}
if ((*job)->state == JobState::Done) {
// Duplicate delivery: the inbox already recorded the outcome and
// the outbox must not gain a second entry.
return {};
}
if ((*job)->state != JobState::InFlight ||
(*job)->consumer != consumer) {
return std::unexpected{conflict(
"ReplicatedQueue: job is not in flight for this consumer")};
}
(*job)->state = JobState::Done;
(*job)->consumer.clear();
(*job)->outbox_pending = true;
return store(**job);
}
Void::Result::Result<QueueJob>
ReplicatedQueue::nack(std::string_view consumer, std::string_view job_id,
std::string reason)
{
auto job = load(job_id);
if (!job) {
return std::unexpected{std::move(job).error()};
}
if (!job->has_value()) {
return std::unexpected{
not_found("ReplicatedQueue: unknown job")};
}
if ((*job)->state != JobState::InFlight ||
(*job)->consumer != consumer) {
return std::unexpected{conflict(
"ReplicatedQueue: job is not in flight for this consumer")};
}
(*job)->reason = std::move(reason);
(*job)->consumer.clear();
if ((*job)->attempts >= m_config.max_attempts) {
(*job)->state = JobState::Dead;
} else {
(*job)->state = JobState::Pending;
}
if (auto written = store(**job); !written) {
return std::unexpected{std::move(written).error()};
}
return **job;
}
Void::Result::Result<std::size_t>
ReplicatedQueue::recover_consumer(std::string_view consumer)
{
auto jobs = all_jobs();
if (!jobs) {
return std::unexpected{std::move(jobs).error()};
}
std::size_t affected = 0;
for (auto& [key, job] : *jobs) {
(void)key;
if (job.state != JobState::InFlight || job.consumer != consumer) {
continue;
}
job.consumer.clear();
if (job.attempts >= m_config.max_attempts) {
job.state = JobState::Dead;
job.reason = "consumer lost after final attempt";
} else {
job.state = JobState::Pending;
}
if (auto written = store(job); !written) {
return std::unexpected{std::move(written).error()};
}
++affected;
}
return affected;
}
Void::Result::Result<std::size_t>
ReplicatedQueue::dispatch_outbox(const OutboxSink& sink)
{
auto jobs = all_jobs();
if (!jobs) {
return std::unexpected{std::move(jobs).error()};
}
std::size_t delivered = 0;
for (auto& [key, job] : *jobs) {
(void)key;
if (job.state != JobState::Done || !job.outbox_pending) {
continue;
}
if (sink) {
sink(job);
}
job.outbox_pending = false;
if (auto written = store(job); !written) {
// The effect was delivered but not marked: the next dispatch
// delivers it again (at-least-once).
return std::unexpected{std::move(written).error()};
}
++delivered;
}
return delivered;
}
Void::Result::Result<std::vector<QueueJob>>
ReplicatedQueue::dead_letters()
{
auto jobs = all_jobs();
if (!jobs) {
return std::unexpected{std::move(jobs).error()};
}
std::vector<QueueJob> dead;
for (auto& [key, job] : *jobs) {
(void)key;
if (job.state == JobState::Dead) {
dead.push_back(std::move(job));
}
}
return dead;
}
Void::Result::Result<QueueJob>
ReplicatedQueue::status(std::string_view job_id)
{
auto job = load(job_id);
if (!job) {
return std::unexpected{std::move(job).error()};
}
if (!job->has_value()) {
return std::unexpected{
not_found("ReplicatedQueue: unknown job")};
}
return **job;
}
} // namespace DistributedHost
@@ -0,0 +1,376 @@
#include "distributed_host/single_node.hpp"
#include <Void/Net/Http.hpp>
#include <algorithm>
#include <charconv>
#include <chrono>
#include <format>
#include <string>
#include <string_view>
#include <utility>
namespace DistributedHost
{
namespace
{
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{
Void::Result::ErrorKind::invalid_argument, std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] Void::Result::Error exhausted(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
std::move(message)};
}
[[nodiscard]] bool parse_address(std::string_view address,
std::string& host,
std::uint16_t& port) noexcept
{
const auto colon = address.rfind(':');
if (colon == std::string_view::npos || colon == 0 ||
colon + 1 >= address.size()) {
return false;
}
host = std::string{address.substr(0, colon)};
const auto digits = address.substr(colon + 1);
unsigned int value = 0;
const auto parsed = std::from_chars(
digits.data(), digits.data() + digits.size(), value);
if (parsed.ec != std::errc{} ||
parsed.ptr != digits.data() + digits.size() || value > 65535U) {
return false;
}
port = static_cast<std::uint16_t>(value);
return true;
}
/// Length-independent comparison: always scans the full candidate.
[[nodiscard]] bool constant_time_equal(std::string_view a,
std::string_view b) noexcept
{
unsigned char difference =
static_cast<unsigned char>(a.size() == b.size() ? 0 : 1);
for (std::size_t i = 0; i < b.size(); ++i) {
const unsigned char left =
i < a.size() ? static_cast<unsigned char>(a[i]) : 0;
difference |= static_cast<unsigned char>(
left ^ static_cast<unsigned char>(b[i]));
}
return difference == 0;
}
[[nodiscard]] bool iequals_ascii(std::string_view a,
std::string_view b) noexcept
{
if (a.size() != b.size()) {
return false;
}
for (std::size_t i = 0; i < a.size(); ++i) {
auto lower = [](char c) noexcept {
return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a')
: c;
};
if (lower(a[i]) != lower(b[i])) {
return false;
}
}
return true;
}
[[nodiscard]] Void::Net::ServerResponse text_response(int status,
std::string body)
{
Void::Net::ServerResponse response;
response.status = static_cast<std::uint16_t>(status);
response.headers.push_back(
Void::Net::Header{"content-type", "text/plain; charset=utf-8"});
response.headers.push_back(Void::Net::Header{"cache-control", "no-store"});
response.body = std::move(body);
return response;
}
} // namespace
Void::Result::Result<void> SingleNodeConfig::validate() const
{
std::string host;
std::uint16_t port = 0;
if (!parse_address(peer_address, host, port)) {
return std::unexpected{
invalid("SingleNodeConfig: peer_address must be host:port")};
}
if (peer_token.empty()) {
return std::unexpected{invalid(
"SingleNodeConfig: peer_token is required (fail closed)")};
}
if (max_connections == 0) {
return std::unexpected{invalid(
"SingleNodeConfig: max_connections must be positive")};
}
if (max_append_bytes == 0) {
return std::unexpected{invalid(
"SingleNodeConfig: max_append_bytes must be positive")};
}
if (max_log_entries == 0) {
return std::unexpected{invalid(
"SingleNodeConfig: max_log_entries must be positive")};
}
if (shutdown_grace.count() < 0) {
return std::unexpected{invalid(
"SingleNodeConfig: shutdown_grace must not be negative")};
}
return {};
}
PeerLog::PeerLog(std::size_t max_entries)
: m_max_entries(max_entries)
{
}
Void::Result::Result<std::uint64_t> PeerLog::append(std::string entry)
{
std::lock_guard lock{m_mutex};
if (m_entries.size() >= m_max_entries) {
return std::unexpected{exhausted(
"PeerLog: retained entry cap reached")};
}
m_entries.push_back(std::move(entry));
return static_cast<std::uint64_t>(m_entries.size());
}
std::size_t PeerLog::size() const
{
std::lock_guard lock{m_mutex};
return m_entries.size();
}
std::uint64_t PeerLog::last_index() const
{
std::lock_guard lock{m_mutex};
return static_cast<std::uint64_t>(m_entries.size());
}
HttpPeerTransport::HttpPeerTransport(std::string address, std::string token,
PeerLog& log,
std::size_t max_connections,
std::size_t max_append_bytes)
: m_address(std::move(address))
, m_token(std::move(token))
, m_log(log)
, m_max_connections(max_connections)
, m_max_append_bytes(max_append_bytes)
{
}
HttpPeerTransport::~HttpPeerTransport() noexcept
{
close();
}
bool HttpPeerTransport::authorized(
const Void::Net::ServerRequest& req) const noexcept
{
if (m_token.empty()) {
return false;
}
const auto header = req.header("authorization");
if (!header) {
return false;
}
constexpr std::string_view scheme{"bearer "};
if (header->size() < scheme.size() ||
!iequals_ascii(header->substr(0, scheme.size()), scheme)) {
return false;
}
return constant_time_equal(header->substr(scheme.size()), m_token);
}
Void::Result::Result<void> HttpPeerTransport::listen()
{
if (m_server) {
return std::unexpected{
conflict("HttpPeerTransport: already listening")};
}
std::string host;
std::uint16_t port = 0;
if (!parse_address(m_address, host, port)) {
return std::unexpected{
invalid("HttpPeerTransport: address must be host:port")};
}
Void::Net::HttpServerOptions options;
options.bind_host = std::move(host);
options.port = port;
options.max_concurrent_connections = m_max_connections;
options.max_body_bytes = m_max_append_bytes;
auto server = std::make_unique<Void::Net::HttpServer>(options);
auto added = server->add_route(
Void::Net::Method::Get, "/peer/health",
[this](const Void::Net::ServerRequest& req)
-> Void::Net::RouteResult {
if (!authorized(req)) {
return Void::Result::ok(
text_response(401, "unauthorized"));
}
return Void::Result::ok(text_response(
200, std::format("role=leader entries={} last_index={}",
m_log.size(), m_log.last_index())));
});
if (!added) {
return std::unexpected{std::move(added).error()};
}
added = server->add_route(
Void::Net::Method::Post, "/peer/append",
[this](const Void::Net::ServerRequest& req)
-> Void::Net::RouteResult {
if (!authorized(req)) {
return Void::Result::ok(
text_response(401, "unauthorized"));
}
if (req.body.empty()) {
return Void::Result::ok(
text_response(400, "empty entry"));
}
if (req.body.size() > m_max_append_bytes) {
return Void::Result::ok(
text_response(413, "entry too large"));
}
auto index = m_log.append(req.body);
if (!index) {
return Void::Result::ok(
text_response(503, index.error().message()));
}
return Void::Result::ok(text_response(
200, std::format("index={}", *index)));
});
if (!added) {
return std::unexpected{std::move(added).error()};
}
if (auto started = server->start(); !started) {
return started;
}
m_server = std::move(server);
return {};
}
Void::Result::Result<void>
HttpPeerTransport::connect_peers(const std::vector<NodeId>& peers)
{
// A single-node fixture has no outgoing peer connections; the count is
// recorded for inspect and the multi-node transport is a later task.
m_connected_peers = peers.size();
return {};
}
void HttpPeerTransport::close() noexcept
{
if (m_server) {
m_server->shutdown(std::chrono::seconds{2});
m_server.reset();
}
m_connected_peers = 0;
}
std::uint16_t HttpPeerTransport::bound_port() const noexcept
{
return m_server ? m_server->bound_port() : 0;
}
Void::Result::Result<void> SingleNodeReplication::start()
{
if (m_running) {
return std::unexpected{
conflict("SingleNodeReplication: already started")};
}
m_running = true;
return {};
}
SingleNodeHost::SingleNodeHost(SingleNodeConfig config)
: m_config(std::move(config))
, m_log(std::make_unique<PeerLog>(m_config.max_log_entries))
, m_storage(std::make_unique<NoopStorage>())
{
}
SingleNodeHost::~SingleNodeHost()
{
stop();
}
Void::Result::Result<SingleNodeHost>
SingleNodeHost::create(SingleNodeConfig config)
{
if (auto valid = config.validate(); !valid) {
return std::unexpected{std::move(valid).error()};
}
SingleNodeHost host{std::move(config)};
host.m_transport = std::make_unique<HttpPeerTransport>(
host.m_config.peer_address, host.m_config.peer_token, *host.m_log,
host.m_config.max_connections, host.m_config.max_append_bytes);
host.m_replication = std::make_unique<SingleNodeReplication>();
HostResources resources;
resources.storage = host.m_storage.get();
resources.transport = host.m_transport.get();
resources.replication = host.m_replication.get();
HostConfig graph_config;
graph_config.cluster = "single-node";
graph_config.self = "node-1";
graph_config.peers = {};
graph_config.publish_discovery = false;
graph_config.startup_deadline = host.m_config.shutdown_grace;
auto graph =
DistributedHostGraph::compose(resources, std::move(graph_config));
if (!graph) {
return std::unexpected{std::move(graph).error()};
}
host.m_graph =
std::make_unique<DistributedHostGraph>(std::move(*graph));
return host;
}
Void::Result::Result<void> SingleNodeHost::start()
{
if (!m_graph) {
return std::unexpected{
conflict("SingleNodeHost: host was moved out")};
}
return m_graph->start();
}
void SingleNodeHost::stop() noexcept
{
if (m_graph) {
m_graph->stop();
}
}
HealthSnapshot SingleNodeHost::health() const
{
return m_graph ? m_graph->health() : HealthSnapshot{};
}
std::uint16_t SingleNodeHost::peer_port() const noexcept
{
return m_transport ? m_transport->bound_port() : 0;
}
const std::vector<std::string>& SingleNodeHost::history() const noexcept
{
static const std::vector<std::string> empty{};
return m_graph ? m_graph->history() : empty;
}
} // namespace DistributedHost
@@ -0,0 +1,184 @@
#include "distributed_host/cluster_fixture.hpp"
#include <Void/Net/Http.hpp>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
namespace
{
using namespace DistributedHost;
Void::Net::Header auth()
{
return Void::Net::Header{"authorization", "Bearer peer-secret"};
}
Void::Net::Response
send(Void::Net::HttpClient& client, Void::Net::Method method,
const std::string& url, std::string body = {})
{
Void::Net::Request request;
request.method = method;
request.url = url;
request.body = std::move(body);
request.headers.push_back(auth());
auto response = client.send(request);
assert(response.has_value());
return *response;
}
void three_real_listeners_serve_the_replicated_kv()
{
auto fixture = ClusterFixture::create();
assert(fixture.has_value());
// Construction opens nothing.
assert((*fixture)->endpoint("a").empty());
assert((*fixture)->start().has_value());
const std::string a = (*fixture)->endpoint("a");
const std::string b = (*fixture)->endpoint("b");
const std::string c = (*fixture)->endpoint("c");
assert(!a.empty() && !b.empty() && !c.empty());
assert(a != b && b != c && a != c);
Void::Net::HttpClient client;
// Every peer route is authenticated.
auto anonymous = client.get(a + "/peer/health");
assert(anonymous.has_value() && anonymous->status == 401);
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").body ==
"elected");
auto proposed = send(client, Void::Net::Method::Put,
a + "/peer/propose?key=k", "value");
assert(proposed.status == 200);
assert(proposed.body.starts_with("applied"));
auto read = client.get(a + "/peer/read?key=k", {auth()});
assert(read.has_value());
assert(read->status == 200);
assert(read->body == "value");
// The follower applied the committed entry but cannot serve a
// consistent read.
auto follower_read = client.get(b + "/peer/read?key=k", {auth()});
assert(follower_read.has_value());
assert(follower_read->status == 409);
auto follower_write =
send(client, Void::Net::Method::Put, b + "/peer/propose?key=k", "x");
assert(follower_write.status == 409);
(*fixture)->stop();
assert((*fixture)->endpoint("a").empty());
}
void minority_leader_cannot_commit_or_read_over_http()
{
auto fixture = ClusterFixture::create();
assert(fixture.has_value());
assert((*fixture)->start().has_value());
const std::string a = (*fixture)->endpoint("a");
const std::string b = (*fixture)->endpoint("b");
const std::string c = (*fixture)->endpoint("c");
Void::Net::HttpClient client;
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
200);
assert(send(client, Void::Net::Method::Post,
a + "/admin/partition?node=b&partition=1")
.status == 200);
assert(send(client, Void::Net::Method::Post,
a + "/admin/partition?node=c&partition=1")
.status == 200);
auto proposed = send(client, Void::Net::Method::Put,
a + "/peer/propose?key=k", "lost");
assert(proposed.status == 503);
assert(proposed.body.starts_with("no-quorum"));
auto read = client.get(a + "/peer/read?key=k", {auth()});
assert(read.has_value());
assert(read->status == 503);
// Heal and let the majority take over.
assert(send(client, Void::Net::Method::Post,
b + "/admin/partition?node=b&partition=0")
.status == 200);
assert(send(client, Void::Net::Method::Post,
b + "/admin/partition?node=c&partition=0")
.status == 200);
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
200);
assert(send(client, Void::Net::Method::Put,
b + "/peer/propose?key=k", "kept")
.status == 200);
auto read_after = client.get(b + "/peer/read?key=k", {auth()});
assert(read_after.has_value());
assert(read_after->status == 200);
assert(read_after->body == "kept");
(*fixture)->stop();
}
void crash_history_keeps_committed_replies()
{
auto fixture = ClusterFixture::create();
assert(fixture.has_value());
assert((*fixture)->start().has_value());
const std::string a = (*fixture)->endpoint("a");
const std::string b = (*fixture)->endpoint("b");
const std::string c = (*fixture)->endpoint("c");
Void::Net::HttpClient client;
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
200);
assert(send(client, Void::Net::Method::Put,
a + "/peer/propose?key=committed", "1")
.status == 200);
// One voter crashes: the majority still commits.
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=c")
.status == 200);
assert(send(client, Void::Net::Method::Put,
a + "/peer/propose?key=second", "2")
.status == 200);
// A second crash loses the majority: no durable reply.
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=b")
.status == 200);
assert(send(client, Void::Net::Method::Put,
a + "/peer/propose?key=third", "3")
.status == 503);
// Restart and re-elect: committed history is intact, the failed
// proposal was never applied.
assert(send(client, Void::Net::Method::Post,
b + "/admin/restart?node=b")
.status == 200);
assert(send(client, Void::Net::Method::Post,
c + "/admin/restart?node=c")
.status == 200);
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
200);
auto first = client.get(b + "/peer/read?key=committed", {auth()});
auto second = client.get(b + "/peer/read?key=second", {auth()});
auto third = client.get(b + "/peer/read?key=third", {auth()});
assert(first.has_value() && first->status == 200 &&
first->body == "1");
assert(second.has_value() && second->status == 200 &&
second->body == "2");
assert(third.has_value() && third->status == 404);
(*fixture)->stop();
}
} // namespace
int main()
{
three_real_listeners_serve_the_replicated_kv();
minority_leader_cannot_commit_or_read_over_http();
crash_history_keeps_committed_replies();
std::puts("distributed cluster fixture ok");
return 0;
}
@@ -0,0 +1,261 @@
#include "distributed_host/cluster_fixture.hpp"
#include <Void/Net/Http.hpp>
#include <cassert>
#include <cstdio>
#include <string>
#include <utility>
namespace
{
using namespace DistributedHost;
Void::Net::Header auth()
{
return Void::Net::Header{"authorization", "Bearer peer-secret"};
}
Void::Net::Response send(Void::Net::HttpClient& client,
Void::Net::Method method, const std::string& url,
std::string body = {})
{
Void::Net::Request request;
request.method = method;
request.url = url;
request.body = std::move(body);
request.headers.push_back(auth());
auto response = client.send(request);
assert(response.has_value());
return *response;
}
Void::Net::Response get(Void::Net::HttpClient& client,
const std::string& url)
{
auto response = client.get(url, {auth()});
assert(response.has_value());
return *response;
}
void publish_claim_ack_dispatch_over_http()
{
auto fixture = ClusterFixture::create();
assert(fixture.has_value());
assert((*fixture)->start().has_value());
const std::string a = (*fixture)->endpoint("a");
assert(!a.empty());
Void::Net::HttpClient client;
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
200);
auto published = send(client, Void::Net::Method::Post,
a + "/queue/publish?key=q1", "hello");
assert(published.status == 200);
assert(published.body == "job=q1");
// Idempotent by key.
auto duplicate = send(client, Void::Net::Method::Post,
a + "/queue/publish?key=q1", "ignored");
assert(duplicate.status == 200);
assert(duplicate.body == "job=q1");
auto claimed = send(client, Void::Net::Method::Post,
a + "/queue/claim?consumer=w1");
assert(claimed.status == 200);
assert(claimed.body.find("job=q1") != std::string::npos);
assert(claimed.body.find("payload=hello") != std::string::npos);
assert(claimed.body.find("attempts=1") != std::string::npos);
auto empty = send(client, Void::Net::Method::Post,
a + "/queue/claim?consumer=w1");
assert(empty.status == 204);
assert(send(client, Void::Net::Method::Post,
a + "/queue/ack?consumer=w1&id=q1")
.status == 200);
auto status = get(client, a + "/queue/status?id=q1");
assert(status.status == 200);
assert(status.body.find("state=done") != std::string::npos);
assert(status.body.find("outbox=1") != std::string::npos);
// Duplicate ack does not create a second outbox entry.
assert(send(client, Void::Net::Method::Post,
a + "/queue/ack?consumer=w1&id=q1")
.status == 200);
auto dispatched = send(client, Void::Net::Method::Post,
a + "/queue/dispatch");
assert(dispatched.status == 200);
assert(dispatched.body == "delivered=1");
auto again =
send(client, Void::Net::Method::Post, a + "/queue/dispatch");
assert(again.body == "delivered=0");
assert(get(client, a + "/queue/delivered").body == "q1\n");
// Every queue route is authenticated.
auto anonymous = client.get(a + "/queue/dlq");
assert(anonymous.has_value());
assert(anonymous->status == 401);
(*fixture)->stop();
}
void retry_then_dead_letter_over_http()
{
ClusterFixtureConfig config;
config.queue.max_attempts = 2;
auto fixture = ClusterFixture::create(config);
assert(fixture.has_value());
assert((*fixture)->start().has_value());
const std::string a = (*fixture)->endpoint("a");
Void::Net::HttpClient client;
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
200);
assert(send(client, Void::Net::Method::Post,
a + "/queue/publish?key=r1", "poison")
.status == 200);
assert(send(client, Void::Net::Method::Post,
a + "/queue/claim?consumer=w")
.status == 200);
auto retried = send(client, Void::Net::Method::Post,
a + "/queue/nack?consumer=w&id=r1", "boom");
assert(retried.status == 200);
assert(retried.body == "state=pending attempts=1");
assert(send(client, Void::Net::Method::Post,
a + "/queue/claim?consumer=w")
.status == 200);
auto dead = send(client, Void::Net::Method::Post,
a + "/queue/nack?consumer=w&id=r1", "boom again");
assert(dead.status == 200);
assert(dead.body == "state=dead attempts=2");
auto dlq = get(client, a + "/queue/dlq");
assert(dlq.status == 200);
assert(dlq.body.find("id=r1") != std::string::npos);
assert(dlq.body.find("reason=boom again") != std::string::npos);
assert(send(client, Void::Net::Method::Post,
a + "/queue/claim?consumer=w")
.status == 204);
(*fixture)->stop();
}
void partition_history_over_http()
{
auto fixture = ClusterFixture::create();
assert(fixture.has_value());
assert((*fixture)->start().has_value());
const std::string a = (*fixture)->endpoint("a");
const std::string b = (*fixture)->endpoint("b");
const std::string c = (*fixture)->endpoint("c");
Void::Net::HttpClient client;
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
200);
assert(send(client, Void::Net::Method::Post,
a + "/admin/partition?node=b&partition=1")
.status == 200);
assert(send(client, Void::Net::Method::Post,
a + "/admin/partition?node=c&partition=1")
.status == 200);
// Minority leader: no durable reply for the queue.
assert(send(client, Void::Net::Method::Post,
a + "/queue/publish?key=p1", "lost")
.status == 503);
// Heal and let the majority take over.
assert(send(client, Void::Net::Method::Post,
b + "/admin/partition?node=b&partition=0")
.status == 200);
assert(send(client, Void::Net::Method::Post,
b + "/admin/partition?node=c&partition=0")
.status == 200);
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
200);
assert(send(client, Void::Net::Method::Post,
b + "/queue/publish?key=p1", "kept")
.status == 200);
auto claimed = send(client, Void::Net::Method::Post,
b + "/queue/claim?consumer=w");
assert(claimed.status == 200);
assert(claimed.body.find("payload=kept") != std::string::npos);
(*fixture)->stop();
}
void crash_history_over_http()
{
auto fixture = ClusterFixture::create();
assert(fixture.has_value());
assert((*fixture)->start().has_value());
const std::string a = (*fixture)->endpoint("a");
const std::string b = (*fixture)->endpoint("b");
const std::string c = (*fixture)->endpoint("c");
Void::Net::HttpClient client;
assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status ==
200);
assert(send(client, Void::Net::Method::Post,
a + "/queue/publish?key=j1", "one")
.status == 200);
assert(send(client, Void::Net::Method::Post,
a + "/queue/claim?consumer=w")
.status == 200);
assert(send(client, Void::Net::Method::Post,
a + "/queue/ack?consumer=w&id=j1")
.status == 200);
// One crash keeps the majority: j2 is durably published.
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=c")
.status == 200);
assert(send(client, Void::Net::Method::Post,
a + "/queue/publish?key=j2", "two")
.status == 200);
// A second crash loses the majority: j3 has no durable reply.
assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=b")
.status == 200);
assert(send(client, Void::Net::Method::Post,
a + "/queue/publish?key=j3", "three")
.status == 503);
// Restart and re-elect: committed history is intact, the failed
// publish left no record.
assert(send(client, Void::Net::Method::Post,
b + "/admin/restart?node=b")
.status == 200);
assert(send(client, Void::Net::Method::Post,
c + "/admin/restart?node=c")
.status == 200);
assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status ==
200);
assert(get(client, b + "/queue/status?id=j1").body.find("state=done") !=
std::string::npos);
assert(get(client, b + "/queue/status?id=j2")
.body.find("state=pending") != std::string::npos);
assert(get(client, b + "/queue/status?id=j3").status == 404);
auto reclaimed = send(client, Void::Net::Method::Post,
b + "/queue/claim?consumer=w");
assert(reclaimed.status == 200);
assert(reclaimed.body.find("job=j2") != std::string::npos);
(*fixture)->stop();
}
} // namespace
int main()
{
publish_claim_ack_dispatch_over_http();
retry_then_dead_letter_over_http();
partition_history_over_http();
crash_history_over_http();
std::puts("distributed cluster queue ok");
return 0;
}
@@ -0,0 +1,316 @@
#include "distributed_host/host_graph.hpp"
#include <cassert>
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
namespace
{
using namespace DistributedHost;
/// Deterministic component fakes: they record nothing themselves (the
/// graph's history is the ordered record) but can fail at a chosen step.
struct FakeStorage final : StorageBackend {
bool fail_open{false};
bool fail_recover{false};
int opens{0};
int closes{0};
Void::Result::Result<void> open() override
{
++opens;
if (fail_open) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::io, "storage open failed"}};
}
return {};
}
Void::Result::Result<void> recover() override
{
if (fail_recover) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::corrupt,
"storage recovery required"}};
}
return {};
}
void close() noexcept override { ++closes; }
};
struct FakeTransport final : PeerTransport {
bool fail_listen{false};
bool fail_connect{false};
int closes{0};
Void::Result::Result<void> listen() override
{
if (fail_listen) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::io, "listen failed"}};
}
return {};
}
Void::Result::Result<void>
connect_peers(const std::vector<NodeId>& peers) override
{
if (fail_connect) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::io, "peer connect failed"}};
}
(void)peers;
return {};
}
void close() noexcept override { ++closes; }
};
struct FakeReplication final : ReplicationAdapter {
bool fail_start{false};
bool leader{true};
Role current_role{Role::Leader};
int stops{0};
Void::Result::Result<void> start() override
{
if (fail_start) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::internal,
"replication start failed"}};
}
return {};
}
Role role() const noexcept override { return current_role; }
bool leader_available() const noexcept override { return leader; }
void stop() noexcept override { ++stops; }
};
struct FakeDirectory final : DirectoryPublisher {
bool fail_publish{false};
int published{0};
int withdrawals{0};
Void::Result::Result<void> publish(const NodeId& self) override
{
(void)self;
++published;
if (fail_publish) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::io, "directory unavailable"}};
}
return {};
}
void withdraw() noexcept override { ++withdrawals; }
};
struct World {
FakeStorage storage;
FakeTransport transport;
FakeReplication replication;
FakeDirectory directory;
HostResources resources()
{
return HostResources{&storage, &transport, &replication,
&directory};
}
};
HostConfig config()
{
HostConfig cfg;
cfg.cluster = "test-cluster";
cfg.self = "node-1";
cfg.peers = {"node-2", "node-3"};
return cfg;
}
std::vector<std::string> expected_happy_start()
{
return {"storage.open", "storage.recover", "transport.listen",
"transport.connect_peers", "replication.start",
"replication.readiness", "directory.publish"};
}
void compose_validates_configuration()
{
World world;
HostConfig empty_cluster = config();
empty_cluster.cluster.clear();
assert(!DistributedHostGraph::compose(world.resources(), empty_cluster)
.has_value());
HostConfig self_as_peer = config();
self_as_peer.peers.push_back("node-1");
assert(!DistributedHostGraph::compose(world.resources(), self_as_peer)
.has_value());
HostConfig zero_deadline = config();
zero_deadline.startup_deadline = std::chrono::milliseconds{0};
assert(!DistributedHostGraph::compose(world.resources(), zero_deadline)
.has_value());
HostResources incomplete{&world.storage, nullptr, &world.replication,
nullptr};
assert(!DistributedHostGraph::compose(incomplete, config()).has_value());
}
void happy_path_starts_in_order_and_stops_in_reverse()
{
World world;
auto graph = DistributedHostGraph::compose(world.resources(), config());
assert(graph.has_value());
// Construction starts nothing.
assert(graph->history().empty());
assert(graph->readiness() == Readiness::Starting);
assert(graph->start().has_value());
assert(graph->readiness() == Readiness::WriteReady);
assert(graph->health().quorum_available);
assert(graph->health().started_components == 3);
assert(graph->history() == expected_happy_start());
graph->stop();
const std::vector<std::string> expected_stop{
"directory.withdraw", "replication.stop", "transport.close",
"storage.close"};
assert(graph->history().size() ==
expected_happy_start().size() + expected_stop.size());
assert(std::equal(expected_stop.begin(), expected_stop.end(),
graph->history().end() - expected_stop.size()));
assert(graph->readiness() == Readiness::Stopped);
assert(graph->health().started_components == 0);
assert(world.storage.closes == 1);
assert(world.transport.closes == 1);
assert(world.replication.stops == 1);
// Idempotent.
graph->stop();
assert(world.storage.closes == 1);
}
void follower_is_healthy_but_not_write_ready()
{
World world;
world.replication.leader = false;
world.replication.current_role = Role::Follower;
HostConfig cfg = config();
cfg.require_leader_readiness = false;
auto graph = DistributedHostGraph::compose(world.resources(), cfg);
assert(graph.has_value());
assert(graph->start().has_value());
assert(graph->readiness() == Readiness::FollowerHealthy);
assert(!graph->health().quorum_available);
}
void missing_leader_path_fails_startup_and_unwinds()
{
World world;
world.replication.leader = false;
auto graph = DistributedHostGraph::compose(world.resources(), config());
assert(graph.has_value());
auto started = graph->start();
assert(!started.has_value());
assert(graph->readiness() == Readiness::Failed);
assert(graph->health().last_error.find("no leader path") !=
std::string::npos);
// Everything started before the failure is closed in reverse order.
const std::vector<std::string> expected{
"storage.open", "storage.recover", "transport.listen",
"transport.connect_peers", "replication.start", "replication.stop",
"transport.close", "storage.close"};
assert(graph->history() == expected);
assert(world.storage.closes == 1);
assert(world.transport.closes == 1);
assert(world.replication.stops == 1);
}
void storage_recovery_failure_unwinds_opened_storage()
{
World world;
world.storage.fail_recover = true;
auto graph = DistributedHostGraph::compose(world.resources(), config());
assert(graph.has_value());
assert(!graph->start().has_value());
assert(graph->readiness() == Readiness::Failed);
assert(graph->health().last_error == "storage recovery required");
const std::vector<std::string> expected{"storage.open",
"storage.close"};
assert(graph->history() == expected);
assert(world.storage.closes == 1);
}
void peer_connect_failure_keeps_original_error()
{
World world;
world.transport.fail_connect = true;
auto graph = DistributedHostGraph::compose(world.resources(), config());
assert(graph.has_value());
assert(!graph->start().has_value());
assert(graph->health().last_error == "peer connect failed");
assert(graph->readiness() == Readiness::Failed);
const std::vector<std::string> expected{
"storage.open", "storage.recover", "transport.listen",
"transport.close", "storage.close"};
assert(graph->history() == expected);
}
void discovery_failure_does_not_weaken_quorum()
{
World world;
world.directory.fail_publish = true;
auto graph = DistributedHostGraph::compose(world.resources(), config());
assert(graph.has_value());
assert(graph->start().has_value());
// Still write-ready: discovery is an observation adapter.
assert(graph->readiness() == Readiness::WriteReady);
assert(graph->health().quorum_available);
assert(graph->health().last_error == "directory unavailable");
assert(world.directory.published == 1);
// Nothing to withdraw: the publication was never recorded.
graph->stop();
assert(world.directory.withdrawals == 0);
}
void discovery_can_be_disabled()
{
World world;
HostConfig cfg = config();
cfg.publish_discovery = false;
auto graph = DistributedHostGraph::compose(world.resources(), cfg);
assert(graph.has_value());
assert(graph->start().has_value());
assert(world.directory.published == 0);
for (const auto& step : graph->history()) {
assert(step != "directory.publish");
}
}
void double_start_is_rejected()
{
World world;
auto graph = DistributedHostGraph::compose(world.resources(), config());
assert(graph.has_value());
assert(graph->start().has_value());
assert(!graph->start().has_value());
graph->stop();
assert(!graph->start().has_value());
}
} // namespace
int main()
{
compose_validates_configuration();
happy_path_starts_in_order_and_stops_in_reverse();
follower_is_healthy_but_not_write_ready();
missing_leader_path_fails_startup_and_unwinds();
storage_recovery_failure_unwinds_opened_storage();
peer_connect_failure_keeps_original_error();
discovery_failure_does_not_weaken_quorum();
discovery_can_be_disabled();
double_start_is_rejected();
std::puts("distributed host graph ok");
return 0;
}
@@ -0,0 +1,465 @@
// Multi-process acceptance harness for the distributed KV reference.
//
// Spawns three independent voter-agent processes, drives elections and
// quorum replication over authenticated HTTP, kills and restarts processes
// with SIGKILL, and checks a single-client history: every acknowledged write
// is observed by later reads and survives crash/restart, and a write without
// a durable reply is never observed half-applied.
//
// multi_process_test <path-to-distributed_voter_agent>
#include <Void/Net/Http.hpp>
#include <Void/System/Process.hpp>
#include <csignal>
#include <unistd.h>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
namespace
{
constexpr std::string_view kToken{"peer-secret"};
struct Agent {
std::string id;
std::filesystem::path directory;
std::uint16_t port{0};
std::optional<Void::Process::Child> child;
bool alive{false};
};
struct LogEntry {
std::uint64_t term{0};
std::uint64_t index{0};
std::string key;
std::string value;
};
struct State {
std::uint64_t term{0};
std::uint64_t last_index{0};
std::uint64_t last_term{0};
std::uint64_t commit{0};
std::size_t entries{0};
};
[[nodiscard]] std::optional<std::uint64_t>
field(std::string_view text, std::string_view name)
{
const std::string needle = std::string{name} + "=";
const std::size_t at = text.find(needle);
if (at == std::string_view::npos) {
return std::nullopt;
}
std::uint64_t value = 0;
const char* begin = text.data() + at + needle.size();
const auto parsed = std::from_chars(begin, text.data() + text.size(), value);
if (parsed.ec != std::errc{}) {
return std::nullopt;
}
return value;
}
class Harness
{
public:
Harness(std::string agent_binary, std::size_t count)
{
const auto root =
std::filesystem::temp_directory_path() /
("void-mp-" + std::to_string(::getpid()));
std::filesystem::remove_all(root);
for (std::size_t i = 0; i < count; ++i) {
Agent agent;
agent.id = "node-" + std::to_string(i);
agent.directory = root / agent.id;
std::filesystem::create_directories(agent.directory);
m_agents.push_back(std::move(agent));
}
m_agent_binary = std::move(agent_binary);
}
~Harness()
{
for (auto& agent : m_agents) {
if (agent.child && agent.alive) {
(void)::kill(static_cast<pid_t>(agent.child->pid()),
SIGKILL);
(void)agent.child->wait_blocking(
std::chrono::seconds{5});
}
}
}
[[nodiscard]] bool launch(std::size_t index)
{
Agent& agent = m_agents[index];
std::filesystem::remove(agent.directory / "port");
Void::Process::SpawnOptions options;
options.executable = m_agent_binary;
options.arguments = {"--dir", agent.directory.string(),
"--port", "0", "--token",
std::string{kToken}, "--parent",
std::to_string(::getpid())};
options.stdin_pipe = false;
options.stdout_pipe = false;
options.stderr_pipe = false;
auto child = Void::Process::spawn(options);
if (!child) {
return false;
}
agent.child.emplace(std::move(*child));
agent.alive = true;
// The agent publishes its bound port once serving.
for (int attempt = 0; attempt < 500; ++attempt) {
const auto port_file = agent.directory / "port";
if (std::filesystem::exists(port_file)) {
std::FILE* file = std::fopen(port_file.c_str(), "r");
if (file != nullptr) {
unsigned int port = 0;
const int matched = std::fscanf(file, "%u", &port);
std::fclose(file);
if (matched == 1) {
agent.port = static_cast<std::uint16_t>(port);
return agent.port != 0;
}
}
}
std::this_thread::sleep_for(
std::chrono::milliseconds{10});
}
return false;
}
void kill(std::size_t index)
{
Agent& agent = m_agents[index];
if (!agent.child || !agent.alive) {
return;
}
(void)::kill(static_cast<pid_t>(agent.child->pid()), SIGKILL);
(void)agent.child->wait_blocking(std::chrono::seconds{5});
agent.child.reset();
agent.alive = false;
}
[[nodiscard]] std::string endpoint(std::size_t index) const
{
return "http://127.0.0.1:" +
std::to_string(m_agents[index].port);
}
[[nodiscard]] bool alive(std::size_t index) const
{
return m_agents[index].alive;
}
[[nodiscard]] std::size_t size() const { return m_agents.size(); }
// ── RPC ─────────────────────────────────────────────────────────
[[nodiscard]] std::optional<std::string>
get(std::size_t index, const std::string& path)
{
auto response = m_client.get(
endpoint(index) + path,
{Void::Net::Header{"authorization",
"Bearer " + std::string{kToken}}});
if (!response.has_value() || response->status != 200) {
return std::nullopt;
}
return response->body;
}
[[nodiscard]] int post(std::size_t index, const std::string& path,
std::string body = {})
{
Void::Net::Request request;
request.method = Void::Net::Method::Post;
request.url = endpoint(index) + path;
request.body = std::move(body);
request.headers.push_back(Void::Net::Header{
"authorization", "Bearer " + std::string{kToken}});
auto response = m_client.send(request);
if (!response.has_value()) {
return -1;
}
return response->status;
}
[[nodiscard]] std::optional<State> state(std::size_t index)
{
auto body = get(index, "/voter/state");
if (!body) {
return std::nullopt;
}
State out;
out.term = field(*body, "term").value_or(0);
out.last_index = field(*body, "last_index").value_or(0);
out.last_term = field(*body, "last_term").value_or(0);
out.commit = field(*body, "commit").value_or(0);
out.entries = static_cast<std::size_t>(
field(*body, "entries").value_or(0));
return out;
}
[[nodiscard]] int vote(std::size_t index, std::uint64_t term,
std::string_view candidate,
std::uint64_t last_index,
std::uint64_t last_term)
{
return post(index,
"/voter/vote?term=" + std::to_string(term) +
"&candidate=" + std::string{candidate} +
"&last_index=" + std::to_string(last_index) +
"&last_term=" + std::to_string(last_term));
}
[[nodiscard]] int append(std::size_t index, std::uint64_t term,
std::uint64_t prev_index,
std::uint64_t prev_term,
std::uint64_t commit,
std::string_view entries)
{
return post(index,
"/voter/append?term=" + std::to_string(term) +
"&prev_index=" + std::to_string(prev_index) +
"&prev_term=" + std::to_string(prev_term) +
"&commit=" + std::to_string(commit),
std::string{entries});
}
[[nodiscard]] std::optional<std::string>
value(std::size_t index, std::string_view key)
{
return get(index,
"/voter/value?key=" + std::string{key});
}
private:
std::string m_agent_binary;
std::vector<Agent> m_agents;
Void::Net::HttpClient m_client;
};
/// Single-client linearizable reference: sequential operations, one
/// leader at a time.
class Driver
{
public:
explicit Driver(Harness& harness) : m_harness(harness) {}
[[nodiscard]] bool elect(std::size_t candidate)
{
const auto candidate_state = m_harness.state(candidate);
if (!candidate_state) {
return false;
}
m_term = std::max(m_term, candidate_state->term) + 1;
std::size_t votes = 0;
for (std::size_t i = 0; i < m_harness.size(); ++i) {
if (!m_harness.alive(i)) {
continue;
}
if (m_harness.vote(i, m_term,
"node-" + std::to_string(candidate),
candidate_state->last_index,
candidate_state->last_term) == 200) {
++votes;
}
}
if (votes * 2 <= m_harness.size()) {
return false;
}
m_leader = candidate;
return true;
}
enum class Write { Applied, NoQuorum, NotLeader };
[[nodiscard]] Write propose(std::string key, std::string value)
{
if (!m_leader.has_value() || !m_harness.alive(*m_leader)) {
return Write::NotLeader;
}
const LogEntry entry{
.term = m_term,
.index = m_commit + 1,
.key = std::move(key),
.value = std::move(value)};
const std::string line =
std::to_string(entry.term) + "," +
std::to_string(entry.index) + "," + entry.key + "," +
entry.value + "\n";
auto line_of = [](const LogEntry& e) {
return std::to_string(e.term) + "," +
std::to_string(e.index) + "," + e.key + "," + e.value +
"\n";
};
std::size_t acks = 0;
for (std::size_t i = 0; i < m_harness.size(); ++i) {
if (!m_harness.alive(i)) {
continue;
}
int status = m_harness.append(i, m_term, m_commit, m_prev_term,
m_commit, line);
if (status == 409) {
// The follower is behind: back off to its last entry and
// replay everything it is missing (Raft catch-up).
const auto peer = m_harness.state(i);
if (peer) {
std::string catchup;
for (const auto& acked : m_acknowledged) {
if (acked.index > peer->last_index) {
catchup += line_of(acked);
}
}
catchup += line;
status = m_harness.append(
i, m_term, peer->last_index, peer->last_term,
m_commit, catchup);
}
}
if (status == 200) {
++acks;
}
}
if (acks * 2 <= m_harness.size()) {
return Write::NoQuorum;
}
// Majority acknowledged: publish the commit index so every
// reachable voter applies the entry (AppendEntries carries it).
m_commit = entry.index;
for (std::size_t i = 0; i < m_harness.size(); ++i) {
if (!m_harness.alive(i)) {
continue;
}
(void)m_harness.append(i, m_term, entry.index, entry.term,
m_commit, {});
}
m_prev_term = entry.term;
m_acknowledged.push_back(entry);
return Write::Applied;
}
[[nodiscard]] std::optional<std::string> read(std::string_view key)
{
if (!m_leader.has_value() || !m_harness.alive(*m_leader)) {
return std::nullopt;
}
// Confirm leadership in this term with a majority heartbeat.
std::size_t reachable = 0;
for (std::size_t i = 0; i < m_harness.size(); ++i) {
if (!m_harness.alive(i)) {
continue;
}
const auto peer = m_harness.state(i);
if (!peer || peer->term > m_term) {
return std::nullopt;
}
++reachable;
}
if (reachable * 2 <= m_harness.size()) {
return std::nullopt;
}
return m_harness.value(*m_leader, key);
}
[[nodiscard]] const std::vector<LogEntry>& acknowledged() const
{
return m_acknowledged;
}
[[nodiscard]] std::optional<std::string>
latest_acknowledged(std::string_view key) const
{
for (auto it = m_acknowledged.rbegin();
it != m_acknowledged.rend(); ++it) {
if (it->key == key) {
return it->value;
}
}
return std::nullopt;
}
private:
Harness& m_harness;
std::uint64_t m_term{0};
std::uint64_t m_commit{0};
std::uint64_t m_prev_term{0};
std::optional<std::size_t> m_leader;
std::vector<LogEntry> m_acknowledged;
};
} // namespace
int main(int argc, char** argv)
{
if (argc < 2) {
std::fprintf(stderr,
"usage: multi_process_test <voter-agent-binary>\n");
return 2;
}
Harness harness{argv[1], 3};
for (std::size_t i = 0; i < harness.size(); ++i) {
assert(harness.launch(i));
}
Driver driver{harness};
// Majority election and a durable first write.
assert(driver.elect(0));
assert(driver.propose("k", "v1") == Driver::Write::Applied);
assert(driver.read("k") == std::optional<std::string>{"v1"});
// One process dies: the write is still durably acknowledged.
harness.kill(2);
assert(driver.propose("k", "v2") == Driver::Write::Applied);
assert(driver.read("k") == std::optional<std::string>{"v2"});
// A second death loses quorum: no durable reply, no readable value.
harness.kill(1);
assert(driver.propose("k", "v3") == Driver::Write::NoQuorum);
assert(!driver.read("k").has_value());
// Restart the killed processes: durable state comes back from disk.
assert(harness.launch(1));
assert(harness.launch(2));
// The recovered majority still holds every acknowledged write.
assert(driver.elect(1));
const auto recovered = driver.read("k");
assert(recovered.has_value());
// Never the unacknowledged write.
assert(*recovered != "v3");
assert(*recovered == driver.latest_acknowledged("k"));
// The recovered cluster keeps serving new writes.
assert(driver.propose("k", "v4") == Driver::Write::Applied);
assert(driver.read("k") == std::optional<std::string>{"v4"});
assert(driver.propose("other", "x") == Driver::Write::Applied);
assert(driver.read("other") == std::optional<std::string>{"x"});
// Every acknowledged entry is present on the restarted majority.
for (std::size_t i = 0; i < harness.size(); ++i) {
if (!harness.alive(i)) {
continue;
}
const auto state = harness.state(i);
assert(state.has_value());
assert(state->last_index >= driver.acknowledged().back().index);
}
std::puts("distributed multi-process acceptance ok");
return 0;
}
@@ -0,0 +1,142 @@
#include "distributed_host/operations.hpp"
#include <cassert>
#include <cstdio>
#include <string>
namespace
{
using namespace DistributedHost;
ClusterIdentity identity()
{
return ClusterIdentity{"prod-cluster", {"a", "b", "c"}};
}
void backup_and_restore_retains_identity_and_state()
{
ReplicatedKvCluster source{{"a", "b", "c"}};
assert(source.elect("a").has_value());
assert(source.propose("a", "x", std::string{"1"}).outcome ==
KvWriteOutcome::Applied);
assert(source.propose("a", "y", std::string{"2"}).outcome ==
KvWriteOutcome::Applied);
assert(source.propose("a", "z", std::string{"3"}).outcome ==
KvWriteOutcome::Applied);
assert(source.propose("a", "y", std::nullopt).outcome ==
KvWriteOutcome::Applied);
auto backup = capture_backup(source, "a", identity());
assert(backup.has_value());
assert(backup->identity == identity());
assert(backup->commit_index == source.committed_index());
assert(backup->state.size() == 2);
assert(!backup->state.contains("y"));
// Restore rehearsal into a separately started cluster.
ReplicatedKvCluster target{{"a", "b", "c"}};
assert(target.elect("a").has_value());
auto restored = restore_backup(target, "a", *backup, identity());
assert(restored.has_value());
assert(*restored == 2);
auto x = target.quorum_read("a", "x");
auto z = target.quorum_read("a", "z");
auto y = target.quorum_read("a", "y");
assert(x.has_value() && x->has_value() && **x == "1");
assert(z.has_value() && z->has_value() && **z == "3");
assert(y.has_value() && !y->has_value());
// A different cluster identity is refused, so histories cannot merge.
ClusterIdentity staging{"staging-cluster", {"a", "b", "c"}};
assert(!restore_backup(target, "a", *backup, staging).has_value());
ClusterIdentity fewer_voters{"prod-cluster", {"a", "b"}};
assert(!restore_backup(target, "a", *backup, fewer_voters).has_value());
}
void backup_without_quorum_fails()
{
ReplicatedKvCluster source{{"a", "b", "c"}};
assert(source.elect("a").has_value());
source.set_partition("b", 1);
source.set_partition("c", 1);
auto backup = capture_backup(source, "a", identity());
assert(!backup.has_value());
}
void trust_rotation_overlaps_then_revokes()
{
TrustStore trust{{"old-fp"}};
assert(trust.trusted("old-fp"));
assert(!trust.trusted("new-fp"));
assert(!trust.trusted(""));
// Empty rotation is rejected: verification is never disabled.
assert(!trust.begin_rotation({}).has_value());
auto generation = trust.begin_rotation({"new-fp"});
assert(generation.has_value());
// Overlap: both generations remain trusted while connections drain.
assert(trust.trusted("old-fp"));
assert(trust.trusted("new-fp"));
assert(trust.active_generations() == 2);
assert(trust.complete_rotation(*generation).has_value());
assert(!trust.trusted("old-fp"));
assert(trust.trusted("new-fp"));
assert(trust.active_generations() == 1);
assert(!trust.complete_rotation(99).has_value());
// An empty store trusts nothing.
TrustStore empty;
assert(!empty.trusted("anything"));
}
void mixed_version_rollout_readers_first()
{
RolloutGate gate{{"a", "b", "c"},
VersionPolicy{.format_version = 2, .min_reader = 1}};
assert(!gate.all_advertised());
assert(gate.report_version("a", 2).has_value());
assert(gate.report_version("b", 1).has_value());
assert(gate.report_version("c", 1).has_value());
// Old readers can still read the durable format.
assert(gate.admit_read("b").has_value());
// But new commands wait for every voter.
assert(!gate.admit_new_command("a").has_value());
assert(!gate.all_advertised());
assert(gate.report_version("b", 2).has_value());
assert(gate.report_version("c", 2).has_value());
assert(gate.admit_new_command("a").has_value());
assert(gate.all_advertised());
// Unknown voters are never assumed current.
assert(!gate.report_version("d", 2).has_value());
assert(!gate.admit_read("d").has_value());
}
void reader_floor_is_enforced()
{
RolloutGate gate{{"a"}, VersionPolicy{.format_version = 2,
.min_reader = 2}};
assert(gate.report_version("a", 1).has_value());
assert(!gate.admit_read("a").has_value());
assert(gate.report_version("a", 2).has_value());
assert(gate.admit_read("a").has_value());
}
} // namespace
int main()
{
backup_and_restore_retains_identity_and_state();
backup_without_quorum_fails();
trust_rotation_overlaps_then_revokes();
mixed_version_rollout_readers_first();
reader_floor_is_enforced();
std::puts("distributed operations ok");
return 0;
}
@@ -0,0 +1,171 @@
#include "distributed_host/range_placement.hpp"
#include <cassert>
#include <cstdio>
#include <string>
namespace
{
using namespace DistributedHost;
RangeDirectory directory()
{
RangeDirectory dir{{"a", "b", "c"}};
assert(dir.assign(KeyRange{"a", "m"}, "a").has_value());
assert(dir.assign(KeyRange{"m", "z"}, "b").has_value());
return dir;
}
void ranges_do_not_overlap_and_must_have_known_owners()
{
auto dir = directory();
assert(*dir.owner_of("apple") == "a");
assert(*dir.owner_of("monkey") == "b");
assert(!dir.owner_of("zebra").has_value()); // outside [a, z)
assert(!dir.assign(KeyRange{"l", "n"}, "c").has_value());
assert(!dir.assign(KeyRange{"n", "p"}, "unknown").has_value());
assert(!dir.assign(KeyRange{"p", "p"}, "a").has_value());
assert(dir.ranges().size() == 2);
}
void move_freezes_writes_until_completion()
{
auto dir = directory();
auto move = dir.begin_move(KeyRange{"a", "m"}, "c");
assert(move.has_value());
// Writes in the moving range are rejected; reads stay with the source.
assert(!dir.admit_write("apple").has_value());
assert(dir.admit_read("apple").has_value());
assert(*dir.owner_of("apple") == "a");
// Other ranges are unaffected.
assert(dir.admit_write("monkey").has_value());
// Completion requires a verified copy.
assert(!dir.complete(*move).has_value());
assert(!dir.verify(*move, 5).has_value()); // nothing transferred
assert(dir.transfer(*move, 3).has_value());
assert(!dir.verify(*move, 2).has_value()); // count mismatch
assert(dir.verify(*move, 3).has_value());
assert(dir.complete(*move).has_value());
assert(*dir.owner_of("apple") == "c");
assert(dir.admit_write("apple").has_value());
const auto record = dir.move(*move);
assert(record.has_value());
assert(record->phase == MovePhase::Completed);
assert(record->transferred == 3);
}
void crash_before_verification_rolls_back()
{
auto dir = directory();
auto move = dir.begin_move(KeyRange{"a", "m"}, "c");
assert(move.has_value());
assert(dir.transfer(*move, 2).has_value());
// Simulated restart of the move owner: no verified copy exists.
auto recovered = dir.recover(*move);
assert(recovered.has_value());
assert(*recovered == RangeDirectory::Recovery::RolledBack);
assert(*dir.owner_of("apple") == "a");
assert(dir.admit_write("apple").has_value());
assert(dir.move(*move)->phase == MovePhase::Aborted);
}
void crash_after_verification_rolls_forward()
{
auto dir = directory();
auto move = dir.begin_move(KeyRange{"m", "z"}, "a");
assert(move.has_value());
assert(dir.transfer(*move, 4).has_value());
assert(dir.verify(*move, 4).has_value());
auto recovered = dir.recover(*move);
assert(recovered.has_value());
assert(*recovered == RangeDirectory::Recovery::RolledForward);
assert(*dir.owner_of("monkey") == "a");
assert(dir.admit_write("monkey").has_value());
assert(dir.move(*move)->phase == MovePhase::Completed);
}
void explicit_abort_restores_the_source()
{
auto dir = directory();
auto move = dir.begin_move(KeyRange{"a", "m"}, "c");
assert(move.has_value());
dir.abort(*move, "operator cancelled");
assert(*dir.owner_of("apple") == "a");
assert(dir.admit_write("apple").has_value());
assert(dir.move(*move)->note == "operator cancelled");
// A completed move cannot be aborted.
auto second = dir.begin_move(KeyRange{"a", "m"}, "c");
assert(second.has_value());
assert(dir.transfer(*second, 1).has_value());
assert(dir.verify(*second, 1).has_value());
assert(dir.complete(*second).has_value());
dir.abort(*second, "too late");
assert(*dir.owner_of("apple") == "c");
}
void one_active_move_per_range()
{
auto dir = directory();
assert(dir.begin_move(KeyRange{"a", "m"}, "c").has_value());
auto second = dir.begin_move(KeyRange{"a", "m"}, "b");
assert(!second.has_value());
assert(second.error().kind() == Void::Result::ErrorKind::conflict);
// Moving to the current owner is refused.
auto same = dir.begin_move(KeyRange{"m", "z"}, "b");
assert(!same.has_value());
}
void directory_survives_a_replicated_restart()
{
ReplicatedKvCluster cluster{{"a", "b", "c"}};
assert(cluster.elect("a").has_value());
auto original = directory();
assert(original.persist(cluster, "a").has_value());
// A new directory instance loads the replicated ownership map.
RangeDirectory restored{{"a", "b", "c"}};
assert(restored.load(cluster, "a").has_value());
assert(restored.ranges().size() == 2);
assert(*restored.owner_of("apple") == "a");
assert(*restored.owner_of("monkey") == "b");
// A directory whose voters do not include the stored owners is
// rejected rather than partially installed.
RangeDirectory narrower{{"a"}};
assert(!narrower.load(cluster, "a").has_value());
assert(narrower.ranges().empty());
// Corrupt persisted content is rejected.
assert(cluster.propose("a", std::string{RangeDirectory::default_key},
std::string{"broken-record\n"})
.outcome == KvWriteOutcome::Applied);
RangeDirectory corrupt_dir{{"a", "b", "c"}};
assert(!corrupt_dir.load(cluster, "a").has_value());
assert(corrupt_dir.ranges().empty());
// Persisting without quorum is not durable.
cluster.set_partition("b", 1);
cluster.set_partition("c", 1);
assert(!original.persist(cluster, "a").has_value());
}
} // namespace
int main()
{
ranges_do_not_overlap_and_must_have_known_owners();
move_freezes_writes_until_completion();
crash_before_verification_rolls_back();
crash_after_verification_rolls_forward();
explicit_abort_restores_the_source();
one_active_move_per_range();
directory_survives_a_replicated_restart();
std::puts("distributed range placement ok");
return 0;
}
@@ -0,0 +1,192 @@
#include "distributed_host/replicated_kv.hpp"
#include <cassert>
#include <cstdio>
#include <optional>
#include <string>
namespace
{
using namespace DistributedHost;
ReplicatedKvCluster cluster()
{
return ReplicatedKvCluster{{"a", "b", "c"}};
}
void leader_commits_with_a_majority()
{
auto kv = cluster();
assert(kv.elect("a").has_value());
const auto reply = kv.propose("a", "key", std::string{"value"});
assert(reply.outcome == KvWriteOutcome::Applied);
assert(reply.index == 1);
assert(kv.committed_index() == 1);
auto read = kv.quorum_read("a", "key");
assert(read.has_value());
assert(read->has_value());
assert(**read == "value");
// Followers applied the committed entry too.
assert(kv.snapshot("b")->kv.at("key") == "value");
assert(kv.snapshot("c")->kv.at("key") == "value");
assert(kv.snapshot("b")->applied_index ==
kv.snapshot("b")->commit_index);
}
void minority_leader_cannot_commit_or_read()
{
auto kv = cluster();
assert(kv.elect("a").has_value());
kv.set_partition("b", 1);
kv.set_partition("c", 1);
const auto reply = kv.propose("a", "key", std::string{"lost"});
assert(reply.outcome == KvWriteOutcome::NoQuorum);
// Never applied without a majority.
assert(kv.snapshot("a")->kv.empty());
auto read = kv.quorum_read("a", "key");
assert(!read.has_value());
assert(read.error().kind() == Void::Result::ErrorKind::overloaded);
}
void new_majority_elects_and_preserves_committed_history()
{
auto kv = cluster();
assert(kv.elect("a").has_value());
assert(kv.propose("a", "key", std::string{"one"}).outcome ==
KvWriteOutcome::Applied);
// Isolate the old leader; the other two form a majority.
kv.set_partition("a", 1);
assert(kv.elect("b").has_value());
assert(kv.propose("b", "key", std::string{"two"}).outcome ==
KvWriteOutcome::Applied);
// Heal: the next heartbeat from the new leader delivers the committed
// entry and term to the stale node, which steps down.
kv.set_partition("a", 0);
assert(kv.heartbeat("b").has_value());
assert(kv.snapshot("a")->role == Role::Follower);
assert(kv.snapshot("a")->kv.at("key") == "two");
const auto stale = kv.propose("a", "key", std::string{"stale"});
assert(stale.outcome == KvWriteOutcome::NotLeader);
auto read = kv.quorum_read("b", "key");
assert(read.has_value() && read->has_value());
assert(**read == "two");
// Committed history was never lost on the old leader either.
assert(kv.snapshot("a")->kv.at("key") == "two");
}
void uncommitted_entry_is_overwritten_and_never_applied()
{
auto kv = cluster();
assert(kv.elect("a").has_value());
kv.set_partition("b", 1);
kv.set_partition("c", 1);
const auto ghost = kv.propose("a", "key", std::string{"ghost"});
assert(ghost.outcome == KvWriteOutcome::NoQuorum);
assert(!kv.snapshot("a")->kv.contains("key"));
const std::size_t ghost_log = kv.snapshot("a")->log_size;
kv.set_partition("b", 0);
kv.set_partition("c", 0);
assert(kv.elect("b").has_value());
assert(kv.propose("b", "key", std::string{"real"}).outcome ==
KvWriteOutcome::Applied);
// The stale suffix was truncated and replaced, never applied.
const auto old = kv.snapshot("a");
assert(old->log_size <= ghost_log);
assert(old->kv.at("key") == "real");
auto read = kv.quorum_read("b", "key");
assert(read.has_value() && read->has_value() && **read == "real");
}
void crash_and_restart_preserve_committed_state()
{
auto kv = cluster();
assert(kv.elect("a").has_value());
assert(kv.propose("a", "x", std::string{"1"}).outcome ==
KvWriteOutcome::Applied);
assert(kv.propose("a", "y", std::string{"2"}).outcome ==
KvWriteOutcome::Applied);
for (const auto& id : kv.voters()) {
kv.crash(id);
}
for (const auto& id : kv.voters()) {
kv.restart(id);
}
assert(kv.elect("c").has_value());
auto x = kv.quorum_read("c", "x");
auto y = kv.quorum_read("c", "y");
assert(x.has_value() && x->has_value() && **x == "1");
assert(y.has_value() && y->has_value() && **y == "2");
}
void follower_cannot_serve_consistent_read()
{
auto kv = cluster();
assert(kv.elect("a").has_value());
auto read = kv.quorum_read("b", "key");
assert(!read.has_value());
assert(read.error().kind() == Void::Result::ErrorKind::conflict);
}
void election_without_majority_or_voter_fails()
{
auto kv = cluster();
kv.set_partition("b", 1);
kv.set_partition("c", 1);
assert(!kv.elect("a").has_value());
auto unknown = kv.elect("nope");
assert(!unknown.has_value());
assert(unknown.error().kind() == Void::Result::ErrorKind::not_found);
}
void write_requires_a_leader() {
auto kv = cluster();
assert(kv.elect("a").has_value());
assert(kv.propose("b", "key", std::string{"v"}).outcome ==
KvWriteOutcome::NotLeader);
assert(kv.propose("missing", "key", std::string{"v"}).outcome ==
KvWriteOutcome::NodeDown);
}
void deletes_replicate_as_tombstones()
{
auto kv = cluster();
assert(kv.elect("a").has_value());
assert(kv.propose("a", "key", std::string{"value"}).outcome ==
KvWriteOutcome::Applied);
assert(kv.propose("a", "key", std::nullopt).outcome ==
KvWriteOutcome::Applied);
auto read = kv.quorum_read("a", "key");
assert(read.has_value());
assert(!read->has_value());
assert(!kv.snapshot("b")->kv.contains("key"));
}
} // namespace
int main()
{
leader_commits_with_a_majority();
minority_leader_cannot_commit_or_read();
new_majority_elects_and_preserves_committed_history();
uncommitted_entry_is_overwritten_and_never_applied();
crash_and_restart_preserve_committed_state();
follower_cannot_serve_consistent_read();
election_without_majority_or_voter_fails();
write_requires_a_leader();
deletes_replicate_as_tombstones();
std::puts("distributed replicated kv ok");
return 0;
}
@@ -0,0 +1,205 @@
#include "distributed_host/replicated_queue.hpp"
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
namespace
{
using namespace DistributedHost;
struct World {
ReplicatedKvCluster cluster{{"a", "b", "c"}};
QueueConfig config{.max_attempts = 2, .max_jobs = 8};
World()
{
assert(cluster.elect("a").has_value());
}
ReplicatedQueue queue()
{
return ReplicatedQueue{cluster, "a", config};
}
};
void publish_claim_ack_dispatches_one_effect()
{
World world;
auto queue = world.queue();
auto id = queue.publish("payload", "job-1");
assert(id.has_value());
// Idempotent publish: the same key never creates a second job.
auto duplicate = queue.publish("different", "job-1");
assert(duplicate.has_value());
assert(*duplicate == *id);
auto claimed = queue.claim("worker-1");
assert(claimed.has_value() && claimed->has_value());
assert((*claimed)->id == *id);
assert((*claimed)->state == JobState::InFlight);
assert((*claimed)->consumer == "worker-1");
assert((*claimed)->attempts == 1);
// No other pending job.
auto none = queue.claim("worker-1");
assert(none.has_value() && !none->has_value());
assert(queue.ack("worker-1", *id).has_value());
const auto done = queue.status(*id);
assert(done.has_value());
assert(done->state == JobState::Done);
assert(done->outbox_pending);
// Duplicate ack: the inbox already recorded it, no second outbox row.
assert(queue.ack("worker-1", *id).has_value());
int delivered = 0;
auto dispatched = queue.dispatch_outbox([&](const QueueJob& job) {
++delivered;
assert(job.id == *id);
assert(job.payload == "payload");
});
assert(dispatched.has_value());
assert(*dispatched == 1);
assert(delivered == 1);
// The outbox entry was marked delivered.
auto redispatch = queue.dispatch_outbox(
[&](const QueueJob&) { ++delivered; });
assert(redispatch.has_value());
assert(*redispatch == 0);
assert(delivered == 1);
}
void retries_then_dead_letters()
{
World world;
auto queue = world.queue();
auto id = queue.publish("poison", "retry-1");
assert(id.has_value());
assert(queue.claim("w").has_value());
auto retried = queue.nack("w", *id, "boom");
assert(retried.has_value());
assert(retried->state == JobState::Pending);
assert(retried->attempts == 1);
assert(queue.claim("w").has_value());
auto dead = queue.nack("w", *id, "boom again");
assert(dead.has_value());
assert(dead->state == JobState::Dead);
assert(dead->attempts == 2);
assert(dead->reason == "boom again");
auto letters = queue.dead_letters();
assert(letters.has_value());
assert(letters->size() == 1);
assert((*letters)[0].id == *id);
// Dead jobs are no longer claimable.
auto none = queue.claim("w");
assert(none.has_value() && !none->has_value());
}
void crashed_consumer_is_recovered()
{
World world;
auto queue = world.queue();
auto id = queue.publish("work", "recover-1");
assert(id.has_value());
auto claimed = queue.claim("worker-1");
assert(claimed.has_value() && claimed->has_value());
auto recovered = queue.recover_consumer("worker-1");
assert(recovered.has_value());
assert(*recovered == 1);
// Recovery is idempotent: nothing is in flight any more.
assert(*queue.recover_consumer("worker-1") == 0);
auto reclaimed = queue.claim("worker-2");
assert(reclaimed.has_value() && reclaimed->has_value());
assert((*reclaimed)->consumer == "worker-2");
assert((*reclaimed)->attempts == 2);
}
void final_attempt_recovery_dead_letters()
{
World world;
world.config.max_attempts = 1;
auto queue = world.queue();
assert(queue.publish("work", "final-1").has_value());
assert(queue.claim("worker-1").has_value());
auto recovered = queue.recover_consumer("worker-1");
assert(recovered.has_value());
assert(*recovered == 1);
const auto job = queue.status("final-1");
assert(job.has_value());
assert(job->state == JobState::Dead);
}
void no_quorum_write_is_never_durable()
{
World world;
auto queue = world.queue();
world.cluster.set_partition("b", 1);
world.cluster.set_partition("c", 1);
auto published = queue.publish("lost", "loss-1");
assert(!published.has_value());
world.cluster.set_partition("b", 0);
world.cluster.set_partition("c", 0);
// The failed publish was never applied.
auto status = queue.status("loss-1");
assert(!status.has_value());
}
void ack_from_the_wrong_consumer_is_rejected()
{
World world;
auto queue = world.queue();
assert(queue.publish("work", "owner-1").has_value());
assert(queue.claim("worker-1").has_value());
auto wrong = queue.ack("worker-2", "owner-1");
assert(!wrong.has_value());
assert(wrong.error().kind() == Void::Result::ErrorKind::conflict);
assert(queue.ack("worker-1", "owner-1").has_value());
}
void leader_change_requires_endpoint_update()
{
World world;
auto queue = world.queue();
assert(queue.publish("work", "move-1").has_value());
world.cluster.set_partition("a", 1);
assert(world.cluster.elect("b").has_value());
// The queue still points at the old leader: explicit failure, not a
// silent write to a minority.
auto stale = queue.publish("work", "move-2");
assert(!stale.has_value());
queue.set_leader("b");
auto moved = queue.publish("work", "move-2");
assert(moved.has_value());
}
} // namespace
int main()
{
publish_claim_ack_dispatches_one_effect();
retries_then_dead_letters();
crashed_consumer_is_recovered();
final_attempt_recovery_dead_letters();
no_quorum_write_is_never_durable();
ack_from_the_wrong_consumer_is_rejected();
leader_change_requires_endpoint_update();
std::puts("distributed replicated queue ok");
return 0;
}
@@ -0,0 +1,177 @@
#include "distributed_host/single_node.hpp"
#include <Void/Net/Http.hpp>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cassert>
#include <cstdio>
#include <string>
namespace
{
using namespace DistributedHost;
SingleNodeConfig config()
{
SingleNodeConfig cfg;
cfg.peer_address = "127.0.0.1:0";
cfg.peer_token = "peer-secret";
cfg.shutdown_grace = std::chrono::seconds{2};
return cfg;
}
Void::Net::Header auth()
{
return Void::Net::Header{"authorization", "Bearer peer-secret"};
}
void config_fails_closed_without_a_token()
{
SingleNodeConfig no_token;
no_token.peer_token.clear();
assert(!SingleNodeHost::create(no_token).has_value());
SingleNodeConfig bad_address;
bad_address.peer_token = "x";
bad_address.peer_address = "not-an-address";
assert(!SingleNodeHost::create(bad_address).has_value());
SingleNodeConfig zero_entries = config();
zero_entries.max_log_entries = 0;
assert(!SingleNodeHost::create(zero_entries).has_value());
}
void peer_fixture_requires_authentication_and_serves_bounded_state()
{
auto host = SingleNodeHost::create(config());
assert(host.has_value());
// Construction opens no listener.
assert(host->peer_port() == 0);
assert(host->history().empty());
assert(host->start().has_value());
assert(host->health().readiness == Readiness::WriteReady);
const std::uint16_t port = host->peer_port();
assert(port != 0);
Void::Net::HttpClient client;
const std::string base =
"http://127.0.0.1:" + std::to_string(port);
// Both peer endpoints reject missing and wrong credentials.
auto anonymous_health = client.get(base + "/peer/health");
assert(anonymous_health.has_value());
assert(anonymous_health->status == 401);
auto wrong = client.get(
base + "/peer/health",
{Void::Net::Header{"authorization", "Bearer wrong"}});
assert(wrong.has_value());
assert(wrong->status == 401);
auto health = client.get(base + "/peer/health", {auth()});
assert(health.has_value());
assert(health->status == 200);
assert(health->body.find("role=leader") != std::string::npos);
assert(health->body.find("entries=0") != std::string::npos);
// The credential never appears in a response.
assert(health->body.find("peer-secret") == std::string::npos);
auto append = [&](std::string body) {
Void::Net::Request request;
request.method = Void::Net::Method::Post;
request.url = base + "/peer/append";
request.body = std::move(body);
request.headers.push_back(auth());
return client.send(request);
};
auto anonymous = client.send(Void::Net::Request{
.method = Void::Net::Method::Post,
.url = base + "/peer/append",
.body = "entry"});
assert(anonymous.has_value());
assert(anonymous->status == 401);
auto first = append("entry-one");
assert(first.has_value());
assert(first->status == 200);
assert(first->body == "index=1");
auto second = append("entry-two");
assert(second.has_value());
assert(second->body == "index=2");
auto after = client.get(base + "/peer/health", {auth()});
assert(after.has_value());
assert(after->body.find("entries=2") != std::string::npos);
// Auth is required for the mutation even with a valid-looking path.
auto wrong_method = client.get(base + "/peer/append", {auth()});
assert(wrong_method.has_value());
assert(wrong_method->status == 405);
host->stop();
assert(host->peer_port() == 0);
const auto closed = client.get(base + "/peer/health", {auth()});
assert(!closed.has_value());
// Idempotent.
host->stop();
}
void bind_failure_rolls_back_in_reverse_order()
{
// Occupy a loopback port with a raw listener.
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
assert(fd >= 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = 0;
assert(::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) == 0);
assert(::listen(fd, 4) == 0);
socklen_t length = sizeof(addr);
assert(::getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &length) ==
0);
const std::uint16_t busy_port = ntohs(addr.sin_port);
SingleNodeConfig cfg = config();
cfg.peer_address = "127.0.0.1:" + std::to_string(busy_port);
auto host = SingleNodeHost::create(cfg);
assert(host.has_value());
auto started = host->start();
assert(!started.has_value());
assert(host->health().readiness == Readiness::Failed);
const std::vector<std::string> expected{
"storage.open", "storage.recover", "storage.close"};
assert(host->history() == expected);
assert(host->peer_port() == 0);
(void)::close(fd);
}
void log_cap_is_bounded()
{
PeerLog log{2};
assert(log.append("a").has_value());
assert(log.append("b").has_value());
auto rejected = log.append("c");
assert(!rejected.has_value());
assert(log.size() == 2);
assert(log.last_index() == 2);
}
} // namespace
int main()
{
config_fails_closed_without_a_token();
peer_fixture_requires_authentication_and_serves_bounded_state();
bind_failure_rolls_back_in_reverse_order();
log_cap_is_bounded();
std::puts("distributed single-node host ok");
return 0;
}
@@ -0,0 +1,50 @@
cmake_minimum_required(VERSION 4.0)
project(NetworkedKv LANGUAGES CXX)
# Reference application, built as an installed-package consumer so it cannot
# accidentally rely on whole-repository linkage.
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(Void CONFIG REQUIRED COMPONENTS Runtime Net Sqlite Messaging Scheduler Discovery)
add_library(networked_kv STATIC
src/application.cpp
src/http_api.cpp
src/job_service.cpp
src/memory_store.cpp
src/service_directory.cpp
src/sqlite_store.cpp)
target_include_directories(networked_kv PUBLIC include)
target_link_libraries(networked_kv PUBLIC Void::Net Void::Runtime Void::Sqlite Void::Messaging Void::Scheduler Void::Discovery)
add_executable(networked_kv_test tests/application_test.cpp)
target_link_libraries(networked_kv_test PRIVATE networked_kv)
add_executable(networked_kv_domain_test tests/domain_test.cpp)
target_link_libraries(networked_kv_domain_test PRIVATE networked_kv)
add_executable(networked_kv_http_test tests/http_api_test.cpp)
target_link_libraries(networked_kv_http_test PRIVATE networked_kv)
add_executable(networked_kv_sqlite_test tests/sqlite_store_test.cpp)
target_link_libraries(networked_kv_sqlite_test PRIVATE networked_kv)
add_executable(networked_kv_protocol_test tests/protocol_matrix_test.cpp)
target_link_libraries(networked_kv_protocol_test PRIVATE networked_kv)
add_executable(networked_kv_job_test tests/job_service_test.cpp)
target_link_libraries(networked_kv_job_test PRIVATE networked_kv)
add_executable(networked_kv_directory_test tests/service_directory_test.cpp)
target_link_libraries(networked_kv_directory_test PRIVATE networked_kv)
enable_testing()
add_test(NAME networked_kv_lifecycle COMMAND networked_kv_test)
add_test(NAME networked_kv_domain COMMAND networked_kv_domain_test)
add_test(NAME networked_kv_http COMMAND networked_kv_http_test)
add_test(NAME networked_kv_sqlite COMMAND networked_kv_sqlite_test)
add_test(NAME networked_kv_protocol COMMAND networked_kv_protocol_test)
add_test(NAME networked_kv_jobs COMMAND networked_kv_job_test)
add_test(NAME networked_kv_directory COMMAND networked_kv_directory_test)
@@ -0,0 +1,168 @@
#pragma once
#include "networked_kv/domain.hpp"
#include "networked_kv/http_api.hpp"
#include "networked_kv/service_directory.hpp"
#include <Void/Functional/Result.hpp>
#include <Void/Net/HttpServer.hpp>
#include <Void/Runtime/Host.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
namespace NetworkedKv
{
/// Validated listener and request bounds for the reference service.
/// Construction alone opens no socket or worker.
struct NetworkedConfig {
std::string listen_address{"127.0.0.1:0"};
std::string admin_address{};
/// Bearer token required on the data plane; empty fails closed.
std::string bearer_token{};
/// Durable SQLite KV path. Empty selects the in-memory profile.
std::string storage_path{};
std::uint32_t max_connections{64};
std::size_t max_request_bytes{1024ULL * 1024ULL};
std::size_t max_header_bytes{64ULL * 1024ULL};
std::size_t max_scan_page{1000};
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
/// Optional Discovery-owned service directory. Registration is an
/// observation dependency: its failure never stops the data plane.
bool discovery_enabled{false};
std::string discovery_service{"networked-kv"};
std::string discovery_instance{};
std::string discovery_host{"127.0.0.1"};
std::chrono::milliseconds request_deadline{
std::chrono::seconds{30}};
std::chrono::milliseconds shutdown_grace{
std::chrono::seconds{5}};
[[nodiscard]] Void::Result::Result<void> validate() const;
};
enum class ResourceOwnership : std::uint8_t { Embedded, Managed };
/// Module-owned resources supplied by the application.
///
/// Embedded mode borrows an already-running host and never shuts it down.
/// Managed mode lets the application create and own the host.
struct ApplicationResources {
ResourceOwnership ownership{ResourceOwnership::Embedded};
Void::Runtime::Host* borrowed_host{nullptr};
Void::Runtime::Options runtime_options{};
};
enum class ApplicationState : std::uint8_t {
Created,
Running,
Stopping,
Stopped,
Failed
};
struct HealthSnapshot {
ApplicationState state{ApplicationState::Created};
bool ready{false};
bool managed{false};
std::size_t started_workers{0};
std::uint16_t bound_port{0};
bool discovery_registered{false};
std::string discovery_error;
};
/// Composition surface for the networked key-value reference service.
///
/// This slice owns lifecycle and resource-mode policy only: it wires no
/// HTTP endpoints yet and defines no competing executor, clock, logger or
/// error type.
class NetworkedApplication
{
public:
NetworkedApplication(const NetworkedApplication&) = delete;
NetworkedApplication& operator=(const NetworkedApplication&) = delete;
NetworkedApplication(NetworkedApplication&&) noexcept;
NetworkedApplication& operator=(NetworkedApplication&&) noexcept;
~NetworkedApplication();
[[nodiscard]] static Void::Result::Result<NetworkedApplication>
create(ApplicationResources resources, NetworkedConfig config);
/// Start serving. Managed mode creates and starts the owned host;
/// embedded mode requires the borrowed host to already be running.
[[nodiscard]] Void::Result::Result<void> start();
/// Stop serving. Idempotent and bounded. Managed mode shuts the
/// owned host down; embedded mode leaves the borrowed host alone.
[[nodiscard]] Void::Result::Result<Void::Runtime::ShutdownReport>
stop();
[[nodiscard]] HealthSnapshot health() const;
[[nodiscard]] const NetworkedConfig& config() const noexcept
{
return m_config;
}
/// Generation of the live configuration (starts at 1 after the first
/// successful start; incremented by each applied reload).
[[nodiscard]] std::uint64_t config_generation() const noexcept
{
return m_generation;
}
/// Parse/validate a complete candidate and apply the live-reloadable
/// parts atomically: the bearer token and readiness gating. Listener
/// addresses, backend selection, storage path and limits require a
/// restart and are rejected with a conflict error while the
/// application is running, leaving the old generation untouched.
[[nodiscard]] Void::Result::Result<void>
reload(NetworkedConfig candidate);
/// Port the HTTP listener actually bound (0 when not listening).
[[nodiscard]] std::uint16_t bound_port() const noexcept;
/// Port the administrative listener bound (0 when not listening).
[[nodiscard]] std::uint16_t admin_bound_port() const noexcept;
/// Discovery directory when enabled (null otherwise). Owned by the
/// application; valid until the next reload or stop.
[[nodiscard]] ServiceDirectory* directory() noexcept
{
return m_directory.get();
}
[[nodiscard]] const ServiceDirectory* directory() const noexcept
{
return m_directory.get();
}
/// Consistent operator backup of the durable profile. Fails when
/// the in-memory profile is active.
[[nodiscard]] Void::Result::Result<void>
backup_storage(const std::string& destination);
/// Restore the durable profile from a backup. Quiesce clients first;
/// the caller owns re-validation before routing traffic again.
[[nodiscard]] Void::Result::Result<void>
restore_storage(const std::string& source);
private:
NetworkedApplication() = default;
void stop_owned_host() noexcept;
NetworkedConfig m_config{};
ApplicationResources m_resources{};
std::unique_ptr<Void::Runtime::Host> m_owned_host{};
Void::Runtime::Host* m_host{nullptr};
// Heap-owned so a moved application keeps the KvApi reference valid.
std::unique_ptr<KvStore> m_store{};
std::unique_ptr<KvApi> m_api{};
std::unique_ptr<Void::Net::HttpServer> m_server{};
std::unique_ptr<Void::Net::HttpServer> m_admin_server{};
std::unique_ptr<ServiceDirectory> m_directory{};
std::string m_discovery_error{};
ApplicationState m_state{ApplicationState::Created};
std::uint64_t m_generation{0};
};
} // namespace NetworkedKv
@@ -0,0 +1,158 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace NetworkedKv
{
using Version = std::uint64_t;
struct Limits {
std::size_t max_key_bytes{512};
std::size_t max_value_bytes{1024ULL * 1024ULL};
std::size_t max_request_id_bytes{128};
std::size_t max_scan_page{1000};
std::size_t max_operation_records{1024};
};
struct Entry {
std::string value;
Version version{1};
};
enum class PreconditionKind : std::uint8_t { Absent, Version };
/// Explicit absent/version precondition for a mutation.
struct Precondition {
PreconditionKind kind{PreconditionKind::Absent};
Version version{0};
[[nodiscard]] static Precondition absent() noexcept
{
return {};
}
[[nodiscard]] static Precondition at_version(Version value) noexcept
{
return {PreconditionKind::Version, value};
}
};
/// Idempotency key for a mutation. Replaying the same id returns the
/// recorded outcome instead of applying the mutation twice.
struct RequestId {
std::string value;
};
enum class WriteOutcome : std::uint8_t {
Applied,
Conflict,
NotFound,
/// The backend could not prove whether the write committed.
Unknown
};
struct WriteResult {
WriteOutcome outcome{WriteOutcome::Unknown};
Version version{0};
};
struct ScanItem {
std::string key;
Entry entry;
};
struct ScanPage {
std::vector<ScanItem> items;
/// Opaque cursor for the next page; empty when the scan is done.
std::optional<std::string> next_cursor;
};
/// Versioned key-value domain contract shared by storage backends.
class KvStore
{
public:
KvStore() = default;
KvStore(const KvStore&) = delete;
KvStore& operator=(const KvStore&) = delete;
virtual ~KvStore() = default;
[[nodiscard]] virtual Void::Result::Result<std::optional<Entry>>
get(std::string_view key) const = 0;
[[nodiscard]] virtual Void::Result::Result<WriteResult>
put(std::string_view key, std::string value,
Precondition precondition, RequestId request) = 0;
[[nodiscard]] virtual Void::Result::Result<WriteResult>
erase(std::string_view key, Precondition precondition,
RequestId request) = 0;
[[nodiscard]] virtual Void::Result::Result<ScanPage>
scan(std::optional<std::string_view> cursor,
std::size_t limit = 0) const = 0;
/// Recorded outcome of a mutation request id, if it is still within
/// the retention window. Absence is not proof that a write did not
/// commit; callers must treat it as unknown.
[[nodiscard]] virtual Void::Result::Result<std::optional<WriteResult>>
lookup_operation(const RequestId& request) const = 0;
};
/// Bounded in-memory reference backend. Durable backends implement the
/// same contract without changing the domain semantics.
class MemoryKvStore final : public KvStore
{
public:
explicit MemoryKvStore(Limits limits = {});
[[nodiscard]] Void::Result::Result<std::optional<Entry>>
get(std::string_view key) const override;
[[nodiscard]] Void::Result::Result<WriteResult>
put(std::string_view key, std::string value,
Precondition precondition, RequestId request) override;
[[nodiscard]] Void::Result::Result<WriteResult>
erase(std::string_view key, Precondition precondition,
RequestId request) override;
[[nodiscard]] Void::Result::Result<ScanPage>
scan(std::optional<std::string_view> cursor,
std::size_t limit = 0) const override;
[[nodiscard]] Void::Result::Result<std::optional<WriteResult>>
lookup_operation(const RequestId& request) const override;
[[nodiscard]] const Limits& limits() const noexcept
{
return m_limits;
}
private:
[[nodiscard]] Void::Result::Result<void>
validate_key(std::string_view key) const;
[[nodiscard]] Void::Result::Result<void>
validate_request(const RequestId& request) const;
[[nodiscard]] std::optional<WriteResult>
replay(const RequestId& request) const;
void remember(const RequestId& request, const WriteResult& result);
mutable std::mutex m_mutex;
Limits m_limits;
std::map<std::string, Entry, std::less<>> m_entries;
std::map<std::string, WriteResult, std::less<>> m_operations;
std::vector<std::string> m_operation_order;
};
} // namespace NetworkedKv
@@ -0,0 +1,96 @@
#pragma once
#include "networked_kv/domain.hpp"
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
namespace NetworkedKv
{
struct HttpRequest {
std::string method;
std::string target;
std::map<std::string, std::string, std::less<>> headers;
std::string body;
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const;
};
struct HttpResponse {
int status{200};
std::map<std::string, std::string, std::less<>> headers;
std::string body;
};
struct ApiConfig {
std::string bearer_token;
std::size_t max_body_bytes{1024ULL * 1024ULL};
std::size_t max_scan_limit{1000};
};
struct ApiMetrics {
std::uint64_t requests{0};
std::uint64_t unauthorized{0};
std::uint64_t client_errors{0};
std::uint64_t server_errors{0};
std::uint64_t bytes_in{0};
std::uint64_t bytes_out{0};
};
/// Transport-agnostic HTTP application layer for the key-value service.
///
/// Net owns parsing and framing; this maps an already-parsed request to the
/// KV domain, enforces bearer auth on the data plane, and exposes bounded
/// admin views that never dump credentials or mutate data.
class KvApi
{
public:
KvApi(KvStore& store, ApiConfig config);
[[nodiscard]] HttpResponse handle(const HttpRequest& request);
[[nodiscard]] HttpResponse admin(const HttpRequest& request) const;
void set_ready(bool ready) noexcept { m_ready = ready; }
/// Atomically replace the live-reloadable bearer token. In-flight
/// requests read either the old or the new token, never a torn mix.
void set_bearer_token(std::string token)
{
std::lock_guard lock{m_config_mutex};
m_config.bearer_token = std::move(token);
}
[[nodiscard]] ApiMetrics metrics() const noexcept { return m_metrics; }
private:
[[nodiscard]] bool authorized(const HttpRequest& request) const;
[[nodiscard]] HttpResponse
kv_get(std::string_view key, const HttpRequest& request);
[[nodiscard]] HttpResponse
kv_put(std::string_view key, const HttpRequest& request);
[[nodiscard]] HttpResponse
kv_delete(std::string_view key, const HttpRequest& request);
[[nodiscard]] HttpResponse
kv_scan(const HttpRequest& request);
[[nodiscard]] HttpResponse
kv_operation(std::string_view request_id);
void note(const HttpResponse& response);
KvStore& m_store;
ApiConfig m_config;
mutable std::mutex m_config_mutex;
bool m_ready{true};
ApiMetrics m_metrics;
};
} // namespace NetworkedKv
@@ -0,0 +1,123 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Messaging/Queue.hpp>
#include <Void/Scheduler/Scheduler.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <map>
#include <mutex>
#include <string>
#include <string_view>
#include <vector>
namespace NetworkedKv
{
struct JobServiceConfig {
std::string queue_name{"jobs"};
std::string group_name{"workers"};
std::chrono::milliseconds visibility_timeout{
std::chrono::seconds{30}};
/// Attempts before the queue dead-letters the job.
std::uint32_t max_attempts{3};
std::chrono::milliseconds retry_delay{
std::chrono::milliseconds{50}};
/// Bounded status records; the oldest is evicted beyond this.
std::size_t max_tracked_jobs{1024};
/// Memory is explicit for the in-memory profile; a durable queue
/// profile passes Durable.
Void::Messaging::PublishDurability publish_durability{
Void::Messaging::PublishDurability::Memory};
};
enum class JobState : std::uint8_t {
Submitted,
Running,
Succeeded,
RetryScheduled,
DeadLettered,
Unknown
};
[[nodiscard]] std::string_view job_state_name(JobState state) noexcept;
struct JobView {
std::string id;
JobState state{JobState::Unknown};
std::uint32_t attempts{0};
std::string last_error;
};
/// Runs one delivered job. `attempt` starts at 1.
using JobHandler = std::function<Void::Result::Result<void>(
std::string_view payload, std::uint32_t attempt)>;
/// Durable-job reference composition over the Messaging queue contract.
///
/// Delivery semantics are the queue's (at-least-once with visibility
/// timeout and DLQ after exhausted attempts); this service adds bounded
/// job status tracking and a Scheduler-driven maintenance job. Workers
/// must be idempotent per job id: a redelivery after a lost ack is
/// possible by contract.
class JobService
{
public:
JobService(Void::Messaging::Queue& queue, JobServiceConfig config = {});
JobService(const JobService&) = delete;
JobService& operator=(const JobService&) = delete;
/// Create the queue and consumer group. Idempotent for an
/// existing compatible configuration.
[[nodiscard]] Void::Result::Result<void> initialize();
/// Publish one job and return its stable id. The id is the
/// queue's idempotency key, so a repeated publish of the same id
/// is deduplicated by the queue.
[[nodiscard]] Void::Result::Result<std::string> submit(std::string payload);
/// Receive at most one job, run the handler and ack or nack it.
/// Returns the affected job view, or empty when no job is ready.
/// A handler failure is recorded (retry or dead letter), not
/// returned as an error; queue failures are.
[[nodiscard]] Void::Result::Result<std::optional<JobView>>
process_one(const JobHandler& handler);
[[nodiscard]] Void::Result::Result<JobView>
status(std::string_view id) const;
/// Reap expired in-flight deliveries back to pending (or the DLQ
/// when attempts are exhausted). Driven by the Scheduler job.
[[nodiscard]] Void::Result::Result<std::size_t> maintain();
[[nodiscard]] Void::Result::Result<
std::vector<Void::Messaging::DeadLetterEntry>>
dead_letters(std::size_t limit = 100) const;
/// Register a fixed-rate Scheduler job that runs `maintain()`.
/// The scheduler is pure and thread-free: the caller drives it with
/// tick()/dispatch_one(). Returns the scheduler job id.
[[nodiscard]] Void::Result::Result<std::uint64_t>
schedule_maintenance(Void::Scheduler::Scheduler& scheduler,
std::chrono::milliseconds period =
std::chrono::seconds{30});
private:
void track(const JobView& view);
Void::Messaging::Queue& m_queue;
JobServiceConfig m_config;
std::uint64_t m_next_id{1};
bool m_initialized{false};
bool m_maintenance_registered{false};
mutable std::mutex m_mutex;
std::map<std::string, JobView, std::less<>> m_jobs;
std::deque<std::string> m_order;
};
} // namespace NetworkedKv
@@ -0,0 +1,71 @@
#pragma once
#include <Void/Discovery/Catalog.hpp>
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace NetworkedKv
{
struct ServiceDirectoryConfig {
std::string service_name{"networked-kv"};
/// Stable instance identity; required when the directory is enabled.
std::string instance_id{};
std::string advertise_host{"127.0.0.1"};
std::string scheme{"http"};
std::uint32_t weight{1};
};
/// Thin adapter over the Discovery-owned `Catalog`.
///
/// The catalog is authoritative for registration, revision and resolution
/// policy; this adapter only maps the reference service's endpoint into it.
/// Discovery is an observation dependency: a provider that is stale or
/// unavailable never stops the data plane and never counts as a quorum
/// vote.
class ServiceDirectory
{
public:
explicit ServiceDirectory(ServiceDirectoryConfig config = {});
ServiceDirectory(const ServiceDirectory&) = delete;
ServiceDirectory& operator=(const ServiceDirectory&) = delete;
ServiceDirectory(ServiceDirectory&&) noexcept = default;
ServiceDirectory& operator=(ServiceDirectory&&) noexcept = default;
~ServiceDirectory();
/// Register the live data-plane endpoint. Idempotent while the
/// previous registration is active.
[[nodiscard]] Void::Result::Result<void>
register_endpoint(std::uint16_t port);
void deregister() noexcept;
[[nodiscard]] Void::Result::Result<
std::vector<Void::Discovery::EndpointRecord>>
resolve(std::string_view service,
Void::Discovery::ResolvePolicy policy = {}) const;
/// Adapter hook for an unavailable/stale upstream provider.
void set_provider_health(
Void::Discovery::Freshness freshness,
std::optional<Void::Discovery::Error> provider_error =
std::nullopt) noexcept;
[[nodiscard]] std::size_t active_records() const noexcept;
[[nodiscard]] std::uint64_t revision() const noexcept;
[[nodiscard]] bool registered() const noexcept;
private:
ServiceDirectoryConfig m_config;
Void::Discovery::Catalog m_catalog;
Void::Discovery::Registration m_registration;
};
} // namespace NetworkedKv
@@ -0,0 +1,77 @@
#pragma once
#include "networked_kv/domain.hpp"
#include <Void/Sqlite/Sqlite.hpp>
#include <filesystem>
#include <memory>
#include <mutex>
#include <string_view>
namespace NetworkedKv
{
/// Durable KV profile backed by Void::Sqlite.
///
/// Business rows and idempotency records are written in one explicit
/// transaction, so a request either commits both or neither. Versions are
/// checked inside that transaction.
class SqliteKvStore final : public KvStore
{
public:
[[nodiscard]] static Void::Result::Result<std::unique_ptr<SqliteKvStore>>
open(const std::filesystem::path& path, Limits limits = {});
~SqliteKvStore() override = default;
SqliteKvStore(const SqliteKvStore&) = delete;
SqliteKvStore& operator=(const SqliteKvStore&) = delete;
SqliteKvStore(SqliteKvStore&&) noexcept = default;
SqliteKvStore& operator=(SqliteKvStore&&) noexcept = default;
[[nodiscard]] Void::Result::Result<std::optional<Entry>>
get(std::string_view key) const override;
[[nodiscard]] Void::Result::Result<WriteResult>
put(std::string_view key, std::string value,
Precondition precondition, RequestId request) override;
[[nodiscard]] Void::Result::Result<WriteResult>
erase(std::string_view key, Precondition precondition,
RequestId request) override;
[[nodiscard]] Void::Result::Result<ScanPage>
scan(std::optional<std::string_view> cursor,
std::size_t limit = 0) const override;
[[nodiscard]] Void::Result::Result<std::optional<WriteResult>>
lookup_operation(const RequestId& request) const override;
[[nodiscard]] const Limits& limits() const noexcept
{
return m_limits;
}
/// Consistent operator backup through SQLite's online backup API.
/// `destination` must not be the live database file.
[[nodiscard]] Void::Result::Result<Void::Sqlite::BackupReport>
backup_to(const std::filesystem::path& destination);
/// Restore this connection from a verified backup file. Callers
/// must quiesce application traffic first; run domain checks before
/// routing traffic to the restored contents.
[[nodiscard]] Void::Result::Result<Void::Sqlite::BackupReport>
restore_from(const std::filesystem::path& source);
private:
SqliteKvStore(Void::Sqlite::Database database, Limits limits);
[[nodiscard]] Void::Result::Result<void> ensure_schema();
mutable std::mutex m_mutex;
// prepare() is non-const, but the read-only KvStore methods are const.
mutable Void::Sqlite::Database m_db;
Limits m_limits;
};
} // namespace NetworkedKv
@@ -0,0 +1,532 @@
#include "networked_kv/application.hpp"
#include "networked_kv/sqlite_store.hpp"
#include <Void/Time/Clock.hpp>
#include <charconv>
#include <cstdint>
#include <string>
#include <string_view>
#include <utility>
namespace NetworkedKv
{
namespace
{
[[nodiscard]] Void::Result::Error
config_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
[[nodiscard]] Void::Result::Error state_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] bool parse_address(std::string_view address, std::string& host,
std::uint16_t& port) noexcept
{
const auto colon = address.rfind(':');
if (colon == std::string_view::npos || colon == 0 ||
colon + 1 >= address.size()) {
return false;
}
host = std::string{address.substr(0, colon)};
const auto digits = address.substr(colon + 1);
unsigned int value = 0;
const auto parsed = std::from_chars(
digits.data(), digits.data() + digits.size(), value);
if (parsed.ec != std::errc{} ||
parsed.ptr != digits.data() + digits.size() || value > 65535U) {
return false;
}
port = static_cast<std::uint16_t>(value);
return true;
}
[[nodiscard]] std::string method_name(Void::Net::Method method)
{
switch (method) {
case Void::Net::Method::Get: return "GET";
case Void::Net::Method::Post: return "POST";
case Void::Net::Method::Put: return "PUT";
case Void::Net::Method::Delete: return "DELETE";
case Void::Net::Method::Patch: return "PATCH";
case Void::Net::Method::Head: return "HEAD";
case Void::Net::Method::Options: return "OPTIONS";
}
return "GET";
}
[[nodiscard]] HttpRequest
to_http_request(const Void::Net::ServerRequest& request)
{
HttpRequest out;
out.method = method_name(request.method);
out.target = request.path;
if (!request.query.empty()) {
out.target += '?';
out.target += request.query;
}
for (const auto& header : request.headers) {
out.headers[header.name] = header.value;
}
out.body = request.body;
return out;
}
[[nodiscard]] Void::Net::ServerResponse
to_server_response(const HttpResponse& response)
{
Void::Net::ServerResponse out;
out.status = static_cast<std::uint16_t>(response.status);
out.body = response.body;
out.headers.reserve(response.headers.size());
for (const auto& [name, value] : response.headers) {
out.headers.push_back(Void::Net::Header{name, value});
}
return out;
}
[[nodiscard]] Void::Async::OperationOptions
deadline_after(std::chrono::milliseconds grace)
{
Void::Async::OperationOptions options;
options.deadline = Void::Time::SystemMonotonicClock::instance().now() +
grace;
return options;
}
} // namespace
Void::Result::Result<void> NetworkedConfig::validate() const
{
if (listen_address.empty()) {
return std::unexpected{
config_error("NetworkedConfig: listen_address must not be empty")};
}
if (max_connections == 0) {
return std::unexpected{
config_error("NetworkedConfig: max_connections must be positive")};
}
if (max_request_bytes == 0) {
return std::unexpected{config_error(
"NetworkedConfig: max_request_bytes must be positive")};
}
if (max_header_bytes == 0) {
return std::unexpected{config_error(
"NetworkedConfig: max_header_bytes must be positive")};
}
if (read_timeout.count() <= 0 || write_timeout.count() <= 0) {
return std::unexpected{config_error(
"NetworkedConfig: read/write timeouts must be positive")};
}
if (max_scan_page == 0) {
return std::unexpected{
config_error("NetworkedConfig: max_scan_page must be positive")};
}
if (request_deadline.count() <= 0) {
return std::unexpected{config_error(
"NetworkedConfig: request_deadline must be positive")};
}
if (shutdown_grace.count() < 0) {
return std::unexpected{config_error(
"NetworkedConfig: shutdown_grace must not be negative")};
}
if (discovery_enabled && discovery_instance.empty()) {
return std::unexpected{config_error(
"NetworkedConfig: discovery_instance is required when "
"discovery is enabled")};
}
return {};
}
NetworkedApplication::NetworkedApplication(NetworkedApplication&& other) noexcept
: m_config(std::move(other.m_config))
, m_resources(other.m_resources)
, m_owned_host(std::move(other.m_owned_host))
, m_host(other.m_host)
, m_store(std::move(other.m_store))
, m_api(std::move(other.m_api))
, m_server(std::move(other.m_server))
, m_admin_server(std::move(other.m_admin_server))
, m_directory(std::move(other.m_directory))
, m_discovery_error(std::move(other.m_discovery_error))
, m_state(other.m_state)
{
other.m_host = nullptr;
other.m_state = ApplicationState::Stopped;
}
NetworkedApplication&
NetworkedApplication::operator=(NetworkedApplication&& other) noexcept
{
if (this != &other) {
stop_owned_host();
m_config = std::move(other.m_config);
m_resources = other.m_resources;
m_owned_host = std::move(other.m_owned_host);
m_host = other.m_host;
m_store = std::move(other.m_store);
m_api = std::move(other.m_api);
m_server = std::move(other.m_server);
m_admin_server = std::move(other.m_admin_server);
m_directory = std::move(other.m_directory);
m_discovery_error = std::move(other.m_discovery_error);
m_state = other.m_state;
other.m_host = nullptr;
other.m_state = ApplicationState::Stopped;
}
return *this;
}
NetworkedApplication::~NetworkedApplication()
{
if (m_server) {
m_server->shutdown(m_config.shutdown_grace);
m_server.reset();
}
if (m_admin_server) {
m_admin_server->shutdown(m_config.shutdown_grace);
m_admin_server.reset();
}
stop_owned_host();
}
Void::Result::Result<NetworkedApplication>
NetworkedApplication::create(ApplicationResources resources,
NetworkedConfig config)
{
if (auto valid = config.validate(); !valid) {
return std::unexpected{std::move(valid).error()};
}
if (resources.ownership == ResourceOwnership::Embedded &&
(resources.borrowed_host == nullptr ||
!resources.borrowed_host->valid())) {
return std::unexpected{config_error(
"NetworkedApplication: embedded mode requires a valid borrowed "
"host")};
}
NetworkedApplication app;
app.m_config = std::move(config);
app.m_resources = resources;
if (app.m_config.storage_path.empty()) {
app.m_store = std::make_unique<MemoryKvStore>();
} else {
auto durable = SqliteKvStore::open(app.m_config.storage_path);
if (!durable) {
return std::unexpected{std::move(durable).error()};
}
app.m_store = std::move(*durable);
}
app.m_api = std::make_unique<KvApi>(
*app.m_store,
ApiConfig{.bearer_token = app.m_config.bearer_token,
.max_body_bytes = app.m_config.max_request_bytes,
.max_scan_limit = app.m_config.max_scan_page});
if (app.m_config.discovery_enabled) {
app.m_directory = std::make_unique<ServiceDirectory>(
ServiceDirectoryConfig{
.service_name = app.m_config.discovery_service,
.instance_id = app.m_config.discovery_instance,
.advertise_host = app.m_config.discovery_host});
}
return app;
}
Void::Result::Result<void> NetworkedApplication::start()
{
if (m_state == ApplicationState::Running) {
return std::unexpected{
state_error("NetworkedApplication: already running")};
}
if (m_resources.ownership == ResourceOwnership::Managed) {
if (!m_owned_host) {
auto created =
Void::Runtime::Host::create(m_resources.runtime_options);
if (!created) {
m_state = ApplicationState::Failed;
return std::unexpected{std::move(created).error()};
}
m_owned_host =
std::make_unique<Void::Runtime::Host>(std::move(*created));
m_host = m_owned_host.get();
}
if (!m_host->is_running()) {
if (auto started = m_host->start(); !started) {
m_state = ApplicationState::Failed;
return started;
}
}
} else {
m_host = m_resources.borrowed_host;
if (m_host == nullptr || !m_host->is_running()) {
return std::unexpected{state_error(
"NetworkedApplication: embedded mode requires a running "
"borrowed host")};
}
}
if (!m_server) {
std::string host;
std::uint16_t port = 0;
if (!parse_address(m_config.listen_address, host, port)) {
m_state = ApplicationState::Failed;
return std::unexpected{config_error(
"NetworkedApplication: listen_address must be host:port")};
}
Void::Net::HttpServerOptions options;
options.bind_host = std::move(host);
options.port = port;
options.max_body_bytes = m_config.max_request_bytes;
options.max_header_bytes = m_config.max_header_bytes;
options.read_timeout = m_config.read_timeout;
options.write_timeout = m_config.write_timeout;
options.max_concurrent_connections = m_config.max_connections;
auto server = std::make_unique<Void::Net::HttpServer>(options);
auto add = [&](Void::Net::Method method, const char* pattern) {
return server->add_route(
method, pattern,
[this](const Void::Net::ServerRequest& request)
-> Void::Net::RouteResult {
return to_server_response(
m_api->handle(to_http_request(request)));
});
};
Void::Result::Error route_error{};
bool routes_ok = true;
auto add_checked = [&](Void::Net::Method method, const char* pattern) {
if (!routes_ok) {
return;
}
if (auto added = add(method, pattern); !added) {
routes_ok = false;
route_error = std::move(added).error();
}
};
add_checked(Void::Net::Method::Get, "/v1/kv/:key");
add_checked(Void::Net::Method::Put, "/v1/kv/:key");
add_checked(Void::Net::Method::Delete, "/v1/kv/:key");
add_checked(Void::Net::Method::Get, "/v1/scan");
add_checked(Void::Net::Method::Get, "/v1/operations/:id");
if (!routes_ok) {
m_state = ApplicationState::Failed;
return std::unexpected{std::move(route_error)};
}
if (auto started = server->start(); !started) {
m_state = ApplicationState::Failed;
return started;
}
m_server = std::move(server);
if (m_directory) {
// Discovery is an observation dependency: a failed registration
// is reported, never fatal for the data plane.
if (auto registered =
m_directory->register_endpoint(m_server->bound_port());
!registered) {
m_discovery_error = registered.error().message();
} else {
m_discovery_error.clear();
}
}
}
// The administrative listener is separate from the data plane and
// only exposes bounded lifecycle and telemetry views.
if (!m_admin_server && !m_config.admin_address.empty()) {
std::string host;
std::uint16_t port = 0;
if (!parse_address(m_config.admin_address, host, port)) {
m_state = ApplicationState::Failed;
return std::unexpected{config_error(
"NetworkedApplication: admin_address must be host:port")};
}
Void::Net::HttpServerOptions options;
options.bind_host = std::move(host);
options.port = port;
options.max_concurrent_connections = 8;
auto admin = std::make_unique<Void::Net::HttpServer>(options);
auto add_admin = [&](const char* pattern) {
return admin->add_route(
Void::Net::Method::Get, pattern,
[this](const Void::Net::ServerRequest& request)
-> Void::Net::RouteResult {
return to_server_response(
m_api->admin(to_http_request(request)));
});
};
Void::Result::Error admin_error{};
bool admin_ok = true;
for (const char* pattern : {"/live", "/ready", "/metrics"}) {
if (!admin_ok) {
break;
}
if (auto added = add_admin(pattern); !added) {
admin_ok = false;
admin_error = std::move(added).error();
}
}
if (!admin_ok) {
m_state = ApplicationState::Failed;
return std::unexpected{std::move(admin_error)};
}
if (auto started = admin->start(); !started) {
m_state = ApplicationState::Failed;
return started;
}
m_admin_server = std::move(admin);
}
m_state = ApplicationState::Running;
++m_generation;
return {};
}
Void::Result::Result<void>
NetworkedApplication::reload(NetworkedConfig candidate)
{
if (auto valid = candidate.validate(); !valid) {
return valid;
}
if (m_state != ApplicationState::Running) {
return std::unexpected{state_error(
"NetworkedApplication: reload requires a running application")};
}
// Only policy that can change without rebinding listeners or reopening
// the backend is applied live. Everything else is a restart decision.
if (candidate.listen_address != m_config.listen_address ||
candidate.admin_address != m_config.admin_address ||
candidate.storage_path != m_config.storage_path ||
candidate.max_connections != m_config.max_connections ||
candidate.max_request_bytes != m_config.max_request_bytes ||
candidate.max_header_bytes != m_config.max_header_bytes ||
candidate.read_timeout != m_config.read_timeout ||
candidate.write_timeout != m_config.write_timeout ||
candidate.max_scan_page != m_config.max_scan_page) {
return std::unexpected{state_error(
"NetworkedApplication: listener, storage and limit changes "
"require a restart")};
}
// Publish the immutable generation only after every step succeeded.
// The API token swap is the single live mutation; there is no second
// listener to fail after it.
m_api->set_bearer_token(candidate.bearer_token);
m_config = std::move(candidate);
++m_generation;
return {};
}
Void::Result::Result<Void::Runtime::ShutdownReport>
NetworkedApplication::stop()
{
if (m_state == ApplicationState::Stopped) {
return Void::Runtime::ShutdownReport{};
}
if (m_state != ApplicationState::Running) {
m_state = ApplicationState::Stopped;
return Void::Runtime::ShutdownReport{};
}
m_state = ApplicationState::Stopping;
if (m_directory) {
m_directory->deregister();
}
if (m_server) {
m_server->shutdown(m_config.shutdown_grace);
m_server.reset();
}
if (m_admin_server) {
m_admin_server->shutdown(m_config.shutdown_grace);
m_admin_server.reset();
}
if (m_resources.ownership == ResourceOwnership::Managed && m_host) {
auto report =
m_host->shutdown_blocking(deadline_after(m_config.shutdown_grace));
m_state = ApplicationState::Stopped;
return report;
}
// Embedded: the borrowed host belongs to the application, so only
// this composition's view stops.
m_state = ApplicationState::Stopped;
Void::Runtime::ShutdownReport report;
report.complete = true;
report.state = m_host ? m_host->state()
: Void::Runtime::HostState::stopped;
return report;
}
HealthSnapshot NetworkedApplication::health() const
{
HealthSnapshot snapshot;
snapshot.state = m_state;
snapshot.managed = m_resources.ownership == ResourceOwnership::Managed;
if (m_host != nullptr) {
snapshot.ready = m_host->is_ready();
snapshot.started_workers = m_host->started_worker_count();
}
snapshot.bound_port = bound_port();
snapshot.discovery_registered =
m_directory != nullptr && m_directory->registered();
snapshot.discovery_error = m_discovery_error;
return snapshot;
}
std::uint16_t NetworkedApplication::bound_port() const noexcept
{
return m_server ? m_server->bound_port() : 0;
}
std::uint16_t NetworkedApplication::admin_bound_port() const noexcept
{
return m_admin_server ? m_admin_server->bound_port() : 0;
}
Void::Result::Result<void>
NetworkedApplication::backup_storage(const std::string& destination)
{
auto* durable = dynamic_cast<SqliteKvStore*>(m_store.get());
if (durable == nullptr) {
return std::unexpected{state_error(
"NetworkedApplication: backup requires the durable profile")};
}
if (destination.empty()) {
return std::unexpected{
config_error("NetworkedApplication: backup destination is empty")};
}
if (auto backed_up = durable->backup_to(destination); !backed_up) {
return std::unexpected{std::move(backed_up).error()};
}
return {};
}
Void::Result::Result<void>
NetworkedApplication::restore_storage(const std::string& source)
{
auto* durable = dynamic_cast<SqliteKvStore*>(m_store.get());
if (durable == nullptr) {
return std::unexpected{state_error(
"NetworkedApplication: restore requires the durable profile")};
}
if (source.empty()) {
return std::unexpected{
config_error("NetworkedApplication: restore source is empty")};
}
if (auto restored = durable->restore_from(source); !restored) {
return std::unexpected{std::move(restored).error()};
}
return {};
}
void NetworkedApplication::stop_owned_host() noexcept
{
if (m_resources.ownership != ResourceOwnership::Managed ||
!m_owned_host || m_state != ApplicationState::Running) {
return;
}
m_state = ApplicationState::Stopping;
(void)m_owned_host->shutdown_blocking(
deadline_after(m_config.shutdown_grace));
m_state = ApplicationState::Stopped;
}
} // namespace NetworkedKv
@@ -0,0 +1,483 @@
#include "networked_kv/http_api.hpp"
#include <algorithm>
#include <charconv>
#include <format>
#include <mutex>
#include <string>
#include <utility>
namespace NetworkedKv
{
namespace
{
constexpr std::string_view kJsonType{"application/json"};
constexpr std::string_view kTextType{"text/plain; charset=utf-8"};
constexpr std::string_view kKvPrefix{"/v1/kv/"};
constexpr std::string_view kOperationsPrefix{"/v1/operations/"};
[[nodiscard]] bool iequals(std::string_view lhs,
std::string_view rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
for (std::size_t i = 0; i < lhs.size(); ++i) {
const char a = lhs[i] >= 'A' && lhs[i] <= 'Z'
? static_cast<char>(lhs[i] + 32)
: lhs[i];
const char b = rhs[i] >= 'A' && rhs[i] <= 'Z'
? static_cast<char>(rhs[i] + 32)
: rhs[i];
if (a != b) {
return false;
}
}
return true;
}
[[nodiscard]] std::string_view path_of(std::string_view target) noexcept
{
const auto query = target.find('?');
return target.substr(0, query);
}
[[nodiscard]] std::string_view query_of(std::string_view target) noexcept
{
const auto query = target.find('?');
return query == std::string_view::npos ? std::string_view{}
: target.substr(query + 1);
}
[[nodiscard]] std::optional<std::string_view>
query_param(std::string_view query, std::string_view name) noexcept
{
while (!query.empty()) {
const auto amp = query.find('&');
const auto part = query.substr(0, amp);
const auto eq = part.find('=');
if (eq != std::string_view::npos &&
part.substr(0, eq) == name) {
return part.substr(eq + 1);
}
if (amp == std::string_view::npos) {
break;
}
query.remove_prefix(amp + 1);
}
return std::nullopt;
}
[[nodiscard]] bool constant_time_equal(std::string_view lhs,
std::string_view rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
unsigned int diff = 0;
for (std::size_t i = 0; i < lhs.size(); ++i) {
diff |= static_cast<unsigned int>(
static_cast<unsigned char>(lhs[i]) ^
static_cast<unsigned char>(rhs[i]));
}
return diff == 0;
}
[[nodiscard]] std::string json_escape(std::string_view input,
std::size_t max)
{
std::string out;
out.reserve(std::min(input.size(), max) + 8);
for (const char ch : input) {
if (out.size() >= max) {
break;
}
const auto byte = static_cast<unsigned char>(ch);
switch (ch) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (byte < 0x20) {
out += std::format("\\u{:04x}", byte);
} else {
out += ch;
}
}
}
return out;
}
[[nodiscard]] int status_for(const Void::Result::Error& error) noexcept
{
using Kind = Void::Result::ErrorKind;
switch (error.kind()) {
case Kind::invalid_argument: return 400;
case Kind::not_found: return 404;
case Kind::conflict: return 409;
case Kind::exhausted: return 429;
case Kind::overloaded: return 503;
case Kind::cancelled: return 499;
case Kind::timeout: return 504;
case Kind::unsupported: return 501;
default: return 500;
}
}
[[nodiscard]] HttpResponse error_response(int status,
std::string message)
{
HttpResponse response;
response.status = status;
response.headers["content-type"] = std::string{kJsonType};
response.body = "{\"error\":\"" + json_escape(message, 512) + "\"}";
return response;
}
[[nodiscard]] HttpResponse text_response(int status, std::string body)
{
HttpResponse response;
response.status = status;
response.headers["content-type"] = std::string{kTextType};
response.body = std::move(body);
return response;
}
[[nodiscard]] std::optional<Version>
parse_etag(std::string_view value) noexcept
{
if (value.size() >= 2 && value.front() == '"' &&
value.back() == '"') {
value = value.substr(1, value.size() - 2);
}
Version version = 0;
const auto parsed = std::from_chars(
value.data(), value.data() + value.size(), version);
if (parsed.ec != std::errc{} ||
parsed.ptr != value.data() + value.size()) {
return std::nullopt;
}
return version;
}
[[nodiscard]] std::string etag(Version version)
{
return "\"" + std::to_string(version) + "\"";
}
} // namespace
std::optional<std::string_view>
HttpRequest::header(std::string_view name) const
{
for (const auto& [key, value] : headers) {
if (iequals(key, name)) {
return value;
}
}
return std::nullopt;
}
KvApi::KvApi(KvStore& store, ApiConfig config)
: m_store(store)
, m_config(std::move(config))
{
}
bool KvApi::authorized(const HttpRequest& request) const
{
const auto header = request.header("authorization");
if (!header) {
return false;
}
constexpr std::string_view scheme{"bearer "};
if (header->size() < scheme.size() ||
!iequals(header->substr(0, scheme.size()), scheme)) {
return false;
}
std::lock_guard lock{m_config_mutex};
// Fail closed: an empty configured token authorizes nothing.
if (m_config.bearer_token.empty()) {
return false;
}
return constant_time_equal(header->substr(scheme.size()),
m_config.bearer_token);
}
void KvApi::note(const HttpResponse& response)
{
m_metrics.bytes_out += response.body.size();
if (response.status >= 500) {
++m_metrics.server_errors;
} else if (response.status >= 400) {
++m_metrics.client_errors;
}
}
HttpResponse KvApi::handle(const HttpRequest& request)
{
++m_metrics.requests;
m_metrics.bytes_in += request.target.size() + request.body.size();
if (request.body.size() > m_config.max_body_bytes) {
HttpResponse response = error_response(413, "request body too large");
note(response);
return response;
}
const auto path = path_of(request.target);
HttpResponse response;
if (path.starts_with(kKvPrefix) || path == "/v1/scan" ||
path.starts_with(kOperationsPrefix)) {
if (!authorized(request)) {
++m_metrics.unauthorized;
response = error_response(401, "missing or invalid bearer token");
} else if (path == "/v1/scan") {
response = request.method == "GET"
? kv_scan(request)
: error_response(405, "method not allowed");
} else if (path.starts_with(kOperationsPrefix)) {
response = request.method == "GET"
? kv_operation(path.substr(kOperationsPrefix.size()))
: error_response(405, "method not allowed");
} else {
const auto key = path.substr(kKvPrefix.size());
if (key.empty()) {
response = error_response(400, "key required");
} else if (request.method == "GET") {
response = kv_get(key, request);
} else if (request.method == "PUT") {
response = kv_put(key, request);
} else if (request.method == "DELETE") {
response = kv_delete(key, request);
} else {
response = error_response(405, "method not allowed");
}
}
} else {
response = error_response(404, "not found");
}
note(response);
return response;
}
HttpResponse KvApi::kv_get(std::string_view key, const HttpRequest&)
{
auto got = m_store.get(key);
if (!got) {
return error_response(status_for(got.error()),
got.error().message());
}
if (!got->has_value()) {
return error_response(404, "not found");
}
HttpResponse response;
response.status = 200;
response.headers["content-type"] = "application/octet-stream";
response.headers["etag"] = etag((*got)->version);
response.headers["cache-control"] = "no-store";
response.body = (*got)->value;
return response;
}
HttpResponse KvApi::kv_put(std::string_view key, const HttpRequest& request)
{
const auto request_id = request.header("x-request-id");
if (!request_id || request_id->empty()) {
return error_response(428, "x-request-id required");
}
Precondition precondition;
if (const auto none = request.header("if-none-match");
none && *none == "*") {
precondition = Precondition::absent();
} else if (const auto match = request.header("if-match")) {
const auto version = parse_etag(*match);
if (!version) {
return error_response(400, "invalid if-match");
}
precondition = Precondition::at_version(*version);
} else {
return error_response(428,
"if-none-match or if-match required");
}
auto result = m_store.put(key, request.body, precondition,
RequestId{std::string{*request_id}});
if (!result) {
return error_response(status_for(result.error()),
result.error().message());
}
switch (result->outcome) {
case WriteOutcome::Applied: {
HttpResponse response = text_response(200, "applied");
response.headers["etag"] = etag(result->version);
return response;
}
case WriteOutcome::Conflict:
return error_response(412, "version precondition failed");
case WriteOutcome::NotFound:
return error_response(404, "not found");
case WriteOutcome::Unknown:
return error_response(503, "commit outcome unknown");
}
return error_response(500, "unreachable");
}
HttpResponse KvApi::kv_delete(std::string_view key,
const HttpRequest& request)
{
const auto request_id = request.header("x-request-id");
if (!request_id || request_id->empty()) {
return error_response(428, "x-request-id required");
}
const auto match = request.header("if-match");
if (!match) {
return error_response(428, "if-match required");
}
const auto version = parse_etag(*match);
if (!version) {
return error_response(400, "invalid if-match");
}
auto result = m_store.erase(key, Precondition::at_version(*version),
RequestId{std::string{*request_id}});
if (!result) {
return error_response(status_for(result.error()),
result.error().message());
}
switch (result->outcome) {
case WriteOutcome::Applied: {
HttpResponse response;
response.status = 204;
return response;
}
case WriteOutcome::Conflict:
return error_response(412, "version precondition failed");
case WriteOutcome::NotFound:
return error_response(404, "not found");
case WriteOutcome::Unknown:
return error_response(503, "commit outcome unknown");
}
return error_response(500, "unreachable");
}
HttpResponse KvApi::kv_scan(const HttpRequest& request)
{
const auto query = query_of(request.target);
const auto cursor = query_param(query, "cursor");
std::size_t limit = 0;
if (const auto raw = query_param(query, "limit")) {
std::size_t parsed = 0;
const auto result = std::from_chars(
raw->data(), raw->data() + raw->size(), parsed);
if (result.ec != std::errc{} ||
result.ptr != raw->data() + raw->size() || parsed == 0) {
return error_response(400, "invalid limit");
}
limit = std::min(parsed, m_config.max_scan_limit);
}
auto page = m_store.scan(cursor ? std::optional<std::string_view>{*cursor}
: std::nullopt,
limit);
if (!page) {
return error_response(status_for(page.error()),
page.error().message());
}
std::string body = "{\"items\":[";
for (std::size_t i = 0; i < page->items.size(); ++i) {
const auto& item = page->items[i];
if (i != 0) {
body += ',';
}
body += "{\"key\":\"" + json_escape(item.key, 1024) +
"\",\"version\":" + std::to_string(item.entry.version) +
",\"value\":\"" + json_escape(item.entry.value, 64 * 1024) +
"\"}";
}
body += "],\"next_cursor\":";
if (page->next_cursor) {
body += "\"" + json_escape(*page->next_cursor, 1024) + "\"";
} else {
body += "null";
}
body += '}';
HttpResponse response;
response.status = 200;
response.headers["content-type"] = std::string{kJsonType};
response.headers["cache-control"] = "no-store";
response.body = std::move(body);
return response;
}
HttpResponse KvApi::kv_operation(std::string_view request_id)
{
HttpResponse response;
response.status = 200;
response.headers["content-type"] = std::string{kJsonType};
response.headers["cache-control"] = "no-store";
if (request_id.empty()) {
return error_response(400, "operation id required");
}
auto recorded = m_store.lookup_operation(RequestId{std::string{request_id}});
if (!recorded) {
return error_response(status_for(recorded.error()),
recorded.error().message());
}
if (!recorded->has_value()) {
// Absence or expired retention is explicitly unknown, never proof
// that the write did not commit.
response.body = "{\"outcome\":\"unknown\"}";
return response;
}
std::string_view outcome;
switch ((*recorded)->outcome) {
case WriteOutcome::Applied: outcome = "applied"; break;
case WriteOutcome::Conflict: outcome = "conflict"; break;
case WriteOutcome::NotFound: outcome = "not_found"; break;
case WriteOutcome::Unknown: outcome = "unknown"; break;
}
response.body = "{\"outcome\":\"" + std::string{outcome} +
"\",\"version\":" +
std::to_string((*recorded)->version) + "}";
return response;
}
HttpResponse KvApi::admin(const HttpRequest& request) const
{
const auto path = path_of(request.target);
if (request.method != "GET") {
return error_response(405, "method not allowed");
}
if (path == "/live") {
return text_response(200, "ok");
}
if (path == "/ready") {
return m_ready ? text_response(200, "ready")
: text_response(503, "not ready");
}
if (path == "/metrics") {
std::string body;
body += "# bounded application counters\n";
body += "networked_kv_requests_total " +
std::to_string(m_metrics.requests) + "\n";
body += "networked_kv_unauthorized_total " +
std::to_string(m_metrics.unauthorized) + "\n";
body += "networked_kv_client_errors_total " +
std::to_string(m_metrics.client_errors) + "\n";
body += "networked_kv_server_errors_total " +
std::to_string(m_metrics.server_errors) + "\n";
body += "networked_kv_bytes_in_total " +
std::to_string(m_metrics.bytes_in) + "\n";
body += "networked_kv_bytes_out_total " +
std::to_string(m_metrics.bytes_out) + "\n";
return text_response(200, std::move(body));
}
return error_response(404, "not found");
}
} // namespace NetworkedKv
@@ -0,0 +1,232 @@
#include "networked_kv/job_service.hpp"
#include <Void/Time/Clock.hpp>
#include <exception>
#include <span>
#include <string>
#include <utility>
namespace NetworkedKv
{
namespace
{
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] Void::Result::Error not_found(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::not_found,
std::move(message)};
}
[[nodiscard]] std::vector<std::byte> to_bytes(std::string_view text)
{
const auto raw = std::as_bytes(std::span{text.data(), text.size()});
return std::vector<std::byte>{raw.begin(), raw.end()};
}
[[nodiscard]] std::string to_string(std::span<const std::byte> bytes)
{
return std::string{
reinterpret_cast<const char*>(bytes.data()), bytes.size()};
}
} // namespace
std::string_view job_state_name(JobState state) noexcept
{
switch (state) {
case JobState::Submitted: return "submitted";
case JobState::Running: return "running";
case JobState::Succeeded: return "succeeded";
case JobState::RetryScheduled: return "retry-scheduled";
case JobState::DeadLettered: return "dead-lettered";
case JobState::Unknown: return "unknown";
}
return "unknown";
}
JobService::JobService(Void::Messaging::Queue& queue,
JobServiceConfig config)
: m_queue(queue), m_config(std::move(config))
{
}
Void::Result::Result<void> JobService::initialize()
{
if (m_initialized) {
return {};
}
Void::Messaging::QueueConfig queue;
queue.name = m_config.queue_name;
queue.retry = Void::Messaging::RetryPolicy{
.max_attempts = m_config.max_attempts,
.base_delay = m_config.retry_delay,
.max_delay = m_config.retry_delay};
if (auto created = m_queue.create_queue(std::move(queue)); !created) {
return created;
}
Void::Messaging::GroupConfig group;
group.name = m_config.group_name;
group.visibility_timeout = m_config.visibility_timeout;
if (auto created =
m_queue.create_group(m_config.queue_name, std::move(group));
!created) {
return created;
}
m_initialized = true;
return {};
}
Void::Result::Result<std::string> JobService::submit(std::string payload)
{
if (!m_initialized) {
return std::unexpected{
conflict("JobService: initialize() before submitting")};
}
Void::Messaging::Message message;
message.id = "job-" + std::to_string(m_next_id++);
message.payload = to_bytes(payload);
auto published = m_queue.publish(
m_config.queue_name, std::move(message),
m_config.publish_durability);
if (!published) {
return std::unexpected{std::move(published).error()};
}
track(JobView{.id = published->message_id,
.state = JobState::Submitted});
return published->message_id;
}
Void::Result::Result<std::optional<JobView>>
JobService::process_one(const JobHandler& handler)
{
auto received =
m_queue.try_receive(m_config.queue_name, m_config.group_name);
if (!received) {
return std::unexpected{std::move(received).error()};
}
if (!received->has_value()) {
return std::optional<JobView>{};
}
Void::Messaging::Delivery delivery = std::move(**received);
const std::string id = delivery.message.id;
JobView view;
view.id = id;
view.attempts = delivery.attempt;
view.state = JobState::Running;
track(view);
Void::Result::Result<void> handled;
try {
handled = handler
? handler(to_string(delivery.message.payload),
delivery.attempt)
: Void::Result::Result<void>{};
} catch (const std::exception& error) {
handled = std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::internal,
std::string{"job handler threw: "} + error.what()}};
} catch (...) {
handled = std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::internal,
"job handler threw an unknown exception"}};
}
if (handled.has_value()) {
if (auto acknowledged = m_queue.ack(delivery.receipt);
!acknowledged) {
return std::unexpected{std::move(acknowledged).error()};
}
view.state = JobState::Succeeded;
track(view);
return std::optional<JobView>{view};
}
view.last_error = handled.error().message();
// Exhausted attempts are moved to the DLQ by the queue; record the
// terminal state now so status does not depend on another receive.
view.state = delivery.attempt >= m_config.max_attempts
? JobState::DeadLettered
: JobState::RetryScheduled;
if (auto rejected = m_queue.nack(delivery.receipt,
m_config.retry_delay);
!rejected) {
return std::unexpected{std::move(rejected).error()};
}
track(view);
return std::optional<JobView>{view};
}
Void::Result::Result<JobView>
JobService::status(std::string_view id) const
{
std::lock_guard lock{m_mutex};
const auto found = m_jobs.find(id);
if (found == m_jobs.end()) {
return std::unexpected{not_found(
"JobService: no tracked job for the given id")};
}
return found->second;
}
Void::Result::Result<std::size_t> JobService::maintain()
{
return m_queue.reap_expired_visibility();
}
Void::Result::Result<std::vector<Void::Messaging::DeadLetterEntry>>
JobService::dead_letters(std::size_t limit) const
{
return m_queue.list_dead_letters(m_config.queue_name,
m_config.group_name, limit);
}
Void::Result::Result<std::uint64_t> JobService::schedule_maintenance(
Void::Scheduler::Scheduler& scheduler, std::chrono::milliseconds period)
{
if (!m_maintenance_registered) {
auto registered = scheduler.register_handler(
"job-maintenance",
[this](const Void::Scheduler::OccurrenceContext&,
std::span<const std::byte>,
Void::Async::OperationOptions) -> Void::Result::Result<void> {
auto reaped = maintain();
if (!reaped) {
return std::unexpected{std::move(reaped).error()};
}
return {};
});
if (!registered) {
return std::unexpected{std::move(registered).error()};
}
m_maintenance_registered = true;
}
Void::Scheduler::JobSpec spec;
spec.id = "job-maintenance";
spec.handler_id = "job-maintenance";
spec.schedule = Void::Scheduler::Schedule::fixed_rate(
period, Void::Time::SystemMonotonicClock::instance().now());
return scheduler.add_job(std::move(spec));
}
void JobService::track(const JobView& view)
{
std::lock_guard lock{m_mutex};
const auto found = m_jobs.find(view.id);
if (found == m_jobs.end()) {
if (m_jobs.size() >= m_config.max_tracked_jobs &&
!m_order.empty()) {
m_jobs.erase(m_order.front());
m_order.pop_front();
}
m_order.push_back(view.id);
}
m_jobs.insert_or_assign(view.id, view);
}
} // namespace NetworkedKv
@@ -0,0 +1,210 @@
#include "networked_kv/domain.hpp"
#include <algorithm>
#include <string>
#include <utility>
namespace NetworkedKv
{
namespace
{
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
[[nodiscard]] bool matches(const std::optional<Entry>& current,
const Precondition& precondition) noexcept
{
if (precondition.kind == PreconditionKind::Absent) {
return !current.has_value();
}
return current.has_value() &&
current->version == precondition.version;
}
} // namespace
MemoryKvStore::MemoryKvStore(Limits limits)
: m_limits(limits)
{
}
Void::Result::Result<void>
MemoryKvStore::validate_key(std::string_view key) const
{
if (key.empty()) {
return std::unexpected{invalid("KvStore: key must not be empty")};
}
if (key.size() > m_limits.max_key_bytes) {
return std::unexpected{
invalid("KvStore: key exceeds max_key_bytes")};
}
return {};
}
Void::Result::Result<void>
MemoryKvStore::validate_request(const RequestId& request) const
{
if (request.value.empty()) {
return std::unexpected{
invalid("KvStore: request id must not be empty")};
}
if (request.value.size() > m_limits.max_request_id_bytes) {
return std::unexpected{
invalid("KvStore: request id exceeds max_request_id_bytes")};
}
return {};
}
std::optional<WriteResult>
MemoryKvStore::replay(const RequestId& request) const
{
const auto found = m_operations.find(request.value);
if (found == m_operations.end()) {
return std::nullopt;
}
return found->second;
}
void MemoryKvStore::remember(const RequestId& request,
const WriteResult& result)
{
if (m_limits.max_operation_records == 0) {
return;
}
if (m_operations.size() >= m_limits.max_operation_records &&
!m_operation_order.empty()) {
m_operations.erase(m_operation_order.front());
m_operation_order.erase(m_operation_order.begin());
}
m_operations.emplace(request.value, result);
m_operation_order.push_back(request.value);
}
Void::Result::Result<std::optional<Entry>>
MemoryKvStore::get(std::string_view key) const
{
if (auto valid = validate_key(key); !valid) {
return std::unexpected{std::move(valid).error()};
}
std::lock_guard lock{m_mutex};
const auto found = m_entries.find(key);
if (found == m_entries.end()) {
return std::optional<Entry>{};
}
return std::optional<Entry>{found->second};
}
Void::Result::Result<WriteResult>
MemoryKvStore::put(std::string_view key, std::string value,
Precondition precondition, RequestId request)
{
if (auto valid = validate_key(key); !valid) {
return std::unexpected{std::move(valid).error()};
}
if (auto valid = validate_request(request); !valid) {
return std::unexpected{std::move(valid).error()};
}
if (value.size() > m_limits.max_value_bytes) {
return std::unexpected{
invalid("KvStore: value exceeds max_value_bytes")};
}
std::lock_guard lock{m_mutex};
if (const auto replayed = replay(request)) {
return *replayed;
}
const auto found = m_entries.find(key);
const std::optional<Entry> current =
found == m_entries.end() ? std::nullopt
: std::optional<Entry>{found->second};
if (!matches(current, precondition)) {
WriteResult result{WriteOutcome::Conflict,
current ? current->version : 0};
remember(request, result);
return result;
}
const Version version = current ? current->version + 1 : 1;
m_entries.insert_or_assign(
std::string{key}, Entry{std::move(value), version});
WriteResult result{WriteOutcome::Applied, version};
remember(request, result);
return result;
}
Void::Result::Result<WriteResult>
MemoryKvStore::erase(std::string_view key, Precondition precondition,
RequestId request)
{
if (auto valid = validate_key(key); !valid) {
return std::unexpected{std::move(valid).error()};
}
if (auto valid = validate_request(request); !valid) {
return std::unexpected{std::move(valid).error()};
}
std::lock_guard lock{m_mutex};
if (const auto replayed = replay(request)) {
return *replayed;
}
const auto found = m_entries.find(key);
if (found == m_entries.end()) {
WriteResult result{WriteOutcome::NotFound, 0};
remember(request, result);
return result;
}
const std::optional<Entry> current = found->second;
if (!matches(current, precondition)) {
WriteResult result{WriteOutcome::Conflict, current->version};
remember(request, result);
return result;
}
m_entries.erase(found);
WriteResult result{WriteOutcome::Applied, 0};
remember(request, result);
return result;
}
Void::Result::Result<ScanPage>
MemoryKvStore::scan(std::optional<std::string_view> cursor,
std::size_t limit) const
{
const std::size_t page =
std::min(limit == 0 ? m_limits.max_scan_page : limit,
m_limits.max_scan_page);
std::lock_guard lock{m_mutex};
ScanPage out;
auto it = cursor ? m_entries.upper_bound(*cursor) : m_entries.begin();
while (it != m_entries.end() && out.items.size() < page) {
out.items.push_back(ScanItem{it->first, it->second});
++it;
}
if (it != m_entries.end() && !out.items.empty()) {
out.next_cursor = out.items.back().key;
}
return out;
}
} // namespace NetworkedKv
namespace NetworkedKv
{
Void::Result::Result<std::optional<WriteResult>>
MemoryKvStore::lookup_operation(const RequestId& request) const
{
if (auto valid = validate_request(request); !valid) {
return std::unexpected{std::move(valid).error()};
}
std::lock_guard lock{m_mutex};
const auto found = m_operations.find(request.value);
if (found == m_operations.end()) {
return std::optional<WriteResult>{};
}
return std::optional<WriteResult>{found->second};
}
} // namespace NetworkedKv
@@ -0,0 +1,91 @@
#include "networked_kv/service_directory.hpp"
#include <string>
#include <utility>
namespace NetworkedKv
{
ServiceDirectory::ServiceDirectory(ServiceDirectoryConfig config)
: m_config(std::move(config))
{
}
ServiceDirectory::~ServiceDirectory()
{
deregister();
}
Void::Result::Result<void>
ServiceDirectory::register_endpoint(std::uint16_t port)
{
if (m_registration.active()) {
return {};
}
if (m_config.instance_id.empty()) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"ServiceDirectory: instance_id is required"}};
}
if (port == 0) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::invalid_argument,
"ServiceDirectory: a bound port is required"}};
}
Void::Discovery::EndpointRecord record;
record.instance = m_config.instance_id;
record.service = m_config.service_name;
record.endpoint.scheme = m_config.scheme;
record.endpoint.host = m_config.advertise_host;
record.endpoint.port = port;
record.weight = m_config.weight;
record.ready = true;
auto registered = m_catalog.register_local(std::move(record));
if (!registered) {
return std::unexpected{std::move(registered).error()};
}
m_registration = std::move(*registered);
return {};
}
void ServiceDirectory::deregister() noexcept
{
if (m_registration.active()) {
m_registration.release();
}
}
Void::Result::Result<std::vector<Void::Discovery::EndpointRecord>>
ServiceDirectory::resolve(std::string_view service,
Void::Discovery::ResolvePolicy policy) const
{
auto snapshot = m_catalog.resolve(service, policy);
if (!snapshot) {
return std::unexpected{std::move(snapshot).error()};
}
return std::move(snapshot->records);
}
void ServiceDirectory::set_provider_health(
Void::Discovery::Freshness freshness,
std::optional<Void::Discovery::Error> provider_error) noexcept
{
m_catalog.set_provider_health(freshness, std::move(provider_error));
}
std::size_t ServiceDirectory::active_records() const noexcept
{
return m_catalog.active_record_count();
}
std::uint64_t ServiceDirectory::revision() const noexcept
{
return m_catalog.revision();
}
bool ServiceDirectory::registered() const noexcept
{
return m_registration.active();
}
} // namespace NetworkedKv
@@ -0,0 +1,531 @@
#include "networked_kv/sqlite_store.hpp"
#include <Void/Sqlite/Types.hpp>
#include <algorithm>
#include <cstdint>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
namespace NetworkedKv
{
using Void::Sqlite::BeginMode;
using Void::Sqlite::ValueView;
namespace
{
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
[[nodiscard]] int outcome_to_int(WriteOutcome outcome) noexcept
{
return static_cast<int>(outcome);
}
[[nodiscard]] WriteOutcome outcome_from_int(int value) noexcept
{
switch (value) {
case 0: return WriteOutcome::Applied;
case 1: return WriteOutcome::Conflict;
case 2: return WriteOutcome::NotFound;
default: return WriteOutcome::Unknown;
}
}
[[nodiscard]] bool matches(const std::optional<Entry>& current,
const Precondition& precondition) noexcept
{
if (precondition.kind == PreconditionKind::Absent) {
return !current.has_value();
}
return current.has_value() &&
current->version == precondition.version;
}
[[nodiscard]] ValueView blob_view(std::string_view value) noexcept
{
return ValueView{std::span<const std::byte>{
reinterpret_cast<const std::byte*>(value.data()), value.size()}};
}
} // namespace
SqliteKvStore::SqliteKvStore(Void::Sqlite::Database database, Limits limits)
: m_db(std::move(database))
, m_limits(limits)
{
}
Void::Result::Result<void> SqliteKvStore::ensure_schema()
{
if (auto wal = m_db.exec("PRAGMA journal_mode=WAL"); !wal) {
return std::unexpected{std::move(wal).error()};
}
if (auto kv = m_db.exec(
"CREATE TABLE IF NOT EXISTS kv("
"key TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL)");
!kv) {
return std::unexpected{std::move(kv).error()};
}
if (auto ops = m_db.exec(
"CREATE TABLE IF NOT EXISTS operations("
"request_id TEXT PRIMARY KEY, outcome INTEGER NOT NULL, "
"version INTEGER NOT NULL)");
!ops) {
return std::unexpected{std::move(ops).error()};
}
return {};
}
Void::Result::Result<std::unique_ptr<SqliteKvStore>>
SqliteKvStore::open(const std::filesystem::path& path, Limits limits)
{
auto database = Void::Sqlite::Database::open(path);
if (!database) {
return std::unexpected{std::move(database).error()};
}
std::unique_ptr<SqliteKvStore> store{
new SqliteKvStore{std::move(*database), limits}};
if (auto schema = store->ensure_schema(); !schema) {
return std::unexpected{std::move(schema).error()};
}
return store;
}
Void::Result::Result<std::optional<Entry>>
SqliteKvStore::get(std::string_view key) const
{
if (key.empty() || key.size() > m_limits.max_key_bytes) {
return std::unexpected{invalid("KvStore: invalid key")};
}
std::lock_guard lock{m_mutex};
auto statement = m_db.prepare("SELECT value, version FROM kv WHERE key = ?");
if (!statement) {
return std::unexpected{std::move(statement).error()};
}
if (auto bound = statement->bind_checked(1, ValueView{key}); !bound) {
return std::unexpected{std::move(bound).error()};
}
auto row = statement->step();
if (!row) {
return std::unexpected{std::move(row).error()};
}
if (!*row) {
return std::optional<Entry>{};
}
auto value = statement->try_column_blob(0);
auto version = statement->try_column_int(1);
if (!value || !version) {
return std::unexpected{invalid("KvStore: malformed row")};
}
Entry entry;
entry.value.assign(reinterpret_cast<const char*>(value->data()),
value->size());
entry.version = static_cast<Version>(*version);
return std::optional<Entry>{std::move(entry)};
}
Void::Result::Result<WriteResult>
SqliteKvStore::put(std::string_view key, std::string value,
Precondition precondition, RequestId request)
{
if (key.empty() || key.size() > m_limits.max_key_bytes) {
return std::unexpected{invalid("KvStore: invalid key")};
}
if (request.value.empty() ||
request.value.size() > m_limits.max_request_id_bytes) {
return std::unexpected{invalid("KvStore: invalid request id")};
}
if (value.size() > m_limits.max_value_bytes) {
return std::unexpected{invalid("KvStore: value too large")};
}
std::lock_guard lock{m_mutex};
auto transaction = m_db.begin(Void::Sqlite::BeginMode::Immediate);
if (!transaction) {
return std::unexpected{std::move(transaction).error()};
}
const auto rollback = [&] { (void)transaction->rollback_checked(); };
// Idempotent replay.
{
auto replay = m_db.prepare(
"SELECT outcome, version FROM operations WHERE request_id = ?");
if (!replay) {
rollback();
return std::unexpected{std::move(replay).error()};
}
if (auto bound =
replay->bind_checked(1, ValueView{request.value});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = replay->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto outcome = replay->try_column_int(0);
auto version = replay->try_column_int(1);
if (!outcome || !version) {
rollback();
return std::unexpected{invalid("KvStore: malformed operation")};
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return WriteResult{outcome_from_int(
static_cast<int>(*outcome)),
static_cast<Version>(*version)};
}
}
std::optional<Entry> current;
{
auto existing =
m_db.prepare("SELECT value, version FROM kv WHERE key = ?");
if (!existing) {
rollback();
return std::unexpected{std::move(existing).error()};
}
if (auto bound = existing->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = existing->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto version = existing->try_column_int(1);
if (!version) {
rollback();
return std::unexpected{invalid("KvStore: malformed row")};
}
current = Entry{{}, static_cast<Version>(*version)};
}
}
WriteResult result;
if (!matches(current, precondition)) {
result = WriteResult{WriteOutcome::Conflict,
current ? current->version : 0};
} else {
const Version version = current ? current->version + 1 : 1;
auto upsert = m_db.prepare(
"INSERT INTO kv(key, value, version) VALUES(?, ?, ?) "
"ON CONFLICT(key) DO UPDATE SET "
"value = excluded.value, version = excluded.version");
if (!upsert) {
rollback();
return std::unexpected{std::move(upsert).error()};
}
if (auto bound = upsert->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = upsert->bind_checked(2, blob_view(value)); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = upsert->bind_checked(
3, ValueView{static_cast<std::int64_t>(version)});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto stepped = upsert->step();
if (!stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
result = WriteResult{WriteOutcome::Applied, version};
}
{
auto record = m_db.prepare(
"INSERT INTO operations(request_id, outcome, version) "
"VALUES(?, ?, ?)");
if (!record) {
rollback();
return std::unexpected{std::move(record).error()};
}
if (auto bound =
record->bind_checked(1, ValueView{request.value});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = record->bind_checked(
2, ValueView{outcome_to_int(result.outcome)});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = record->bind_checked(
3, ValueView{static_cast<std::int64_t>(result.version)});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto stepped = record->step();
if (!stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return result;
}
Void::Result::Result<WriteResult>
SqliteKvStore::erase(std::string_view key, Precondition precondition,
RequestId request)
{
if (key.empty() || key.size() > m_limits.max_key_bytes) {
return std::unexpected{invalid("KvStore: invalid key")};
}
if (request.value.empty() ||
request.value.size() > m_limits.max_request_id_bytes) {
return std::unexpected{invalid("KvStore: invalid request id")};
}
std::lock_guard lock{m_mutex};
auto transaction = m_db.begin(Void::Sqlite::BeginMode::Immediate);
if (!transaction) {
return std::unexpected{std::move(transaction).error()};
}
const auto rollback = [&] { (void)transaction->rollback_checked(); };
{
auto replay = m_db.prepare(
"SELECT outcome, version FROM operations WHERE request_id = ?");
if (!replay) {
rollback();
return std::unexpected{std::move(replay).error()};
}
if (auto bound =
replay->bind_checked(1, ValueView{request.value});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = replay->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto outcome = replay->try_column_int(0);
auto version = replay->try_column_int(1);
if (!outcome || !version) {
rollback();
return std::unexpected{invalid("KvStore: malformed operation")};
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return WriteResult{outcome_from_int(
static_cast<int>(*outcome)),
static_cast<Version>(*version)};
}
}
std::optional<Version> current;
{
auto existing = m_db.prepare("SELECT version FROM kv WHERE key = ?");
if (!existing) {
rollback();
return std::unexpected{std::move(existing).error()};
}
if (auto bound = existing->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = existing->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto version = existing->try_column_int(0);
if (!version) {
rollback();
return std::unexpected{invalid("KvStore: malformed row")};
}
current = static_cast<Version>(*version);
}
}
WriteResult result;
if (!current) {
result = WriteResult{WriteOutcome::NotFound, 0};
} else if (precondition.kind == PreconditionKind::Version &&
*current != precondition.version) {
result = WriteResult{WriteOutcome::Conflict, *current};
} else if (precondition.kind == PreconditionKind::Absent) {
result = WriteResult{WriteOutcome::Conflict, *current};
} else {
auto remove = m_db.prepare("DELETE FROM kv WHERE key = ?");
if (!remove) {
rollback();
return std::unexpected{std::move(remove).error()};
}
if (auto bound = remove->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto stepped = remove->step();
if (!stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
result = WriteResult{WriteOutcome::Applied, 0};
}
{
auto record = m_db.prepare(
"INSERT INTO operations(request_id, outcome, version) "
"VALUES(?, ?, ?)");
if (!record) {
rollback();
return std::unexpected{std::move(record).error()};
}
(void)record->bind_checked(1, ValueView{request.value});
(void)record->bind_checked(
2, ValueView{outcome_to_int(result.outcome)});
(void)record->bind_checked(
3, ValueView{static_cast<std::int64_t>(result.version)});
if (auto stepped = record->step(); !stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return result;
}
Void::Result::Result<ScanPage>
SqliteKvStore::scan(std::optional<std::string_view> cursor,
std::size_t limit) const
{
const std::size_t page =
std::min(limit == 0 ? m_limits.max_scan_page : limit,
m_limits.max_scan_page);
if (page == 0) {
return ScanPage{};
}
std::lock_guard lock{m_mutex};
auto statement = m_db.prepare(
"SELECT key, value, version FROM kv WHERE key > ? "
"ORDER BY key LIMIT ?");
if (!statement) {
return std::unexpected{std::move(statement).error()};
}
if (auto bound = statement->bind_checked(
1, ValueView{cursor.value_or(std::string_view{})});
!bound) {
return std::unexpected{std::move(bound).error()};
}
if (auto bound = statement->bind_checked(
2, ValueView{static_cast<std::int64_t>(page + 1)});
!bound) {
return std::unexpected{std::move(bound).error()};
}
ScanPage out;
while (true) {
auto row = statement->step();
if (!row) {
return std::unexpected{std::move(row).error()};
}
if (!*row) {
break;
}
auto key = statement->try_column_text(0);
auto value = statement->try_column_blob(1);
auto version = statement->try_column_int(2);
if (!key || !value || !version) {
return std::unexpected{invalid("KvStore: malformed scan row")};
}
if (out.items.size() == page) {
out.next_cursor = out.items.back().key;
break;
}
Entry entry;
entry.value.assign(reinterpret_cast<const char*>(value->data()),
value->size());
entry.version = static_cast<Version>(*version);
out.items.push_back(
ScanItem{std::string{*key}, std::move(entry)});
}
return out;
}
} // namespace NetworkedKv
namespace NetworkedKv
{
Void::Result::Result<Void::Sqlite::BackupReport>
SqliteKvStore::backup_to(const std::filesystem::path& destination)
{
std::lock_guard lock{m_mutex};
return m_db.backup_to(destination);
}
Void::Result::Result<Void::Sqlite::BackupReport>
SqliteKvStore::restore_from(const std::filesystem::path& source)
{
std::lock_guard lock{m_mutex};
return m_db.restore_from(source);
}
} // namespace NetworkedKv
namespace NetworkedKv
{
Void::Result::Result<std::optional<WriteResult>>
SqliteKvStore::lookup_operation(const RequestId& request) const
{
if (request.value.empty() ||
request.value.size() > m_limits.max_request_id_bytes) {
return std::unexpected{invalid("KvStore: invalid request id")};
}
std::lock_guard lock{m_mutex};
auto statement = m_db.prepare(
"SELECT outcome, version FROM operations WHERE request_id = ?");
if (!statement) {
return std::unexpected{std::move(statement).error()};
}
if (auto bound = statement->bind_checked(1, ValueView{request.value});
!bound) {
return std::unexpected{std::move(bound).error()};
}
auto row = statement->step();
if (!row) {
return std::unexpected{std::move(row).error()};
}
if (!*row) {
return std::optional<WriteResult>{};
}
auto outcome = statement->try_column_int(0);
auto version = statement->try_column_int(1);
if (!outcome || !version) {
return std::unexpected{invalid("KvStore: malformed operation")};
}
return std::optional<WriteResult>{WriteResult{
outcome_from_int(static_cast<int>(*outcome)),
static_cast<Version>(*version)}};
}
} // namespace NetworkedKv
@@ -0,0 +1,400 @@
#include "networked_kv/application.hpp"
#include <Void/Net/Http.hpp>
#include <cassert>
#include <cstdio>
#include <filesystem>
#include <string>
#include <unistd.h>
namespace
{
using namespace NetworkedKv;
void config_validation()
{
NetworkedConfig bad;
bad.listen_address.clear();
assert(!bad.validate().has_value());
NetworkedConfig no_connections;
no_connections.max_connections = 0;
assert(!no_connections.validate().has_value());
NetworkedConfig ok;
assert(ok.validate().has_value());
}
void managed_mode_owns_the_host()
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
auto app = NetworkedApplication::create(resources, NetworkedConfig{});
assert(app.has_value());
// Construction opens no listener or worker.
const auto created = app->health();
assert(created.state == ApplicationState::Created);
assert(!created.ready);
assert(app->start().has_value());
const auto running = app->health();
assert(running.state == ApplicationState::Running);
assert(running.managed);
auto report = app->stop();
assert(report.has_value());
assert(app->health().state == ApplicationState::Stopped);
// Idempotent.
assert(app->stop().has_value());
}
void embedded_mode_borrows_the_host()
{
auto host = Void::Runtime::Host::create();
assert(host.has_value());
assert(host->start().has_value());
ApplicationResources resources;
resources.ownership = ResourceOwnership::Embedded;
resources.borrowed_host = &*host;
auto app = NetworkedApplication::create(resources, NetworkedConfig{});
assert(app.has_value());
assert(app->start().has_value());
assert(app->health().state == ApplicationState::Running);
assert(app->stop().has_value());
// The borrowed host is not shut down by the composition.
assert(host->is_running());
(void)host->shutdown_blocking();
}
void embedded_requires_a_host()
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Embedded;
auto app = NetworkedApplication::create(resources, NetworkedConfig{});
assert(!app.has_value());
}
void http_listener_serves_kv()
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
NetworkedConfig config;
config.listen_address = "127.0.0.1:0";
config.bearer_token = "secret";
auto app = NetworkedApplication::create(resources, config);
assert(app.has_value());
assert(app->start().has_value());
const auto port = app->health().bound_port;
assert(port != 0);
const std::string base =
"http://127.0.0.1:" + std::to_string(port);
Void::Net::HttpClient client;
auto unauthorized = client.get(base + "/v1/kv/a");
assert(unauthorized.has_value());
assert(unauthorized->status == 401);
Void::Net::Request put;
put.method = Void::Net::Method::Put;
put.url = base + "/v1/kv/a";
put.body = std::string{"one"};
put.headers.push_back(
Void::Net::Header{"authorization", "Bearer secret"});
put.headers.push_back(Void::Net::Header{"x-request-id", "r1"});
put.headers.push_back(Void::Net::Header{"if-none-match", "*"});
auto created = client.send(put);
assert(created.has_value());
assert(created->status == 200);
auto got = client.get(
base + "/v1/kv/a",
{Void::Net::Header{"authorization", "Bearer secret"}});
assert(got.has_value());
assert(got->status == 200);
assert(got->body == "one");
assert(app->stop().has_value());
assert(app->health().bound_port == 0);
}
void admin_listener_is_separate()
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
NetworkedConfig config;
config.listen_address = "127.0.0.1:0";
config.admin_address = "127.0.0.1:0";
config.bearer_token = "secret";
auto app = NetworkedApplication::create(resources, config);
assert(app.has_value());
assert(app->start().has_value());
const auto data_port = app->health().bound_port;
const auto admin_port = app->admin_bound_port();
assert(data_port != 0);
assert(admin_port != 0);
assert(admin_port != data_port);
Void::Net::HttpClient client;
const std::string admin_base =
"http://127.0.0.1:" + std::to_string(admin_port);
auto live = client.get(admin_base + "/live");
assert(live.has_value() && live->status == 200);
auto ready = client.get(admin_base + "/ready");
assert(ready.has_value() && ready->status == 200);
auto metrics = client.get(admin_base + "/metrics");
assert(metrics.has_value() && metrics->status == 200);
assert(metrics->body.find("networked_kv_requests_total") !=
std::string::npos);
// Administrative routes are not exposed on the data plane.
const std::string data_base =
"http://127.0.0.1:" + std::to_string(data_port);
auto not_admin = client.get(data_base + "/live");
assert(not_admin.has_value() && not_admin->status == 404);
assert(app->stop().has_value());
assert(app->admin_bound_port() == 0);
}
void durable_profile_survives_restart()
{
const auto directory = std::filesystem::temp_directory_path() /
("void-netapp-" + std::to_string(::getpid()));
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory);
const std::string path = (directory / "kv.db").string();
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
NetworkedConfig config;
config.listen_address = "127.0.0.1:0";
config.bearer_token = "secret";
config.storage_path = path;
auto app = NetworkedApplication::create(resources, config);
assert(app.has_value());
assert(app->start().has_value());
Void::Net::HttpClient client;
const std::string base =
"http://127.0.0.1:" + std::to_string(app->health().bound_port);
Void::Net::Request put;
put.method = Void::Net::Method::Put;
put.url = base + "/v1/kv/persist";
put.body = std::string{"durable"};
put.headers.push_back(
Void::Net::Header{"authorization", "Bearer secret"});
put.headers.push_back(Void::Net::Header{"x-request-id", "p1"});
put.headers.push_back(Void::Net::Header{"if-none-match", "*"});
auto created = client.send(put);
assert(created.has_value());
assert(created->status == 200);
assert(app->stop().has_value());
}
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
NetworkedConfig config;
config.listen_address = "127.0.0.1:0";
config.bearer_token = "secret";
config.storage_path = path;
auto app = NetworkedApplication::create(resources, config);
assert(app.has_value());
assert(app->start().has_value());
Void::Net::HttpClient client;
const std::string base =
"http://127.0.0.1:" + std::to_string(app->health().bound_port);
auto got = client.get(
base + "/v1/kv/persist",
{Void::Net::Header{"authorization", "Bearer secret"}});
assert(got.has_value());
assert(got->status == 200);
assert(got->body == "durable");
assert(app->stop().has_value());
}
std::filesystem::remove_all(directory);
}
void config_reload_publishes_a_new_generation()
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
NetworkedConfig config;
config.listen_address = "127.0.0.1:0";
config.bearer_token = "secret";
auto app = NetworkedApplication::create(resources, config);
assert(app.has_value());
// Reload before start is rejected and publishes nothing.
assert(!app->reload(config).has_value());
assert(app->config_generation() == 0);
assert(app->start().has_value());
assert(app->config_generation() == 1);
const auto port = app->health().bound_port;
const std::string base =
"http://127.0.0.1:" + std::to_string(port);
Void::Net::HttpClient client;
// A restart-required change is rejected atomically.
NetworkedConfig rebound = app->config();
rebound.listen_address = "127.0.0.1:1";
auto rejected = app->reload(rebound);
assert(!rejected.has_value());
assert(app->config_generation() == 1);
assert(app->config().listen_address == "127.0.0.1:0");
assert(app->health().bound_port == port);
// An invalid candidate is rejected before anything is applied.
NetworkedConfig invalid = app->config();
invalid.max_scan_page = 0;
assert(!app->reload(invalid).has_value());
assert(app->config_generation() == 1);
// The bearer token rotates live without rebinding the listener.
NetworkedConfig rotated = app->config();
rotated.bearer_token = "rotated";
assert(app->reload(std::move(rotated)).has_value());
assert(app->config_generation() == 2);
assert(app->health().bound_port == port);
auto old_token = client.get(
base + "/v1/kv/a",
{Void::Net::Header{"authorization", "Bearer secret"}});
assert(old_token.has_value());
assert(old_token->status == 401);
auto new_token = client.get(
base + "/v1/kv/a",
{Void::Net::Header{"authorization", "Bearer rotated"}});
assert(new_token.has_value());
assert(new_token->status == 404);
assert(app->stop().has_value());
}
void durable_backup_and_restore_roundtrip()
{
const auto directory = std::filesystem::temp_directory_path() /
("void-netapp-backup-" + std::to_string(::getpid()));
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory);
const std::string path = (directory / "kv.db").string();
const std::string backup = (directory / "kv.backup.db").string();
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
NetworkedConfig config;
config.listen_address = "127.0.0.1:0";
config.bearer_token = "secret";
config.storage_path = path;
auto app = NetworkedApplication::create(resources, config);
assert(app.has_value());
assert(app->start().has_value());
Void::Net::HttpClient client;
const std::string base =
"http://127.0.0.1:" + std::to_string(app->health().bound_port);
Void::Net::Request put;
put.method = Void::Net::Method::Put;
put.url = base + "/v1/kv/backed-up";
put.body = std::string{"value"};
put.headers.push_back(
Void::Net::Header{"authorization", "Bearer secret"});
put.headers.push_back(Void::Net::Header{"x-request-id", "b1"});
put.headers.push_back(Void::Net::Header{"if-none-match", "*"});
auto created = client.send(put);
assert(created.has_value());
assert(created->status == 200);
assert(app->backup_storage(backup).has_value());
assert(std::filesystem::exists(backup));
// Mutate after the backup so restore is observable.
Void::Net::Request overwrite = put;
overwrite.body = std::string{"changed"};
overwrite.headers[1].value = "b2";
overwrite.headers[2] = Void::Net::Header{"if-match", "\"1\""};
auto updated = client.send(overwrite);
assert(updated.has_value());
assert(updated->status == 200);
assert(app->restore_storage(backup).has_value());
auto got = client.get(
base + "/v1/kv/backed-up",
{Void::Net::Header{"authorization", "Bearer secret"}});
assert(got.has_value());
assert(got->status == 200);
assert(got->body == "value");
assert(app->stop().has_value());
}
std::filesystem::remove_all(directory);
}
void discovery_registers_the_live_endpoint()
{
// Enabling discovery without an instance identity is rejected.
NetworkedConfig missing_identity;
missing_identity.discovery_enabled = true;
assert(!missing_identity.validate().has_value());
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
NetworkedConfig config;
config.listen_address = "127.0.0.1:0";
config.bearer_token = "secret";
config.discovery_enabled = true;
config.discovery_instance = "test-node";
auto app = NetworkedApplication::create(resources, config);
assert(app.has_value());
assert(app->directory() != nullptr);
assert(app->start().has_value());
const auto port = app->health().bound_port;
assert(app->health().discovery_registered);
assert(app->health().discovery_error.empty());
auto records = app->directory()->resolve("networked-kv");
assert(records.has_value());
assert(records->size() == 1);
assert((*records)[0].instance == "test-node");
assert((*records)[0].endpoint.port == port);
assert(app->stop().has_value());
assert(!app->directory()->registered());
auto after = app->directory()->resolve("networked-kv");
assert(after.has_value());
assert(after->empty());
// The directory is optional and absent by default.
auto plain = NetworkedApplication::create(resources, NetworkedConfig{});
assert(plain.has_value());
assert(plain->directory() == nullptr);
}
} // namespace
int main()
{
config_validation();
managed_mode_owns_the_host();
embedded_mode_borrows_the_host();
embedded_requires_a_host();
http_listener_serves_kv();
admin_listener_is_separate();
durable_profile_survives_restart();
config_reload_publishes_a_new_generation();
durable_backup_and_restore_roundtrip();
discovery_registers_the_live_endpoint();
std::puts("networked-kv lifecycle ok");
return 0;
}
@@ -0,0 +1,156 @@
#include "networked_kv/domain.hpp"
#include <cassert>
#include <cstdio>
#include <optional>
#include <string>
#include <vector>
namespace
{
using namespace NetworkedKv;
void versioned_lifecycle()
{
MemoryKvStore store;
auto created = store.put("a", "one", Precondition::absent(), {"r1"});
assert(created.has_value());
assert(created->outcome == WriteOutcome::Applied);
assert(created->version == 1);
auto got = store.get("a");
assert(got.has_value() && got->has_value());
assert((*got)->value == "one");
// Absent precondition no longer holds.
auto conflict = store.put("a", "two", Precondition::absent(), {"r2"});
assert(conflict.has_value());
assert(conflict->outcome == WriteOutcome::Conflict);
auto updated =
store.put("a", "two", Precondition::at_version(1), {"r3"});
assert(updated.has_value());
assert(updated->outcome == WriteOutcome::Applied);
assert(updated->version == 2);
// Replaying the same request id returns the recorded outcome without
// applying the mutation again.
auto replay =
store.put("a", "ignored", Precondition::at_version(2), {"r3"});
assert(replay.has_value());
assert(replay->outcome == WriteOutcome::Applied);
assert(replay->version == 2);
auto current = store.get("a");
assert(current.has_value() && current->has_value());
assert((*current)->value == "two");
assert((*current)->version == 2);
auto stale = store.erase("a", Precondition::at_version(1), {"r4"});
assert(stale.has_value());
assert(stale->outcome == WriteOutcome::Conflict);
auto erased = store.erase("a", Precondition::at_version(2), {"r5"});
assert(erased.has_value());
assert(erased->outcome == WriteOutcome::Applied);
assert(!store.get("a")->has_value());
auto missing = store.erase("missing", Precondition::absent(), {"r6"});
assert(missing.has_value());
assert(missing->outcome == WriteOutcome::NotFound);
}
void input_validation()
{
MemoryKvStore store;
assert(!store.put("", "x", Precondition::absent(), {"r"}).has_value());
assert(!store.put("k", "x", Precondition::absent(), {""}).has_value());
MemoryKvStore small{Limits{.max_key_bytes = 2, .max_value_bytes = 2}};
assert(!small.put("key", "x", Precondition::absent(), {"r"}).has_value());
assert(!small.put("k", "long", Precondition::absent(), {"r"}).has_value());
}
void bounded_scan()
{
MemoryKvStore store{Limits{.max_scan_page = 2}};
for (int i = 0; i < 5; ++i) {
const std::string key(1, static_cast<char>('a' + i));
auto written = store.put(key, "v", Precondition::absent(),
{"s" + std::to_string(i)});
assert(written.has_value());
}
std::vector<std::string> keys;
std::optional<std::string> cursor;
for (;;) {
auto page = store.scan(
cursor ? std::optional<std::string_view>{*cursor} : std::nullopt);
assert(page.has_value());
assert(page->items.size() <= 2);
for (const auto& item : page->items) {
keys.push_back(item.key);
}
if (!page->next_cursor) {
break;
}
cursor = page->next_cursor;
}
assert(keys.size() == 5);
assert(keys.front() == "a");
assert(keys.back() == "e");
}
void bounded_operation_records()
{
MemoryKvStore store{Limits{.max_operation_records = 2}};
for (int i = 0; i < 5; ++i) {
const auto precondition = i == 0 ? Precondition::absent()
: Precondition::at_version(
static_cast<Version>(i));
auto written = store.put("k", "v" + std::to_string(i), precondition,
{"b" + std::to_string(i)});
assert(written.has_value());
assert(written->outcome == WriteOutcome::Applied);
}
// The store keeps working after evicting old operation records.
auto got = store.get("k");
assert(got.has_value() && got->has_value());
assert((*got)->version == 5);
}
void operation_lookup_reports_recorded_outcomes()
{
MemoryKvStore store;
auto applied =
store.put("k", "v", Precondition::absent(), {"op-1"});
assert(applied.has_value());
assert(applied->outcome == WriteOutcome::Applied);
// A replayed request id resolves to the original outcome.
auto replayed = store.put("k", "ignored", Precondition::absent(),
{"op-1"});
assert(replayed.has_value());
assert(replayed->version == applied->version);
auto known = store.lookup_operation({"op-1"});
assert(known.has_value() && known->has_value());
assert((*known)->outcome == WriteOutcome::Applied);
assert((*known)->version == applied->version);
// Unknown ids are absent (not an error), and invalid ids are errors.
auto absent = store.lookup_operation({"never-used"});
assert(absent.has_value() && !absent->has_value());
assert(!store.lookup_operation({""}).has_value());
}
} // namespace
int main()
{
versioned_lifecycle();
input_validation();
bounded_scan();
bounded_operation_records();
operation_lookup_reports_recorded_outcomes();
std::puts("networked-kv domain ok");
return 0;
}
@@ -0,0 +1,205 @@
#include "networked_kv/http_api.hpp"
#include <cassert>
#include <cstdio>
#include <string>
namespace
{
using namespace NetworkedKv;
HttpRequest make_request(std::string method, std::string target,
std::string body = {})
{
HttpRequest request;
request.method = std::move(method);
request.target = std::move(target);
request.body = std::move(body);
return request;
}
HttpRequest authed(HttpRequest request)
{
request.headers["authorization"] = "Bearer secret";
return request;
}
void bearer_auth_is_required()
{
MemoryKvStore store;
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
assert(api.handle(make_request("GET", "/v1/kv/a")).status == 401);
auto wrong = make_request("GET", "/v1/kv/a");
wrong.headers["authorization"] = "Bearer wrong";
assert(api.handle(wrong).status == 401);
assert(api.metrics().unauthorized == 2);
// Fail closed when no token is configured.
KvApi unconfigured{store, ApiConfig{}};
assert(unconfigured.handle(authed(make_request("GET", "/v1/kv/a")))
.status == 401);
}
void kv_lifecycle_over_http()
{
MemoryKvStore store;
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
auto put = authed(make_request("PUT", "/v1/kv/a", "one"));
put.headers["x-request-id"] = "r1";
put.headers["if-none-match"] = "*";
auto created = api.handle(put);
assert(created.status == 200);
assert(created.headers.at("etag") == "\"1\"");
auto get = authed(make_request("GET", "/v1/kv/a"));
auto got = api.handle(get);
assert(got.status == 200);
assert(got.body == "one");
assert(got.headers.at("etag") == "\"1\"");
auto stale = authed(make_request("PUT", "/v1/kv/a", "two"));
stale.headers["x-request-id"] = "r2";
stale.headers["if-match"] = "\"9\"";
assert(api.handle(stale).status == 412);
// Replaying the same request id returns the recorded outcome and does
// not apply the mutation again.
auto replay = authed(make_request("PUT", "/v1/kv/a", "ignored"));
replay.headers["x-request-id"] = "r1";
replay.headers["if-none-match"] = "*";
auto replayed = api.handle(replay);
assert(replayed.status == 200);
assert(replayed.headers.at("etag") == "\"1\"");
assert(api.handle(get).body == "one");
auto delete_stale = authed(make_request("DELETE", "/v1/kv/a"));
delete_stale.headers["x-request-id"] = "r3";
delete_stale.headers["if-match"] = "\"9\"";
assert(api.handle(delete_stale).status == 412);
auto remove = authed(make_request("DELETE", "/v1/kv/a"));
remove.headers["x-request-id"] = "r4";
remove.headers["if-match"] = "\"1\"";
assert(api.handle(remove).status == 204);
assert(api.handle(get).status == 404);
}
void request_validation()
{
MemoryKvStore store;
KvApi api{store, ApiConfig{.bearer_token = "secret",
.max_body_bytes = 4}};
auto oversized = authed(make_request("PUT", "/v1/kv/a", "12345"));
oversized.headers["x-request-id"] = "r";
oversized.headers["if-none-match"] = "*";
assert(api.handle(oversized).status == 413);
auto no_id = authed(make_request("PUT", "/v1/kv/a", "x"));
no_id.headers["if-none-match"] = "*";
assert(api.handle(no_id).status == 428);
auto no_precondition = authed(make_request("PUT", "/v1/kv/a", "x"));
no_precondition.headers["x-request-id"] = "r";
assert(api.handle(no_precondition).status == 428);
assert(api.handle(authed(make_request("POST", "/v1/kv/a")))
.status == 405);
assert(api.handle(authed(make_request("GET", "/v1/nope"))).status ==
404);
}
void operation_status_endpoint()
{
MemoryKvStore store;
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
auto put = authed(make_request("PUT", "/v1/kv/a", "one"));
put.headers["x-request-id"] = "op-1";
put.headers["if-none-match"] = "*";
assert(api.handle(put).status == 200);
auto known =
api.handle(authed(make_request("GET", "/v1/operations/op-1")));
assert(known.status == 200);
assert(known.body.find("\"outcome\":\"applied\"") != std::string::npos);
// Absence is explicitly unknown, not a 404 claiming no commit.
auto unknown =
api.handle(authed(make_request("GET", "/v1/operations/missing")));
assert(unknown.status == 200);
assert(unknown.body.find("\"outcome\":\"unknown\"") !=
std::string::npos);
// The endpoint requires authentication like the data plane.
assert(api.handle(make_request("GET", "/v1/operations/op-1")).status ==
401);
assert(api.handle(authed(make_request("POST", "/v1/operations/op-1")))
.status == 405);
}
void scan_is_bounded()
{
MemoryKvStore store{Limits{.max_scan_page = 2}};
KvApi api{store, ApiConfig{.bearer_token = "secret",
.max_scan_limit = 2}};
for (int i = 0; i < 5; ++i) {
auto put = authed(make_request(
"PUT", "/v1/kv/" + std::string(1, static_cast<char>('a' + i)),
"v"));
put.headers["x-request-id"] = "s" + std::to_string(i);
put.headers["if-none-match"] = "*";
assert(api.handle(put).status == 200);
}
auto page = api.handle(authed(make_request("GET", "/v1/scan")));
assert(page.status == 200);
// Two items retained, and a cursor is offered for the rest.
std::size_t keys = 0;
for (std::size_t pos = 0;
(pos = page.body.find("\"key\":", pos)) != std::string::npos;
pos += 6) {
++keys;
}
assert(keys == 2);
assert(page.body.find("\"next_cursor\":null") == std::string::npos);
assert(api.handle(authed(make_request("GET", "/v1/scan?limit=0")))
.status == 400);
}
void admin_views_are_bounded()
{
MemoryKvStore store;
KvApi api{store, ApiConfig{.bearer_token = "secret"}};
assert(api.admin(make_request("GET", "/live")).status == 200);
assert(api.admin(make_request("GET", "/ready")).status == 200);
api.set_ready(false);
assert(api.admin(make_request("GET", "/ready")).status == 503);
(void)api.handle(authed(make_request("GET", "/v1/kv/a")));
auto metrics = api.admin(make_request("GET", "/metrics"));
assert(metrics.status == 200);
assert(metrics.body.find("networked_kv_requests_total") !=
std::string::npos);
// No credential material in the admin output.
assert(metrics.body.find("secret") == std::string::npos);
assert(api.admin(make_request("POST", "/live")).status == 405);
assert(api.admin(make_request("GET", "/unknown")).status == 404);
}
} // namespace
int main()
{
bearer_auth_is_required();
kv_lifecycle_over_http();
request_validation();
scan_is_bounded();
operation_status_endpoint();
admin_views_are_bounded();
std::puts("networked-kv http api ok");
return 0;
}
@@ -0,0 +1,191 @@
#include "networked_kv/job_service.hpp"
#include <Void/Messaging/Queue.hpp>
#include <Void/Scheduler/Scheduler.hpp>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
namespace
{
using namespace NetworkedKv;
JobServiceConfig config()
{
JobServiceConfig cfg;
cfg.max_attempts = 2;
cfg.retry_delay = std::chrono::milliseconds{0};
cfg.visibility_timeout = std::chrono::milliseconds{500};
return cfg;
}
void submit_requires_initialization()
{
Void::Messaging::InMemoryQueue queue;
JobService service{queue};
assert(!service.submit("payload").has_value());
}
void successful_job_is_acked_and_tracked()
{
Void::Messaging::InMemoryQueue queue;
JobService service{queue, config()};
assert(service.initialize().has_value());
auto id = service.submit("payload");
assert(id.has_value());
assert(service.status(*id)->state == JobState::Submitted);
int calls = 0;
auto processed = service.process_one(
[&](std::string_view payload, std::uint32_t attempt) {
++calls;
assert(payload == "payload");
assert(attempt == 1);
return Void::Result::Result<void>{};
});
assert(processed.has_value() && processed->has_value());
assert((*processed)->state == JobState::Succeeded);
assert(calls == 1);
const auto status = service.status(*id);
assert(status.has_value());
assert(status->state == JobState::Succeeded);
assert(status->attempts == 1);
// Acked: no redelivery and an empty receive.
auto none = service.process_one([](std::string_view,
std::uint32_t) {
return Void::Result::Result<void>{};
});
assert(none.has_value() && !none->has_value());
// Unknown ids are an explicit not-found error.
auto missing = service.status("never-submitted");
assert(!missing.has_value());
assert(missing.error().kind() == Void::Result::ErrorKind::not_found);
}
void failing_job_retries_then_dead_letters()
{
Void::Messaging::InMemoryQueue queue;
JobServiceConfig cfg = config();
cfg.max_attempts = 2;
JobService service{queue, cfg};
assert(service.initialize().has_value());
auto id = service.submit("poison");
assert(id.has_value());
const auto failing = [](std::string_view, std::uint32_t) {
return Void::Result::Result<void>{std::unexpected{
Void::Result::Error{Void::Result::ErrorKind::internal,
"handler exploded"}}};
};
auto first = service.process_one(failing);
assert(first.has_value() && first->has_value());
assert((*first)->attempts == 1);
assert((*first)->state == JobState::RetryScheduled);
assert((*first)->last_error == "handler exploded");
// Retry is immediately available (zero delay) and exhausts attempts.
auto second = service.process_one(failing);
assert(second.has_value() && second->has_value());
assert((*second)->attempts == 2);
assert((*second)->state == JobState::DeadLettered);
auto dead = service.dead_letters();
assert(dead.has_value());
assert(dead->size() == 1);
assert((*dead)[0].message.id == *id);
assert((*dead)[0].attempts == 2);
}
void throwing_handler_is_a_recorded_failure()
{
Void::Messaging::InMemoryQueue queue;
JobService service{queue, config()};
assert(service.initialize().has_value());
assert(service.submit("boom").has_value());
auto processed = service.process_one(
[](std::string_view, std::uint32_t) -> Void::Result::Result<void> {
throw std::runtime_error{"unexpected"};
});
assert(processed.has_value() && processed->has_value());
assert((*processed)->state == JobState::RetryScheduled);
assert((*processed)->last_error.find("unexpected") !=
std::string::npos);
}
void scheduler_driven_maintenance_reclaims_expired_deliveries()
{
Void::Messaging::InMemoryQueue queue;
JobServiceConfig cfg = config();
cfg.visibility_timeout = std::chrono::milliseconds{50};
JobService service{queue, cfg};
assert(service.initialize().has_value());
assert(service.submit("payload").has_value());
// Take the delivery in flight and let its visibility expire.
auto in_flight =
queue.try_receive(cfg.queue_name, cfg.group_name);
assert(in_flight.has_value() && in_flight->has_value());
std::this_thread::sleep_for(std::chrono::milliseconds{80});
auto scheduler = Void::Scheduler::Scheduler::create();
assert(scheduler.has_value());
auto job = service.schedule_maintenance(*scheduler,
std::chrono::seconds{1});
assert(job.has_value());
// The scheduler is pure: the caller drives it. A tick materializes due
// occurrences and dispatch_one executes at most one ready occurrence;
// its handler reaps the expired delivery.
assert(scheduler->tick().has_value());
(void)scheduler->dispatch_one();
auto processed = service.process_one([](std::string_view,
std::uint32_t attempt) {
assert(attempt == 2);
return Void::Result::Result<void>{};
});
assert(processed.has_value() && processed->has_value());
assert((*processed)->state == JobState::Succeeded);
assert((*processed)->attempts == 2);
assert(scheduler->close_and_join().has_value());
}
void tracked_status_is_bounded()
{
Void::Messaging::InMemoryQueue queue;
JobServiceConfig cfg = config();
cfg.max_tracked_jobs = 2;
JobService service{queue, cfg};
assert(service.initialize().has_value());
const auto first = service.submit("a");
const auto second = service.submit("b");
const auto third = service.submit("c");
assert(first.has_value() && second.has_value() && third.has_value());
// Oldest record evicted; recent ones retained.
assert(!service.status(*first).has_value());
assert(service.status(*second).has_value());
assert(service.status(*third).has_value());
}
} // namespace
int main()
{
submit_requires_initialization();
successful_job_is_acked_and_tracked();
failing_job_retries_then_dead_letters();
throwing_handler_is_a_recorded_failure();
scheduler_driven_maintenance_reclaims_expired_deliveries();
tracked_status_is_bounded();
std::puts("networked-kv job service ok");
return 0;
}
@@ -0,0 +1,264 @@
#include "networked_kv/application.hpp"
#include <Void/Net/Http.hpp>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <string>
#include <string_view>
#include <thread>
namespace
{
using namespace NetworkedKv;
/// Minimal raw HTTP peer so framing/overload behavior is observable
/// without the library's own client normalizing it.
class RawPeer
{
public:
explicit RawPeer(std::uint16_t port)
{
m_fd = ::socket(AF_INET, SOCK_STREAM, 0);
assert(m_fd >= 0);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
assert(::connect(m_fd, reinterpret_cast<sockaddr*>(&addr),
sizeof(addr)) == 0);
}
~RawPeer()
{
if (m_fd >= 0) {
(void)::close(m_fd);
}
}
RawPeer(const RawPeer&) = delete;
RawPeer& operator=(const RawPeer&) = delete;
void send(std::string_view bytes) const
{
std::size_t offset = 0;
while (offset < bytes.size()) {
const ssize_t written =
::send(m_fd, bytes.data() + offset,
bytes.size() - offset, MSG_NOSIGNAL);
assert(written > 0);
offset += static_cast<std::size_t>(written);
}
}
/// Read until the server closes or `timeout` elapses.
std::string read_until_closed(
std::chrono::milliseconds timeout = std::chrono::seconds{5})
{
std::string out;
const auto deadline =
std::chrono::steady_clock::now() + timeout;
for (;;) {
const auto remaining = deadline - std::chrono::steady_clock::now();
if (remaining <= std::chrono::milliseconds::zero()) {
break;
}
pollfd pfd{.fd = m_fd, .events = POLLIN, .revents = 0};
const int ready = ::poll(
&pfd, 1,
static_cast<int>(std::min<long long>(
std::chrono::duration_cast<std::chrono::milliseconds>(
remaining)
.count(),
1000)));
if (ready <= 0) {
if (ready == 0) {
continue;
}
break;
}
char buffer[4096];
const ssize_t read = ::recv(m_fd, buffer, sizeof(buffer), 0);
if (read <= 0) {
break;
}
out.append(buffer, static_cast<std::size_t>(read));
}
return out;
}
[[nodiscard]] int fd() const noexcept { return m_fd; }
private:
int m_fd{-1};
};
std::string raw_exchange(std::uint16_t port, std::string_view raw)
{
RawPeer peer{port};
peer.send(raw);
(void)::shutdown(peer.fd(), SHUT_WR);
return peer.read_until_closed();
}
NetworkedConfig config()
{
NetworkedConfig cfg;
cfg.listen_address = "127.0.0.1:0";
cfg.admin_address = "127.0.0.1:0";
cfg.bearer_token = "secret";
cfg.read_timeout = std::chrono::milliseconds{200};
cfg.write_timeout = std::chrono::milliseconds{200};
return cfg;
}
ApplicationResources managed()
{
ApplicationResources resources;
resources.ownership = ResourceOwnership::Managed;
return resources;
}
void malformed_framing_is_rejected()
{
auto app = NetworkedApplication::create(managed(), config());
assert(app.has_value());
assert(app->start().has_value());
const auto port = app->health().bound_port;
assert(raw_exchange(port, "NOT-HTTP\r\n\r\n")
.starts_with("HTTP/1.1 400"));
// Conflicting framing (smuggling shape) is rejected before routing.
assert(raw_exchange(port,
"POST /v1/kv/a HTTP/1.1\r\nHost: x\r\n"
"Content-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n"
"0\r\n\r\n")
.starts_with("HTTP/1.1 400"));
// A request line without a version is malformed.
assert(raw_exchange(port, "GET /v1/kv/a\r\n\r\n")
.starts_with("HTTP/1.1 400"));
assert(app->stop().has_value());
}
void oversized_header_and_body_are_bounded()
{
NetworkedConfig cfg = config();
cfg.max_header_bytes = 512;
cfg.max_request_bytes = 64;
auto app = NetworkedApplication::create(managed(), cfg);
assert(app.has_value());
assert(app->start().has_value());
const auto port = app->health().bound_port;
std::string huge = "GET /v1/kv/a HTTP/1.1\r\nHost: x\r\nX-Huge: ";
huge += std::string(2000, 'H');
huge += "\r\n\r\n";
assert(raw_exchange(port, huge).starts_with("HTTP/1.1 431"));
std::string body = "PUT /v1/kv/a HTTP/1.1\r\nHost: x\r\n";
body += "Authorization: Bearer secret\r\nX-Request-Id: r\r\n";
body += "If-None-Match: *\r\nContent-Length: 100\r\n\r\n";
body += std::string(100, 'B');
assert(raw_exchange(port, body).starts_with("HTTP/1.1 413"));
assert(app->stop().has_value());
}
void pipelining_and_keep_alive_preserve_order()
{
auto app = NetworkedApplication::create(managed(), config());
assert(app.has_value());
assert(app->start().has_value());
const auto port = app->health().bound_port;
RawPeer peer{port};
const std::string first =
"GET /v1/kv/missing HTTP/1.1\r\nHost: x\r\n"
"Authorization: Bearer secret\r\n\r\n";
// Two pipelined requests: the 404 for the missing key, then a 401 for
// the unauthenticated one, in that order.
peer.send(first +
"GET /v1/kv/missing HTTP/1.1\r\nHost: x\r\n\r\n");
(void)::shutdown(peer.fd(), SHUT_WR);
const std::string responses = peer.read_until_closed();
const auto first_response = responses.find("HTTP/1.1 404");
const auto second_response = responses.find("HTTP/1.1 401");
assert(first_response != std::string::npos);
assert(second_response != std::string::npos);
assert(first_response < second_response);
assert(app->stop().has_value());
}
void slow_header_is_bounded_by_the_read_timeout()
{
auto app = NetworkedApplication::create(managed(), config());
assert(app.has_value());
assert(app->start().has_value());
const auto port = app->health().bound_port;
RawPeer peer{port};
peer.send("GET /v1/kv/a HTTP/1.1\r\nHost: x\r\n");
const auto begin = std::chrono::steady_clock::now();
const std::string response =
peer.read_until_closed(std::chrono::seconds{5});
const auto elapsed = std::chrono::steady_clock::now() - begin;
// Bounded: the 200 ms read timeout ends the connection well before
// the client-side 5 second cap.
assert(response.empty());
assert(elapsed < std::chrono::seconds{4});
assert(app->stop().has_value());
}
void overload_returns_503_while_admin_stays_responsive()
{
NetworkedConfig cfg = config();
cfg.max_connections = 1;
auto app = NetworkedApplication::create(managed(), cfg);
assert(app.has_value());
assert(app->start().has_value());
const auto port = app->health().bound_port;
const auto admin_port = app->admin_bound_port();
// Occupy the only admitted connection with a partial request.
RawPeer held{port};
held.send("GET /v1/kv/a HTTP/1.1\r\nHost: x\r\n");
std::this_thread::sleep_for(std::chrono::milliseconds{50});
RawPeer second{port};
second.send("GET /v1/kv/a HTTP/1.1\r\nHost: x\r\n\r\n");
const std::string rejected = second.read_until_closed();
assert(rejected.starts_with("HTTP/1.1 503"));
// The administrative listener has its own admission reserve.
Void::Net::HttpClient client;
auto live = client.get("http://127.0.0.1:" +
std::to_string(admin_port) + "/live");
assert(live.has_value());
assert(live->status == 200);
assert(app->stop().has_value());
}
} // namespace
int main()
{
malformed_framing_is_rejected();
oversized_header_and_body_are_bounded();
pipelining_and_keep_alive_preserve_order();
slow_header_is_bounded_by_the_read_timeout();
overload_returns_503_while_admin_stays_responsive();
std::puts("networked-kv protocol matrix ok");
return 0;
}
@@ -0,0 +1,104 @@
#include "networked_kv/service_directory.hpp"
#include <cassert>
#include <cstdio>
#include <string>
namespace
{
using namespace NetworkedKv;
ServiceDirectoryConfig config()
{
ServiceDirectoryConfig cfg;
cfg.service_name = "networked-kv";
cfg.instance_id = "node-1";
return cfg;
}
void registration_resolves_and_deregisters()
{
ServiceDirectory directory{config()};
assert(!directory.registered());
assert(directory.register_endpoint(8080).has_value());
assert(directory.registered());
assert(directory.active_records() == 1);
// Idempotent while active.
assert(directory.register_endpoint(9090).has_value());
assert(directory.active_records() == 1);
auto records = directory.resolve("networked-kv");
assert(records.has_value());
assert(records->size() == 1);
assert((*records)[0].instance == "node-1");
assert((*records)[0].endpoint.port == 8080);
directory.deregister();
assert(!directory.registered());
assert(directory.active_records() == 0);
auto empty = directory.resolve("networked-kv");
assert(empty.has_value());
assert(empty->empty());
// Idempotent.
directory.deregister();
}
void registration_requires_identity_and_port()
{
ServiceDirectory no_id{ServiceDirectoryConfig{}};
assert(!no_id.register_endpoint(8080).has_value());
ServiceDirectory directory{config()};
assert(!directory.register_endpoint(0).has_value());
}
void provider_partition_does_not_break_registration()
{
ServiceDirectory directory{config()};
assert(directory.register_endpoint(8080).has_value());
// The upstream directory provider becomes unavailable (partition).
Void::Discovery::Error error;
directory.set_provider_health(Void::Discovery::Freshness::Unavailable,
error);
// Default policy refuses stale data...
auto strict = directory.resolve("networked-kv");
assert(!strict.has_value());
// ...but the explicit stale policy still sees the last known records.
Void::Discovery::ResolvePolicy stale;
stale.allow_stale = true;
auto tolerated = directory.resolve("networked-kv", stale);
assert(tolerated.has_value());
assert(tolerated->size() == 1);
// The local registration survives the provider outage.
assert(directory.registered());
assert(directory.active_records() == 1);
// Recovery restores fresh resolution.
directory.set_provider_health(Void::Discovery::Freshness::Fresh);
auto recovered = directory.resolve("networked-kv");
assert(recovered.has_value());
assert(recovered->size() == 1);
}
void unknown_service_resolves_empty()
{
ServiceDirectory directory{config()};
assert(directory.register_endpoint(8080).has_value());
auto records = directory.resolve("other-service");
assert(records.has_value());
assert(records->empty());
}
} // namespace
int main()
{
registration_resolves_and_deregisters();
registration_requires_identity_and_port();
provider_partition_does_not_break_registration();
unknown_service_resolves_empty();
std::puts("networked-kv service directory ok");
return 0;
}
@@ -0,0 +1,112 @@
#include "networked_kv/sqlite_store.hpp"
#include <cassert>
#include <cstdio>
#include <filesystem>
#include <optional>
#include <string>
#include <unistd.h>
namespace
{
using namespace NetworkedKv;
std::filesystem::path temp_database()
{
const auto directory =
std::filesystem::temp_directory_path() /
("void-kv-sqlite-" + std::to_string(::getpid()));
std::filesystem::create_directories(directory);
return directory / "kv.db";
}
} // namespace
int main()
{
const auto path = temp_database();
std::filesystem::remove_all(path.parent_path());
std::filesystem::create_directories(path.parent_path());
{
auto store = SqliteKvStore::open(path);
assert(store.has_value());
auto& kv = **store;
auto created = kv.put("a", "one", Precondition::absent(), {"r1"});
assert(created.has_value());
assert(created->outcome == WriteOutcome::Applied);
assert(created->version == 1);
auto conflict = kv.put("a", "two", Precondition::absent(), {"r2"});
assert(conflict.has_value());
assert(conflict->outcome == WriteOutcome::Conflict);
auto updated = kv.put("a", "two", Precondition::at_version(1), {"r3"});
assert(updated.has_value());
assert(updated->outcome == WriteOutcome::Applied);
assert(updated->version == 2);
// Idempotent replay does not mutate the row.
auto replay = kv.put("a", "ignored", Precondition::at_version(2), {"r3"});
assert(replay.has_value());
assert(replay->version == 2);
auto got = kv.get("a");
assert(got.has_value() && got->has_value());
assert((*got)->value == "two");
assert((*got)->version == 2);
for (int i = 0; i < 5; ++i) {
auto written = kv.put("s" + std::to_string(i), "v",
Precondition::absent(),
{"s" + std::to_string(i)});
assert(written.has_value());
}
std::size_t seen = 0;
std::optional<std::string> cursor;
for (;;) {
auto page = kv.scan(cursor ? std::optional<std::string_view>{*cursor}
: std::nullopt,
2);
assert(page.has_value());
assert(page->items.size() <= 2);
seen += page->items.size();
if (!page->next_cursor) {
break;
}
cursor = page->next_cursor;
}
assert(seen == 6);
}
// Reopen: durable rows and idempotency records survive.
{
auto store = SqliteKvStore::open(path);
assert(store.has_value());
auto& kv = **store;
auto got = kv.get("a");
assert(got.has_value() && got->has_value());
assert((*got)->value == "two");
auto replay = kv.put("a", "ignored", Precondition::at_version(2), {"r3"});
assert(replay.has_value());
assert(replay->version == 2);
// Idempotency outcomes survive the reopen and are queryable.
auto known = kv.lookup_operation({"r3"});
assert(known.has_value() && known->has_value());
assert((*known)->outcome == WriteOutcome::Applied);
assert((*known)->version == 2);
auto absent = kv.lookup_operation({"never-used"});
assert(absent.has_value() && !absent->has_value());
auto removed = kv.erase("a", Precondition::at_version(2), {"r4"});
assert(removed.has_value());
assert(removed->outcome == WriteOutcome::Applied);
assert(!kv.get("a")->has_value());
}
std::filesystem::remove_all(path.parent_path());
std::puts("networked-kv sqlite profile ok");
return 0;
}
+50
View File
@@ -0,0 +1,50 @@
cmake_minimum_required(VERSION 4.0)
project(ReloadableHost LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
find_package(Void CONFIG REQUIRED COMPONENTS Functional System)
add_library(reloadable_host STATIC
src/activation.cpp
src/checkpoint.cpp
src/control.cpp
src/posix_worker.cpp
src/release_registry.cpp
src/reload_transaction.cpp
src/resources.cpp
src/supervisor.cpp)
target_include_directories(reloadable_host PUBLIC include)
target_link_libraries(reloadable_host PUBLIC Void::Functional Void::System)
add_executable(reloadable_host_test tests/reload_transaction_test.cpp)
target_link_libraries(reloadable_host_test PRIVATE reloadable_host)
add_executable(reloadable_host_release_test tests/release_registry_test.cpp)
target_link_libraries(reloadable_host_release_test PRIVATE reloadable_host)
add_executable(reloadable_host_control_test tests/control_test.cpp)
target_link_libraries(reloadable_host_control_test PRIVATE reloadable_host)
add_executable(reloadable_host_checkpoint_test tests/checkpoint_test.cpp)
target_link_libraries(reloadable_host_checkpoint_test PRIVATE reloadable_host)
add_executable(reloadable_host_activation_test tests/activation_test.cpp)
target_link_libraries(reloadable_host_activation_test PRIVATE reloadable_host)
add_executable(reloadable_host_failure_matrix_test tests/reload_failure_matrix_test.cpp)
target_link_libraries(reloadable_host_failure_matrix_test PRIVATE reloadable_host)
add_executable(reloadable_host_supervisor_test tests/supervisor_test.cpp)
target_link_libraries(reloadable_host_supervisor_test PRIVATE reloadable_host)
enable_testing()
add_test(NAME reloadable_host_transaction COMMAND reloadable_host_test)
add_test(NAME reloadable_host_release COMMAND reloadable_host_release_test)
add_test(NAME reloadable_host_control COMMAND reloadable_host_control_test)
add_test(NAME reloadable_host_checkpoint COMMAND reloadable_host_checkpoint_test)
add_test(NAME reloadable_host_activation COMMAND reloadable_host_activation_test)
add_test(NAME reloadable_host_failure_matrix COMMAND reloadable_host_failure_matrix_test)
add_test(NAME reloadable_host_supervisor COMMAND reloadable_host_supervisor_test)
@@ -0,0 +1,256 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <vector>
namespace ReloadableHost
{
/// Durable phase of one host reload.
///
/// `Activated` is reversible and uncommitted: a crash here recovers to the
/// previous healthy release. `HealthyCommitted` is the single commit
/// marker: a crash after it keeps the candidate even when cleanup is
/// incomplete. `RolledBack` records an explicit pre-commit rollback.
enum class ActivationPhase : std::uint8_t {
None,
Activated,
HealthyCommitted,
RolledBack
};
struct ActivationRecord {
std::uint64_t transaction_id{0};
std::string previous_release;
std::string candidate_release;
std::uint64_t checkpoint_generation{0};
ActivationPhase phase{ActivationPhase::None};
};
struct ActivationLimits {
std::size_t max_release_bytes{256};
std::size_t max_record_bytes{4096};
};
/// Durable journal storage boundary. `write` must not report success
/// before the bytes are durable; a file-backed implementation owns
/// fsync and directory sync.
class ActivationStorage
{
public:
ActivationStorage() = default;
ActivationStorage(const ActivationStorage&) = delete;
ActivationStorage& operator=(const ActivationStorage&) = delete;
virtual ~ActivationStorage() = default;
[[nodiscard]] virtual Void::Result::Result<
std::optional<std::vector<std::byte>>>
read() = 0;
[[nodiscard]] virtual Void::Result::Result<void>
write(std::span<const std::byte> bytes) = 0;
[[nodiscard]] virtual Void::Result::Result<void> clear() = 0;
};
/// Bounded in-memory journal used by tests and by hosts without durable
/// recovery (it never survives a process, so it is not recovery evidence).
class MemoryActivationStorage final : public ActivationStorage
{
public:
[[nodiscard]] Void::Result::Result<
std::optional<std::vector<std::byte>>>
read() override
{
if (!m_bytes) {
return std::optional<std::vector<std::byte>>{};
}
return std::optional<std::vector<std::byte>>{*m_bytes};
}
[[nodiscard]] Void::Result::Result<void>
write(std::span<const std::byte> bytes) override
{
if (m_fail_write) {
m_fail_write = false;
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::io,
"MemoryActivationStorage: injected write failure"}};
}
m_bytes = std::vector<std::byte>{bytes.begin(), bytes.end()};
if (m_lose_ack) {
m_lose_ack = false;
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::io,
"MemoryActivationStorage: lost acknowledgement"}};
}
return {};
}
[[nodiscard]] Void::Result::Result<void> clear() override
{
m_bytes.reset();
return {};
}
/// Test hook: simulate a torn/garbage durable record.
void corrupt(std::vector<std::byte> bytes)
{
m_bytes = std::move(bytes);
}
/// Test hook: fail the next write without touching the record.
void fail_next_write(bool fail) noexcept { m_fail_write = fail; }
/// Test hook: make the next write return an error even though the
/// bytes were durably stored (lost acknowledgement).
void lose_next_acknowledgement(bool lose) noexcept
{
m_lose_ack = lose;
}
private:
std::optional<std::vector<std::byte>> m_bytes{};
bool m_fail_write{false};
bool m_lose_ack{false};
};
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_activation(const ActivationRecord& record,
ActivationLimits limits = {});
[[nodiscard]] Void::Result::Result<ActivationRecord>
decode_activation(std::span<const std::byte> bytes,
ActivationLimits limits = {});
enum class RecoveryAction : std::uint8_t {
/// No journal: first bootstrap.
None,
/// Uncommitted activation or explicit rollback: restore the previous
/// healthy release.
UsePrevious,
/// The healthy marker is durable: keep the candidate.
UseCandidate,
/// Corrupt or unknown journal: start not-ready and never invent a
/// release.
Diagnostic
};
struct RecoveryDecision {
RecoveryAction action{RecoveryAction::None};
ActivationRecord record{};
/// True when the healthy marker is durable but post-commit
/// cleanup did not finish.
bool cleanup_pending{false};
std::string diagnostic;
};
enum class CommitOutcome : std::uint8_t {
Committed,
/// The durable acknowledgement was lost. The caller must reconcile;
/// it must never assume a rollback.
Unknown,
/// The transaction is not the active uncommitted activation.
Rejected
};
/// One authoritative activation journal.
///
/// Exactly one record is live. The phase transitions are:
/// None -> Activated -> HealthyCommitted (commit marker, irreversible)
/// -> RolledBack (explicit pre-commit rollback)
/// Committed/rolled-back records are cleared only by `cleanup()`.
class ActivationJournal
{
public:
explicit ActivationJournal(ActivationStorage& storage,
ActivationLimits limits = {});
/// Durably record a new reversible activation. Requires an empty
/// journal (or a cleared one) so two transactions cannot disagree.
[[nodiscard]] Void::Result::Result<void>
activate(ActivationRecord record);
/// Durably record the healthy commit marker. A failed write is
/// resolved by re-reading: if the marker is durable the outcome is
/// Committed, otherwise Unknown.
[[nodiscard]] CommitOutcome
commit_healthy(std::uint64_t transaction_id) noexcept;
/// Durably record an explicit rollback of the uncommitted
/// activation. Rejected after the healthy marker.
[[nodiscard]] Void::Result::Result<void>
rollback(std::uint64_t transaction_id);
/// Remove a committed or rolled-back record after reclaim. Never
/// removes an uncommitted activation.
[[nodiscard]] Void::Result::Result<void> cleanup();
/// Read and classify the durable journal on startup.
[[nodiscard]] RecoveryDecision reconcile();
[[nodiscard]] Void::Result::Result<std::optional<ActivationRecord>>
current();
private:
[[nodiscard]] Void::Result::Result<std::optional<ActivationRecord>>
load();
ActivationStorage& m_storage;
ActivationLimits m_limits;
};
/// Reversible read-only health window after publication.
///
/// During the window snapshot-safe reads are admitted and mutations get a
/// retryable not-ready result; writes reopen only after the healthy marker
/// is durable. A failed observation rolls back immediately.
class HealthWindow
{
public:
enum class Decision : std::uint8_t {
Pending,
Commit,
Rollback
};
explicit HealthWindow(
std::chrono::milliseconds duration =
std::chrono::milliseconds{10000}) noexcept;
[[nodiscard]] bool admit_read() const noexcept { return m_open; }
[[nodiscard]] Void::Result::Result<void> admit_write() const;
/// Record one readiness observation. Any unhealthy observation
/// closes the window for mutation.
void observe(bool healthy) noexcept;
/// Commit once the window elapsed with no failure, roll back on a
/// failed observation, otherwise keep waiting.
[[nodiscard]] Decision evaluate(
std::chrono::steady_clock::time_point now) const noexcept;
/// Close the window after the decision was applied.
void finish() noexcept { m_open = false; }
[[nodiscard]] bool open() const noexcept { return m_open; }
[[nodiscard]] bool failed() const noexcept { return m_failed; }
private:
std::chrono::steady_clock::time_point m_deadline;
bool m_open{true};
bool m_failed{false};
};
} // namespace ReloadableHost
@@ -0,0 +1,40 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace ReloadableHost
{
inline constexpr std::uint32_t kCurrentCheckpointVersion{3};
/// Durable workflow state carried across releases.
struct CheckpointState {
std::uint64_t counter{0};
std::string workflow;
std::uint64_t generation{0};
};
struct CheckpointLimits {
std::size_t max_bytes{64ULL * 1024ULL};
std::size_t max_workflow_bytes{4ULL * 1024ULL};
};
/// Encode the current checkpoint schema (bounded).
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_checkpoint(const CheckpointState& state,
CheckpointLimits limits = {});
/// Decode a supported checkpoint and migrate it to the current schema.
///
/// v1 (counter) and v2 (counter + workflow) are migrated forward with
/// defaults for fields they did not have. Corrupt magic, truncation,
/// oversized payloads and unknown newer versions are rejected.
[[nodiscard]] Void::Result::Result<CheckpointState>
decode_checkpoint(std::span<const std::byte> bytes,
CheckpointLimits limits = {});
} // namespace ReloadableHost
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>
namespace ReloadableHost
{
enum class ControlStatus : std::uint16_t {
Ok = 0,
Unauthenticated = 1,
InvalidArgument = 2,
NotFound = 3,
FailedPrecondition = 4,
Overloaded = 5,
Timeout = 6,
Internal = 7,
Unimplemented = 8
};
struct ControlRequest {
std::string command;
std::string candidate;
std::string token;
std::chrono::milliseconds deadline{0};
std::string payload;
};
struct ControlReply {
ControlStatus status{ControlStatus::Ok};
std::string body;
std::uint64_t transaction_id{0};
};
struct ControlLimits {
std::size_t max_request_bytes{64ULL * 1024ULL};
std::size_t max_reply_bytes{64ULL * 1024ULL};
};
/// Host operations exposed over the authenticated local control endpoint.
class ControlHandler
{
public:
ControlHandler() = default;
ControlHandler(const ControlHandler&) = delete;
ControlHandler& operator=(const ControlHandler&) = delete;
virtual ~ControlHandler() = default;
[[nodiscard]] virtual Void::Result::Result<std::string> inspect() = 0;
[[nodiscard]] virtual Void::Result::Result<bool> health() const = 0;
[[nodiscard]] virtual Void::Result::Result<void>
validate_candidate(std::string_view candidate) = 0;
[[nodiscard]] virtual Void::Result::Result<std::uint64_t>
reload(std::string_view candidate,
std::chrono::milliseconds deadline) = 0;
[[nodiscard]] virtual Void::Result::Result<void>
drain(std::chrono::milliseconds deadline) = 0;
[[nodiscard]] virtual Void::Result::Result<void> shutdown() = 0;
[[nodiscard]] virtual Void::Result::Result<void> recover() = 0;
};
/// Authenticated, bounded control dispatcher.
///
/// The transport (local IPC) owns framing; this validates the token in
/// constant time, enforces request/reply bounds, and maps host errors to
/// stable statuses. An empty configured token authorizes nothing.
class ControlEndpoint
{
public:
ControlEndpoint(std::string token, ControlHandler& handler,
ControlLimits limits = {});
[[nodiscard]] ControlReply handle(const ControlRequest& request);
private:
[[nodiscard]] bool authorized(std::string_view token) const noexcept;
[[nodiscard]] ControlReply dispatch(const ControlRequest& request);
std::string m_token;
ControlHandler& m_handler;
ControlLimits m_limits;
};
} // namespace ReloadableHost
@@ -0,0 +1,38 @@
#pragma once
#include "reloadable_host/supervisor.hpp"
#include <Void/System/Process.hpp>
#include <optional>
namespace ReloadableHost
{
/// Real out-of-process provider port over Void::Process.
///
/// Commands run through `/bin/sh -c` with inherited stdio (no unconsumed
/// pipes), so a noisy worker cannot fill an unread pipe and block.
class PosixWorkerPort final : public WorkerProcessPort
{
public:
PosixWorkerPort() = default;
PosixWorkerPort(const PosixWorkerPort&) = delete;
PosixWorkerPort& operator=(const PosixWorkerPort&) = delete;
~PosixWorkerPort() override;
[[nodiscard]] Void::Result::Result<void>
spawn(const std::string& command) override;
[[nodiscard]] Void::Result::Result<std::optional<WorkerExit>>
try_wait() override;
void terminate(std::chrono::milliseconds grace) noexcept override;
[[nodiscard]] bool running() const noexcept override;
private:
std::optional<Void::Process::Child> m_child{};
};
} // namespace ReloadableHost
@@ -0,0 +1,71 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <vector>
namespace ReloadableHost
{
struct ReleaseDescriptor {
std::string id;
std::string path;
std::uint64_t generation{0};
};
/// Host-supplied trust/checksum validation for a candidate release.
using ReleaseValidator =
std::function<Void::Result::Result<void>(const ReleaseDescriptor&)>;
struct ReleaseLimits {
/// Maximum unpinned-reclaimable older generations retained.
std::size_t max_retained_generations{2};
};
/// Immutable pinned release handle. Holding it keeps its generation alive
/// across reloads, exactly like an old read handle in the reference host.
using ReleaseHandle = std::shared_ptr<const ReleaseDescriptor>;
/// Immutable release generations with pin-based retention.
///
/// Publishing never invalidates an acquired handle. Older generations are
/// retired only after every pin is released, so the retained set stays
/// bounded by the pin count and the configured cap.
class ReleaseRegistry
{
public:
explicit ReleaseRegistry(ReleaseLimits limits = {});
/// Validate and publish a candidate. Returns its generation.
[[nodiscard]] Void::Result::Result<std::uint64_t>
publish(ReleaseDescriptor candidate,
const ReleaseValidator& validate);
/// Pin the current generation. Empty when nothing is published.
[[nodiscard]] ReleaseHandle acquire() const;
[[nodiscard]] std::optional<ReleaseDescriptor> current() const;
/// Retire older generations with no outstanding pins.
std::size_t collect() noexcept;
[[nodiscard]] std::size_t retained() const noexcept;
private:
std::size_t collect_locked() noexcept;
mutable std::mutex m_mutex;
ReleaseLimits m_limits;
std::uint64_t m_next_generation{1};
ReleaseHandle m_current;
std::vector<ReleaseHandle> m_retained;
};
} // namespace ReloadableHost
@@ -0,0 +1,135 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <mutex>
#include <optional>
#include <string>
namespace ReloadableHost
{
using TransactionId = std::uint64_t;
enum class ReloadPhase : std::uint8_t {
Idle,
Validating,
Preparing,
Draining,
Publishing,
Committing,
Completed,
RolledBack,
Failed,
CancelledBeforePublish,
UnknownOutcome
};
enum class ReloadOutcome : std::uint8_t {
None,
Published,
RolledBack,
Failed,
UnknownOutcome
};
struct ReloadReport {
TransactionId id{0};
ReloadPhase phase{ReloadPhase::Idle};
ReloadOutcome outcome{ReloadOutcome::None};
std::string candidate;
std::string error;
};
/// Immutable candidate release identifier and payload location.
struct ReleaseCandidate {
std::string id;
std::string path;
std::uint64_t generation{0};
};
/// Host-supplied trust/checksum validation boundary.
using Validator =
std::function<Void::Result::Result<void>(const ReleaseCandidate&)>;
struct ReloadLimits {
std::chrono::milliseconds drain_deadline{std::chrono::seconds{30}};
std::size_t max_pins{1024};
};
/// Tracks in-flight application calls so a reload drains before publishing.
class Quiescence
{
public:
explicit Quiescence(ReloadLimits limits = {});
/// Admit a call. Fails while draining or at the pin cap.
[[nodiscard]] Void::Result::Result<void> admit();
void release() noexcept;
/// Stop admissions and wait until pins drain or the deadline
/// expires. Returns false on timeout (still draining).
[[nodiscard]] bool drain();
/// Resume admissions after a rollback.
void resume() noexcept;
[[nodiscard]] std::size_t pins() const noexcept;
[[nodiscard]] bool draining() const noexcept;
private:
mutable std::mutex m_mutex;
std::condition_variable m_cv;
ReloadLimits m_limits;
std::size_t m_pins{0};
bool m_draining{false};
};
/// One authoritative reload transaction.
///
/// Exactly one outcome wins. Publication is the point of no return:
/// cancellation before it rolls back, after it the outcome stays
/// published, and a lost durable acknowledgement is UnknownOutcome rather
/// than a false rollback.
class ReloadTransaction
{
public:
explicit ReloadTransaction(TransactionId id);
[[nodiscard]] Void::Result::Result<void>
prepare(const ReleaseCandidate& candidate,
const Validator& validate);
[[nodiscard]] Void::Result::Result<void>
drain(Quiescence& quiescence);
/// Publish the prepared candidate. Only valid after a successful
/// drain.
[[nodiscard]] Void::Result::Result<void> publish();
/// Record the durable healthy commit. `durable == false` models a
/// lost acknowledgement: the outcome is Unknown.
void commit(bool durable) noexcept;
/// Cancel before publication. A no-op once published.
void cancel() noexcept;
[[nodiscard]] ReloadReport report() const;
private:
mutable std::mutex m_mutex;
TransactionId m_id;
ReloadPhase m_phase{ReloadPhase::Idle};
ReloadOutcome m_outcome{ReloadOutcome::None};
std::optional<ReleaseCandidate> m_candidate;
std::string m_error;
};
} // namespace ReloadableHost
@@ -0,0 +1,64 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <map>
#include <mutex>
namespace ReloadableHost
{
/// Aggregate retained-resource permits shared by candidate and retired
/// generations. These are host-owned budgets, not a total-process RSS
/// promise: mapped images, stacks and kernel buffers are accounted
/// separately by the platform.
struct ResourceLimits {
std::size_t max_total_bytes{256ULL * 1024ULL * 1024ULL};
std::size_t max_generation_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_generations{4};
};
struct ResourceUsage {
std::size_t total_bytes{0};
std::size_t generations{0};
};
/// Thread-safe byte/generation ledger.
///
/// `reserve` is admission: it rejects an over-budget generation with
/// `exhausted` before any publication happens. A generation stays reserved
/// until every pin on it is gone and the host releases it, so budget
/// saturation is observable and recoverable rather than silent eviction.
class ResourceLedger
{
public:
explicit ResourceLedger(ResourceLimits limits = {});
[[nodiscard]] Void::Result::Result<void>
reserve(std::uint64_t generation, std::size_t bytes);
/// Release one reserved generation. False when it was not held.
bool release(std::uint64_t generation) noexcept;
[[nodiscard]] bool holds(std::uint64_t generation) const noexcept;
[[nodiscard]] ResourceUsage usage() const noexcept;
/// High-water mark, for retained-resource and RSS reporting.
[[nodiscard]] ResourceUsage peak_usage() const noexcept;
[[nodiscard]] const ResourceLimits& limits() const noexcept
{
return m_limits;
}
private:
mutable std::mutex m_mutex;
ResourceLimits m_limits;
std::map<std::uint64_t, std::size_t> m_reserved;
std::size_t m_total_bytes{0};
ResourceUsage m_peak{};
};
} // namespace ReloadableHost
@@ -0,0 +1,121 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
namespace ReloadableHost
{
enum class WorkerState : std::uint8_t {
Stopped,
Running,
Restarting,
Failed
};
/// Effects already handed to a crashed worker cannot be proven absent.
enum class EffectState : std::uint8_t {
None,
InProgress,
/// The worker died (or was terminated) with an effect in progress.
/// The host must reconcile with the provider; it must never assume
/// the effect was rolled back.
Unknown,
Completed
};
struct RestartPolicy {
std::uint32_t max_restarts{3};
std::chrono::milliseconds base_backoff{50};
std::chrono::milliseconds max_backoff{1000};
};
struct WorkerExit {
bool exited{false};
int code{-1};
int signal{0};
[[nodiscard]] bool clean() const noexcept
{
return exited && code == 0 && signal == 0;
}
};
struct SupervisorReport {
WorkerState state{WorkerState::Stopped};
EffectState effects{EffectState::None};
std::uint32_t restarts{0};
/// Advisory delay before the next restart attempt; the caller
/// owns the clock so supervision stays deterministic.
std::chrono::milliseconds next_backoff{0};
std::string last_error;
};
/// Spawn/observe/terminate boundary for one out-of-process provider.
/// Implementations own exactly one worker at a time.
class WorkerProcessPort
{
public:
WorkerProcessPort() = default;
WorkerProcessPort(const WorkerProcessPort&) = delete;
WorkerProcessPort& operator=(const WorkerProcessPort&) = delete;
virtual ~WorkerProcessPort() = default;
[[nodiscard]] virtual Void::Result::Result<void>
spawn(const std::string& command) = 0;
/// Non-blocking observation. Empty optional while still running.
[[nodiscard]] virtual Void::Result::Result<
std::optional<WorkerExit>>
try_wait() = 0;
virtual void terminate(std::chrono::milliseconds grace) noexcept = 0;
[[nodiscard]] virtual bool running() const noexcept = 0;
};
/// Supervises one out-of-process provider with an explicit restart policy.
///
/// Restarts are attempted only by the next `poll()` after a crash, so the
/// backoff is reported rather than slept. A crash with an in-progress
/// effect reports `EffectState::Unknown`: this composition makes no
/// exactly-once or distributed claim.
class WorkerSupervisor
{
public:
WorkerSupervisor(WorkerProcessPort& port, std::string command,
RestartPolicy policy = {});
[[nodiscard]] Void::Result::Result<void> start();
/// Mark one effect as handed to the worker, and its confirmed
/// completion.
void begin_effect() noexcept;
void complete_effect() noexcept;
/// Observe one exit (non-blocking) and apply the restart policy.
/// The next poll after a crash respawns the worker.
[[nodiscard]] Void::Result::Result<SupervisorReport> poll();
/// Terminate a running worker with a bounded grace. Never claims an
/// in-progress effect was rolled back.
void stop(std::chrono::milliseconds grace = std::chrono::milliseconds{
2000}) noexcept;
[[nodiscard]] SupervisorReport report() const;
private:
[[nodiscard]] std::chrono::milliseconds backoff_for(
std::uint32_t restarts) const noexcept;
WorkerProcessPort& m_port;
std::string m_command;
RestartPolicy m_policy;
SupervisorReport m_report{};
};
} // namespace ReloadableHost
+407
View File
@@ -0,0 +1,407 @@
#include "reloadable_host/activation.hpp"
#include <array>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
constexpr std::array<std::byte, 4> kMagic{
std::byte{'V'}, std::byte{'A'}, std::byte{'C'}, std::byte{'T'}};
constexpr std::uint32_t kVersion{1};
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
[[nodiscard]] Void::Result::Error corrupt(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
{
for (int shift = 24; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
std::size_t& pos, std::uint32_t& value) noexcept
{
if (pos + 4 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 4; ++i) {
value = (value << 8) |
std::to_integer<std::uint32_t>(in[pos + i]);
}
pos += 4;
return true;
}
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
std::size_t& pos, std::uint64_t& value) noexcept
{
if (pos + 8 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 8; ++i) {
value = (value << 8) |
std::to_integer<std::uint64_t>(in[pos + i]);
}
pos += 8;
return true;
}
void append_string(std::vector<std::byte>& out, std::string_view text)
{
append_u32(out, static_cast<std::uint32_t>(text.size()));
for (const char c : text) {
out.push_back(static_cast<std::byte>(
static_cast<unsigned char>(c)));
}
}
[[nodiscard]] bool read_string(std::span<const std::byte> in,
std::size_t& pos, std::string& out,
std::size_t max_bytes) noexcept
{
std::uint32_t length = 0;
if (!read_u32(in, pos, length) || length > max_bytes ||
pos + length > in.size()) {
return false;
}
out.clear();
out.reserve(length);
for (std::uint32_t i = 0; i < length; ++i) {
out.push_back(static_cast<char>(
std::to_integer<unsigned char>(in[pos + i])));
}
pos += length;
return true;
}
[[nodiscard]] std::uint64_t checksum(std::span<const std::byte> bytes)
{
std::uint64_t hash = 0xCBF29CE484222325ULL;
for (const std::byte byte : bytes) {
hash ^= std::to_integer<std::uint64_t>(byte);
hash *= 0x100000001B3ULL;
}
return hash;
}
[[nodiscard]] bool is_known_phase(ActivationPhase phase) noexcept
{
return phase == ActivationPhase::Activated ||
phase == ActivationPhase::HealthyCommitted ||
phase == ActivationPhase::RolledBack;
}
} // namespace
Void::Result::Result<std::vector<std::byte>>
encode_activation(const ActivationRecord& record, ActivationLimits limits)
{
if (record.previous_release.size() > limits.max_release_bytes ||
record.candidate_release.size() > limits.max_release_bytes) {
return std::unexpected{
invalid("Activation: release id exceeds the size limit")};
}
if (!is_known_phase(record.phase)) {
return std::unexpected{
invalid("Activation: cannot encode an unset phase")};
}
std::vector<std::byte> out;
out.insert(out.end(), kMagic.begin(), kMagic.end());
append_u32(out, kVersion);
append_u64(out, record.transaction_id);
append_u64(out, record.checkpoint_generation);
out.push_back(static_cast<std::byte>(record.phase));
append_string(out, record.previous_release);
append_string(out, record.candidate_release);
append_u64(out, checksum(out));
if (out.size() > limits.max_record_bytes) {
return std::unexpected{
invalid("Activation: record exceeds max_record_bytes")};
}
return out;
}
Void::Result::Result<ActivationRecord>
decode_activation(std::span<const std::byte> bytes,
ActivationLimits limits)
{
if (bytes.size() > limits.max_record_bytes ||
bytes.size() < kMagic.size() + 4 + 8 + 8 + 1 + 4 + 4 + 8) {
return std::unexpected{corrupt("Activation: record is truncated")};
}
if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
return std::unexpected{corrupt("Activation: bad magic")};
}
const std::size_t payload = bytes.size() - 8;
std::uint64_t stored_checksum = 0;
{
std::size_t pos = payload;
if (!read_u64(bytes, pos, stored_checksum)) {
return std::unexpected{
corrupt("Activation: missing checksum")};
}
}
if (checksum(bytes.first(payload)) != stored_checksum) {
return std::unexpected{
corrupt("Activation: checksum mismatch")};
}
std::size_t pos = kMagic.size();
std::uint32_t version = 0;
if (!read_u32(bytes, pos, version) || version != kVersion) {
return std::unexpected{
corrupt("Activation: unsupported record version")};
}
ActivationRecord record;
if (!read_u64(bytes, pos, record.transaction_id) ||
!read_u64(bytes, pos, record.checkpoint_generation) ||
pos >= payload) {
return std::unexpected{corrupt("Activation: malformed record")};
}
record.phase = static_cast<ActivationPhase>(
std::to_integer<unsigned char>(bytes[pos++]));
if (!is_known_phase(record.phase)) {
return std::unexpected{corrupt("Activation: unknown phase")};
}
if (!read_string(bytes, pos, record.previous_release,
limits.max_release_bytes) ||
!read_string(bytes, pos, record.candidate_release,
limits.max_release_bytes) ||
pos != payload) {
return std::unexpected{corrupt("Activation: malformed record")};
}
return record;
}
ActivationJournal::ActivationJournal(ActivationStorage& storage,
ActivationLimits limits)
: m_storage(storage), m_limits(limits)
{
}
Void::Result::Result<std::optional<ActivationRecord>>
ActivationJournal::load()
{
auto bytes = m_storage.read();
if (!bytes) {
return std::unexpected{std::move(bytes).error()};
}
if (!bytes->has_value()) {
return std::optional<ActivationRecord>{};
}
auto decoded = decode_activation(**bytes, m_limits);
if (!decoded) {
return std::unexpected{std::move(decoded).error()};
}
return std::optional<ActivationRecord>{std::move(*decoded)};
}
Void::Result::Result<void>
ActivationJournal::activate(ActivationRecord record)
{
record.phase = ActivationPhase::Activated;
auto existing = load();
if (!existing) {
return std::unexpected{std::move(existing).error()};
}
if (existing->has_value()) {
return std::unexpected{conflict(
"Activation: journal already holds a record; cleanup first")};
}
auto encoded = encode_activation(record, m_limits);
if (!encoded) {
return std::unexpected{std::move(encoded).error()};
}
if (auto written = m_storage.write(*encoded); !written) {
// The write may still have landed durably; make the caller decide
// from the journal rather than assuming nothing happened.
return std::unexpected{std::move(written).error()};
}
return {};
}
CommitOutcome
ActivationJournal::commit_healthy(std::uint64_t transaction_id) noexcept
{
auto existing = load();
if (!existing || !existing->has_value() ||
(*existing)->transaction_id != transaction_id) {
return CommitOutcome::Rejected;
}
ActivationRecord record = **existing;
if (record.phase == ActivationPhase::HealthyCommitted) {
return CommitOutcome::Committed;
}
if (record.phase != ActivationPhase::Activated) {
return CommitOutcome::Rejected;
}
record.phase = ActivationPhase::HealthyCommitted;
auto encoded = encode_activation(record, m_limits);
if (!encoded) {
return CommitOutcome::Unknown;
}
if (auto written = m_storage.write(*encoded); written) {
return CommitOutcome::Committed;
}
// Lost acknowledgement: re-read the durable record. The marker being
// present means committed; its absence is Unknown, never a rollback.
auto reread = load();
if (reread && reread->has_value() &&
(*reread)->phase == ActivationPhase::HealthyCommitted &&
(*reread)->transaction_id == transaction_id) {
return CommitOutcome::Committed;
}
return CommitOutcome::Unknown;
}
Void::Result::Result<void>
ActivationJournal::rollback(std::uint64_t transaction_id)
{
auto existing = load();
if (!existing) {
return std::unexpected{std::move(existing).error()};
}
if (!existing->has_value()) {
return std::unexpected{
conflict("Activation: no activation to roll back")};
}
ActivationRecord record = **existing;
if (record.transaction_id != transaction_id) {
return std::unexpected{
conflict("Activation: transaction is not the active one")};
}
if (record.phase == ActivationPhase::HealthyCommitted) {
return std::unexpected{conflict(
"Activation: healthy marker is durable; rollback is not the "
"recovery action")};
}
if (record.phase == ActivationPhase::RolledBack) {
return {};
}
record.phase = ActivationPhase::RolledBack;
auto encoded = encode_activation(record, m_limits);
if (!encoded) {
return std::unexpected{std::move(encoded).error()};
}
return m_storage.write(*encoded);
}
Void::Result::Result<void> ActivationJournal::cleanup()
{
auto existing = load();
if (!existing) {
return std::unexpected{std::move(existing).error()};
}
if (existing->has_value() &&
(*existing)->phase == ActivationPhase::Activated) {
return std::unexpected{conflict(
"Activation: cannot clean up an uncommitted activation")};
}
return m_storage.clear();
}
RecoveryDecision ActivationJournal::reconcile()
{
RecoveryDecision decision;
auto existing = load();
if (!existing) {
decision.action = RecoveryAction::Diagnostic;
decision.diagnostic = existing.error().message();
return decision;
}
if (!existing->has_value()) {
decision.action = RecoveryAction::None;
return decision;
}
decision.record = **existing;
switch (decision.record.phase) {
case ActivationPhase::Activated:
// Crash before the healthy marker: the activation is
// reversible, so the prior healthy release wins.
decision.action = RecoveryAction::UsePrevious;
break;
case ActivationPhase::HealthyCommitted:
// Committed even if reclaim never ran.
decision.action = RecoveryAction::UseCandidate;
decision.cleanup_pending = true;
break;
case ActivationPhase::RolledBack:
decision.action = RecoveryAction::UsePrevious;
break;
case ActivationPhase::None:
decision.action = RecoveryAction::Diagnostic;
decision.diagnostic = "Activation: unset phase";
break;
}
return decision;
}
Void::Result::Result<std::optional<ActivationRecord>>
ActivationJournal::current()
{
return load();
}
HealthWindow::HealthWindow(std::chrono::milliseconds duration) noexcept
: m_deadline(std::chrono::steady_clock::now() + duration)
{
}
Void::Result::Result<void> HealthWindow::admit_write() const
{
if (!m_open) {
return {};
}
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::overloaded,
"HealthWindow: mutations are closed during the read-only health "
"window"}};
}
void HealthWindow::observe(bool healthy) noexcept
{
if (!healthy) {
m_failed = true;
}
}
HealthWindow::Decision HealthWindow::evaluate(
std::chrono::steady_clock::time_point now) const noexcept
{
if (!m_open) {
return Decision::Pending;
}
if (m_failed) {
return Decision::Rollback;
}
return now >= m_deadline ? Decision::Commit : Decision::Pending;
}
} // namespace ReloadableHost
+143
View File
@@ -0,0 +1,143 @@
#include "reloadable_host/checkpoint.hpp"
#include <algorithm>
#include <array>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
constexpr std::array<std::byte, 4> kMagic{
std::byte{'V'}, std::byte{'C'}, std::byte{'H'}, std::byte{'K'}};
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
std::move(message)};
}
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
{
for (int shift = 24; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
std::size_t& pos,
std::uint32_t& value) noexcept
{
if (pos + 4 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 4; ++i) {
value = (value << 8) |
std::to_integer<std::uint32_t>(in[pos + i]);
}
pos += 4;
return true;
}
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
std::size_t& pos,
std::uint64_t& value) noexcept
{
if (pos + 8 > in.size()) {
return false;
}
value = 0;
for (int i = 0; i < 8; ++i) {
value = (value << 8) |
std::to_integer<std::uint64_t>(in[pos + i]);
}
pos += 8;
return true;
}
} // namespace
Void::Result::Result<std::vector<std::byte>>
encode_checkpoint(const CheckpointState& state, CheckpointLimits limits)
{
if (state.workflow.size() > limits.max_workflow_bytes ||
state.workflow.size() > 0xFFFFFFFFULL) {
return std::unexpected{
invalid("Checkpoint: workflow exceeds the size limit")};
}
std::vector<std::byte> out;
out.reserve(4 + 4 + 8 + 4 + state.workflow.size() + 8);
out.insert(out.end(), kMagic.begin(), kMagic.end());
append_u32(out, kCurrentCheckpointVersion);
append_u64(out, state.counter);
append_u32(out, static_cast<std::uint32_t>(state.workflow.size()));
for (const char ch : state.workflow) {
out.push_back(static_cast<std::byte>(ch));
}
append_u64(out, state.generation);
if (out.size() > limits.max_bytes) {
return std::unexpected{
invalid("Checkpoint: encoded state exceeds the size limit")};
}
return out;
}
Void::Result::Result<CheckpointState>
decode_checkpoint(std::span<const std::byte> bytes,
CheckpointLimits limits)
{
if (bytes.size() > limits.max_bytes ||
bytes.size() < kMagic.size() + 4 + 8) {
return std::unexpected{
invalid("Checkpoint: truncated or oversized payload")};
}
if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
return std::unexpected{invalid("Checkpoint: bad magic")};
}
std::size_t pos = kMagic.size();
std::uint32_t version = 0;
if (!read_u32(bytes, pos, version)) {
return std::unexpected{invalid("Checkpoint: truncated version")};
}
if (version == 0 || version > kCurrentCheckpointVersion) {
return std::unexpected{invalid(
"Checkpoint: unsupported schema version")};
}
CheckpointState state;
if (!read_u64(bytes, pos, state.counter)) {
return std::unexpected{invalid("Checkpoint: truncated counter")};
}
if (version >= 2) {
std::uint32_t workflow_size = 0;
if (!read_u32(bytes, pos, workflow_size) ||
workflow_size > limits.max_workflow_bytes ||
pos + workflow_size > bytes.size()) {
return std::unexpected{
invalid("Checkpoint: invalid workflow payload")};
}
state.workflow.assign(
reinterpret_cast<const char*>(bytes.data() + pos),
workflow_size);
pos += workflow_size;
}
if (version >= 3 && !read_u64(bytes, pos, state.generation)) {
return std::unexpected{
invalid("Checkpoint: truncated generation")};
}
if (pos != bytes.size()) {
return std::unexpected{
invalid("Checkpoint: trailing bytes after payload")};
}
return state;
}
} // namespace ReloadableHost
+158
View File
@@ -0,0 +1,158 @@
#include "reloadable_host/control.hpp"
#include <algorithm>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
[[nodiscard]] ControlStatus status_for(const Void::Result::Error& error) noexcept
{
using Kind = Void::Result::ErrorKind;
switch (error.kind()) {
case Kind::invalid_argument: return ControlStatus::InvalidArgument;
case Kind::not_found: return ControlStatus::NotFound;
case Kind::conflict: return ControlStatus::FailedPrecondition;
case Kind::exhausted:
case Kind::overloaded: return ControlStatus::Overloaded;
case Kind::timeout: return ControlStatus::Timeout;
case Kind::unsupported: return ControlStatus::Unimplemented;
default: return ControlStatus::Internal;
}
}
[[nodiscard]] bool constant_time_equal(std::string_view lhs,
std::string_view rhs) noexcept
{
if (lhs.size() != rhs.size()) {
return false;
}
unsigned int diff = 0;
for (std::size_t i = 0; i < lhs.size(); ++i) {
diff |= static_cast<unsigned int>(
static_cast<unsigned char>(lhs[i]) ^
static_cast<unsigned char>(rhs[i]));
}
return diff == 0;
}
void truncate(std::string& body, std::size_t limit)
{
if (body.size() > limit) {
body.resize(limit);
}
}
} // namespace
ControlEndpoint::ControlEndpoint(std::string token, ControlHandler& handler,
ControlLimits limits)
: m_token(std::move(token))
, m_handler(handler)
, m_limits(limits)
{
}
bool ControlEndpoint::authorized(std::string_view token) const noexcept
{
if (m_token.empty()) {
return false;
}
return constant_time_equal(token, m_token);
}
ControlReply ControlEndpoint::handle(const ControlRequest& request)
{
const std::size_t request_bytes = request.command.size() +
request.candidate.size() +
request.token.size() +
request.payload.size();
if (request_bytes > m_limits.max_request_bytes) {
return ControlReply{ControlStatus::InvalidArgument,
"control request exceeds the size limit"};
}
if (!authorized(request.token)) {
return ControlReply{ControlStatus::Unauthenticated,
"missing or invalid control token"};
}
ControlReply reply = dispatch(request);
truncate(reply.body, m_limits.max_reply_bytes);
return reply;
}
ControlReply ControlEndpoint::dispatch(const ControlRequest& request)
{
if (request.command == "inspect") {
auto inspected = m_handler.inspect();
if (!inspected) {
return ControlReply{status_for(inspected.error()),
inspected.error().message()};
}
return ControlReply{ControlStatus::Ok, std::move(*inspected)};
}
if (request.command == "health") {
auto healthy = m_handler.health();
if (!healthy) {
return ControlReply{status_for(healthy.error()),
healthy.error().message()};
}
return ControlReply{ControlStatus::Ok,
*healthy ? "ready" : "not ready"};
}
if (request.command == "validate-candidate") {
if (request.candidate.empty()) {
return ControlReply{ControlStatus::InvalidArgument,
"candidate release id required"};
}
auto validated =
m_handler.validate_candidate(request.candidate);
if (!validated) {
return ControlReply{status_for(validated.error()),
validated.error().message()};
}
return ControlReply{ControlStatus::Ok, "candidate valid"};
}
if (request.command == "reload") {
if (request.candidate.empty()) {
return ControlReply{ControlStatus::InvalidArgument,
"candidate release id required"};
}
auto reloaded =
m_handler.reload(request.candidate, request.deadline);
if (!reloaded) {
return ControlReply{status_for(reloaded.error()),
reloaded.error().message()};
}
ControlReply reply{ControlStatus::Ok, "reload accepted"};
reply.transaction_id = *reloaded;
return reply;
}
if (request.command == "drain") {
auto drained = m_handler.drain(request.deadline);
if (!drained) {
return ControlReply{status_for(drained.error()),
drained.error().message()};
}
return ControlReply{ControlStatus::Ok, "drained"};
}
if (request.command == "shutdown") {
auto stopped = m_handler.shutdown();
if (!stopped) {
return ControlReply{status_for(stopped.error()),
stopped.error().message()};
}
return ControlReply{ControlStatus::Ok, "shutting down"};
}
if (request.command == "recover") {
auto recovered = m_handler.recover();
if (!recovered) {
return ControlReply{status_for(recovered.error()),
recovered.error().message()};
}
return ControlReply{ControlStatus::Ok, "recovered"};
}
return ControlReply{ControlStatus::InvalidArgument,
"unknown control command"};
}
} // namespace ReloadableHost
@@ -0,0 +1,75 @@
#include "reloadable_host/posix_worker.hpp"
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
[[nodiscard]] Void::Result::Error state_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
} // namespace
PosixWorkerPort::~PosixWorkerPort()
{
if (m_child && m_child->valid()) {
(void)m_child->terminate(std::chrono::milliseconds{2000});
}
}
Void::Result::Result<void>
PosixWorkerPort::spawn(const std::string& command)
{
if (m_child && m_child->valid() && m_child->running()) {
return std::unexpected{
state_error("PosixWorkerPort: a worker is already running")};
}
m_child.reset();
Void::Process::SpawnOptions options;
options.executable = "/bin/sh";
options.arguments = {"-c", command};
options.stdin_pipe = false;
options.stdout_pipe = false;
options.stderr_pipe = false;
auto child = Void::Process::spawn(options);
if (!child) {
return std::unexpected{std::move(child).error()};
}
m_child.emplace(std::move(*child));
return {};
}
Void::Result::Result<std::optional<WorkerExit>> PosixWorkerPort::try_wait()
{
if (!m_child) {
return std::optional<WorkerExit>{};
}
auto status = m_child->try_wait();
if (!status) {
return std::unexpected{std::move(status).error()};
}
if (!status->has_value()) {
return std::optional<WorkerExit>{};
}
const auto& exit = **status;
return std::optional<WorkerExit>{WorkerExit{
.exited = exit.exited, .code = exit.code, .signal = exit.signal}};
}
void PosixWorkerPort::terminate(std::chrono::milliseconds grace) noexcept
{
if (m_child && m_child->valid()) {
(void)m_child->terminate(grace);
}
}
bool PosixWorkerPort::running() const noexcept
{
return m_child && m_child->running();
}
} // namespace ReloadableHost
@@ -0,0 +1,117 @@
#include "reloadable_host/release_registry.hpp"
#include <algorithm>
#include <exception>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
[[nodiscard]] Void::Result::Error state_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] Void::Result::Error limit_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
std::move(message)};
}
[[nodiscard]] Void::Result::Error invalid_release(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
} // namespace
ReleaseRegistry::ReleaseRegistry(ReleaseLimits limits)
: m_limits(limits)
{
}
Void::Result::Result<std::uint64_t>
ReleaseRegistry::publish(ReleaseDescriptor candidate,
const ReleaseValidator& validate)
{
if (candidate.id.empty()) {
return std::unexpected{
invalid_release("ReleaseRegistry: release id must not be empty")};
}
Void::Result::Result<void> validated;
try {
validated =
validate ? validate(candidate) : Void::Result::Result<void>{};
} catch (const std::exception& error) {
validated = std::unexpected{invalid_release(
std::string{"validator threw: "} + error.what())};
} catch (...) {
validated = std::unexpected{
invalid_release("validator threw an unknown exception")};
}
if (!validated) {
return std::unexpected{validated.error()};
}
std::lock_guard lock{m_mutex};
if (m_current && m_current->id == candidate.id) {
return std::unexpected{state_error(
"ReleaseRegistry: release id is already published")};
}
(void)collect_locked();
if (m_retained.size() >= m_limits.max_retained_generations) {
return std::unexpected{limit_error(
"ReleaseRegistry: retained generation cap reached; release "
"pins before reloading")};
}
candidate.generation = m_next_generation++;
auto published =
std::make_shared<const ReleaseDescriptor>(std::move(candidate));
if (m_current) {
m_retained.push_back(std::move(m_current));
}
m_current = std::move(published);
return m_current->generation;
}
ReleaseHandle ReleaseRegistry::acquire() const
{
std::lock_guard lock{m_mutex};
return m_current;
}
std::optional<ReleaseDescriptor> ReleaseRegistry::current() const
{
std::lock_guard lock{m_mutex};
if (!m_current) {
return std::nullopt;
}
return *m_current;
}
std::size_t ReleaseRegistry::collect_locked() noexcept
{
const auto before = m_retained.size();
std::erase_if(m_retained, [](const ReleaseHandle& handle) {
return handle.use_count() == 1;
});
return before - m_retained.size();
}
std::size_t ReleaseRegistry::collect() noexcept
{
std::lock_guard lock{m_mutex};
return collect_locked();
}
std::size_t ReleaseRegistry::retained() const noexcept
{
std::lock_guard lock{m_mutex};
return m_retained.size();
}
} // namespace ReloadableHost
@@ -0,0 +1,218 @@
#include "reloadable_host/reload_transaction.hpp"
#include <exception>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
[[nodiscard]] Void::Result::Error state_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
[[nodiscard]] Void::Result::Error limit_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
std::move(message)};
}
[[nodiscard]] Void::Result::Error invalid_candidate(
std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
} // namespace
Quiescence::Quiescence(ReloadLimits limits)
: m_limits(limits)
{
}
Void::Result::Result<void> Quiescence::admit()
{
std::lock_guard lock{m_mutex};
if (m_draining) {
return std::unexpected{
state_error("Quiescence: admissions are closed while draining")};
}
if (m_pins >= m_limits.max_pins) {
return std::unexpected{
limit_error("Quiescence: pin cap reached")};
}
++m_pins;
return {};
}
void Quiescence::release() noexcept
{
{
std::lock_guard lock{m_mutex};
if (m_pins > 0) {
--m_pins;
}
}
m_cv.notify_all();
}
bool Quiescence::drain()
{
std::unique_lock lock{m_mutex};
m_draining = true;
return m_cv.wait_for(lock, m_limits.drain_deadline,
[this] { return m_pins == 0; });
}
void Quiescence::resume() noexcept
{
{
std::lock_guard lock{m_mutex};
m_draining = false;
}
m_cv.notify_all();
}
std::size_t Quiescence::pins() const noexcept
{
std::lock_guard lock{m_mutex};
return m_pins;
}
bool Quiescence::draining() const noexcept
{
std::lock_guard lock{m_mutex};
return m_draining;
}
ReloadTransaction::ReloadTransaction(TransactionId id)
: m_id(id)
{
}
Void::Result::Result<void>
ReloadTransaction::prepare(const ReleaseCandidate& candidate,
const Validator& validate)
{
{
std::lock_guard lock{m_mutex};
if (m_phase != ReloadPhase::Idle) {
return std::unexpected{state_error(
"ReloadTransaction: prepare requires an idle transaction")};
}
m_phase = ReloadPhase::Validating;
m_candidate = candidate;
m_error.clear();
}
Void::Result::Result<void> validated;
try {
validated = validate ? validate(candidate) : Void::Result::Result<void>{};
} catch (const std::exception& error) {
validated = std::unexpected{
invalid_candidate(std::string{"validator threw: "} + error.what())};
} catch (...) {
validated = std::unexpected{
invalid_candidate("validator threw an unknown exception")};
}
std::lock_guard lock{m_mutex};
if (!validated) {
m_phase = ReloadPhase::Failed;
m_outcome = ReloadOutcome::Failed;
m_error = validated.error().message();
return std::unexpected{validated.error()};
}
m_phase = ReloadPhase::Preparing;
return {};
}
Void::Result::Result<void> ReloadTransaction::drain(Quiescence& quiescence)
{
{
std::lock_guard lock{m_mutex};
if (m_phase != ReloadPhase::Preparing) {
return std::unexpected{state_error(
"ReloadTransaction: drain requires a prepared transaction")};
}
m_phase = ReloadPhase::Draining;
}
const bool quiesced = quiescence.drain();
std::lock_guard lock{m_mutex};
if (!quiesced) {
// Quiescence was not reached: the transaction must not be
// publishable. The old owner keeps its pins and the candidate fails
// safely instead of racing a second writer.
m_phase = ReloadPhase::Failed;
m_outcome = ReloadOutcome::Failed;
m_error = "drain deadline expired with pinned calls";
return std::unexpected{
Void::Result::Error{Void::Result::ErrorKind::timeout, m_error}};
}
return {};
}
Void::Result::Result<void> ReloadTransaction::publish()
{
std::lock_guard lock{m_mutex};
if (m_phase != ReloadPhase::Draining) {
return std::unexpected{state_error(
"ReloadTransaction: publish requires a drained transaction")};
}
// Point of no return: from here a cancel() cannot roll back.
m_phase = ReloadPhase::Committing;
return {};
}
void ReloadTransaction::commit(bool durable) noexcept
{
std::lock_guard lock{m_mutex};
if (m_phase != ReloadPhase::Committing) {
return;
}
if (durable) {
m_phase = ReloadPhase::Completed;
m_outcome = ReloadOutcome::Published;
return;
}
// The publication may be live but the durable acknowledgement was
// lost: never report a rollback.
m_phase = ReloadPhase::UnknownOutcome;
m_outcome = ReloadOutcome::UnknownOutcome;
m_error = "durable healthy record not acknowledged";
}
void ReloadTransaction::cancel() noexcept
{
std::lock_guard lock{m_mutex};
switch (m_phase) {
case ReloadPhase::Committing:
case ReloadPhase::Completed:
case ReloadPhase::UnknownOutcome:
return; // published: cannot undo
default:
break;
}
m_phase = ReloadPhase::CancelledBeforePublish;
m_outcome = ReloadOutcome::RolledBack;
}
ReloadReport ReloadTransaction::report() const
{
std::lock_guard lock{m_mutex};
ReloadReport report;
report.id = m_id;
report.phase = m_phase;
report.outcome = m_outcome;
if (m_candidate) {
report.candidate = m_candidate->id;
}
report.error = m_error;
return report;
}
} // namespace ReloadableHost
@@ -0,0 +1,87 @@
#include "reloadable_host/resources.hpp"
#include <algorithm>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
[[nodiscard]] Void::Result::Error exhausted(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
std::move(message)};
}
[[nodiscard]] Void::Result::Error conflict(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
} // namespace
ResourceLedger::ResourceLedger(ResourceLimits limits)
: m_limits(limits)
{
}
Void::Result::Result<void>
ResourceLedger::reserve(std::uint64_t generation, std::size_t bytes)
{
std::lock_guard lock{m_mutex};
if (m_reserved.contains(generation)) {
return std::unexpected{
conflict("ResourceLedger: generation is already reserved")};
}
if (bytes > m_limits.max_generation_bytes) {
return std::unexpected{exhausted(
"ResourceLedger: generation exceeds max_generation_bytes")};
}
if (m_reserved.size() >= m_limits.max_generations) {
return std::unexpected{exhausted(
"ResourceLedger: retained generation cap reached; release "
"pinned generations before reloading")};
}
if (bytes > m_limits.max_total_bytes - m_total_bytes) {
return std::unexpected{exhausted(
"ResourceLedger: aggregate retained budget reached")};
}
m_reserved.emplace(generation, bytes);
m_total_bytes += bytes;
m_peak.total_bytes = std::max(m_peak.total_bytes, m_total_bytes);
m_peak.generations =
std::max(m_peak.generations, m_reserved.size());
return {};
}
bool ResourceLedger::release(std::uint64_t generation) noexcept
{
std::lock_guard lock{m_mutex};
const auto found = m_reserved.find(generation);
if (found == m_reserved.end()) {
return false;
}
m_total_bytes -= found->second;
m_reserved.erase(found);
return true;
}
bool ResourceLedger::holds(std::uint64_t generation) const noexcept
{
std::lock_guard lock{m_mutex};
return m_reserved.contains(generation);
}
ResourceUsage ResourceLedger::usage() const noexcept
{
std::lock_guard lock{m_mutex};
return ResourceUsage{m_total_bytes, m_reserved.size()};
}
ResourceUsage ResourceLedger::peak_usage() const noexcept
{
std::lock_guard lock{m_mutex};
return m_peak;
}
} // namespace ReloadableHost
+148
View File
@@ -0,0 +1,148 @@
#include "reloadable_host/supervisor.hpp"
#include <algorithm>
#include <string>
#include <utility>
namespace ReloadableHost
{
namespace
{
[[nodiscard]] Void::Result::Error state_error(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::conflict,
std::move(message)};
}
} // namespace
WorkerSupervisor::WorkerSupervisor(WorkerProcessPort& port,
std::string command,
RestartPolicy policy)
: m_port(port), m_command(std::move(command)), m_policy(policy)
{
}
std::chrono::milliseconds
WorkerSupervisor::backoff_for(std::uint32_t restarts) const noexcept
{
if (restarts == 0) {
return std::chrono::milliseconds{0};
}
auto delay = m_policy.base_backoff;
for (std::uint32_t i = 1; i < restarts; ++i) {
if (delay >= m_policy.max_backoff) {
break;
}
delay *= 2;
}
return std::min(delay, m_policy.max_backoff);
}
Void::Result::Result<void> WorkerSupervisor::start()
{
if (m_report.state == WorkerState::Running) {
return std::unexpected{
state_error("WorkerSupervisor: already running")};
}
if (m_report.state == WorkerState::Failed) {
return std::unexpected{state_error(
"WorkerSupervisor: restart budget exhausted; recreate")};
}
if (auto spawned = m_port.spawn(m_command); !spawned) {
m_report.state = WorkerState::Failed;
m_report.last_error = spawned.error().message();
return spawned;
}
m_report.state = WorkerState::Running;
m_report.next_backoff = std::chrono::milliseconds{0};
return {};
}
void WorkerSupervisor::begin_effect() noexcept
{
if (m_report.effects != EffectState::Unknown) {
m_report.effects = EffectState::InProgress;
}
}
void WorkerSupervisor::complete_effect() noexcept
{
if (m_report.effects == EffectState::InProgress) {
m_report.effects = EffectState::Completed;
}
}
Void::Result::Result<SupervisorReport> WorkerSupervisor::poll()
{
if (m_report.state == WorkerState::Restarting) {
if (auto spawned = m_port.spawn(m_command); !spawned) {
m_report.state = WorkerState::Failed;
m_report.last_error = spawned.error().message();
return std::unexpected{std::move(spawned).error()};
}
m_report.state = WorkerState::Running;
m_report.next_backoff = std::chrono::milliseconds{0};
return m_report;
}
if (m_report.state != WorkerState::Running) {
return m_report;
}
auto observed = m_port.try_wait();
if (!observed) {
m_report.state = WorkerState::Failed;
m_report.last_error = observed.error().message();
return std::unexpected{std::move(observed).error()};
}
if (!observed->has_value()) {
return m_report; // still running
}
const WorkerExit exit = **observed;
if (exit.clean()) {
m_report.state = WorkerState::Stopped;
if (m_report.effects == EffectState::InProgress) {
// Clean exit is not proof the effect completed.
m_report.effects = EffectState::Unknown;
}
return m_report;
}
// Crash or signal: an in-progress effect has an unknown outcome.
if (m_report.effects == EffectState::InProgress) {
m_report.effects = EffectState::Unknown;
}
m_report.last_error =
exit.signal != 0
? "worker terminated by signal " + std::to_string(exit.signal)
: "worker exited with code " + std::to_string(exit.code);
if (m_report.restarts >= m_policy.max_restarts) {
m_report.state = WorkerState::Failed;
m_report.next_backoff = std::chrono::milliseconds{0};
return m_report;
}
++m_report.restarts;
m_report.state = WorkerState::Restarting;
m_report.next_backoff = backoff_for(m_report.restarts);
return m_report;
}
void WorkerSupervisor::stop(std::chrono::milliseconds grace) noexcept
{
if (m_port.running()) {
m_port.terminate(grace);
}
if (m_report.effects == EffectState::InProgress) {
// Termination may interrupt the effect: never report it as done.
m_report.effects = EffectState::Unknown;
}
m_report.state = WorkerState::Stopped;
m_report.next_backoff = std::chrono::milliseconds{0};
}
SupervisorReport WorkerSupervisor::report() const
{
return m_report;
}
} // namespace ReloadableHost
@@ -0,0 +1,184 @@
#include "reloadable_host/activation.hpp"
#include <cassert>
#include <chrono>
#include <cstdio>
#include <string>
#include <vector>
namespace
{
using namespace ReloadableHost;
ActivationRecord make_record(std::uint64_t id = 1)
{
ActivationRecord record;
record.transaction_id = id;
record.previous_release = "release-a";
record.candidate_release = "release-b";
record.checkpoint_generation = 7;
return record;
}
void encoding_roundtrip()
{
auto record = make_record();
record.phase = ActivationPhase::Activated;
auto encoded = encode_activation(record);
assert(encoded.has_value());
auto decoded = decode_activation(*encoded);
assert(decoded.has_value());
assert(decoded->transaction_id == record.transaction_id);
assert(decoded->previous_release == record.previous_release);
assert(decoded->candidate_release == record.candidate_release);
assert(decoded->checkpoint_generation == record.checkpoint_generation);
assert(decoded->phase == ActivationPhase::Activated);
}
void encoding_rejects_corruption_and_limits()
{
auto record = make_record();
record.phase = ActivationPhase::Activated;
auto encoded = encode_activation(record);
assert(encoded.has_value());
auto flipped = *encoded;
flipped[flipped.size() / 2] ^= std::byte{0xFF};
assert(!decode_activation(flipped).has_value());
auto truncated = std::vector<std::byte>{
encoded->begin(), encoded->begin() + 10};
assert(!decode_activation(truncated).has_value());
ActivationLimits tiny;
tiny.max_record_bytes = 8;
assert(!decode_activation(*encoded, tiny).has_value());
// An unset phase is not a valid durable record.
auto unset = make_record();
assert(!encode_activation(unset).has_value());
}
void activation_is_reversible_until_the_healthy_marker()
{
MemoryActivationStorage storage;
ActivationJournal journal{storage};
assert(journal.reconcile().action == RecoveryAction::None);
assert(journal.activate(make_record(11)).has_value());
// A second activation cannot overwrite the first.
assert(!journal.activate(make_record(12)).has_value());
const auto crashed = journal.reconcile();
assert(crashed.action == RecoveryAction::UsePrevious);
assert(crashed.record.previous_release == "release-a");
assert(crashed.record.candidate_release == "release-b");
assert(!crashed.cleanup_pending);
// Cleanup of an uncommitted activation is refused.
assert(!journal.cleanup().has_value());
assert(journal.rollback(11).has_value());
assert(journal.reconcile().action == RecoveryAction::UsePrevious);
assert(journal.cleanup().has_value());
assert(journal.reconcile().action == RecoveryAction::None);
}
void healthy_marker_is_the_commit_point()
{
MemoryActivationStorage storage;
ActivationJournal journal{storage};
assert(journal.activate(make_record(21)).has_value());
assert(journal.commit_healthy(21) == CommitOutcome::Committed);
const auto recovered = journal.reconcile();
assert(recovered.action == RecoveryAction::UseCandidate);
// Commit durable, reclaim not done yet: reported, not rolled back.
assert(recovered.cleanup_pending);
// Rolling back a committed activation is refused.
assert(!journal.rollback(21).has_value());
assert(journal.cleanup().has_value());
assert(journal.reconcile().action == RecoveryAction::None);
}
void commit_rejects_a_foreign_transaction()
{
MemoryActivationStorage storage;
ActivationJournal journal{storage};
assert(journal.activate(make_record(31)).has_value());
assert(journal.commit_healthy(99) == CommitOutcome::Rejected);
assert(journal.reconcile().action == RecoveryAction::UsePrevious);
}
void lost_acknowledgement_is_never_a_rollback()
{
MemoryActivationStorage storage;
ActivationJournal journal{storage};
assert(journal.activate(make_record(41)).has_value());
// The write lands durably but reports failure.
storage.lose_next_acknowledgement(true);
assert(journal.commit_healthy(41) == CommitOutcome::Committed);
assert(journal.reconcile().action == RecoveryAction::UseCandidate);
}
void failed_write_without_durable_marker_is_unknown()
{
MemoryActivationStorage storage;
ActivationJournal journal{storage};
assert(journal.activate(make_record(51)).has_value());
storage.fail_next_write(true);
assert(journal.commit_healthy(51) == CommitOutcome::Unknown);
// The durable record is still the uncommitted activation.
assert(journal.reconcile().action == RecoveryAction::UsePrevious);
}
void corrupt_journal_never_invents_a_release()
{
MemoryActivationStorage storage;
storage.corrupt({std::byte{1}, std::byte{2}, std::byte{3}});
ActivationJournal journal{storage};
const auto decision = journal.reconcile();
assert(decision.action == RecoveryAction::Diagnostic);
assert(!decision.diagnostic.empty());
}
void health_window_admits_reads_and_holds_writes()
{
HealthWindow window{std::chrono::milliseconds{50}};
assert(window.admit_read());
assert(!window.admit_write().has_value());
using Clock = std::chrono::steady_clock;
const auto now = Clock::now();
assert(window.evaluate(now) == HealthWindow::Decision::Pending);
assert(window.evaluate(now + std::chrono::milliseconds{100}) ==
HealthWindow::Decision::Commit);
window.observe(false);
assert(window.evaluate(now) == HealthWindow::Decision::Rollback);
window.finish();
assert(!window.open());
assert(!window.admit_read());
}
} // namespace
int main()
{
encoding_roundtrip();
encoding_rejects_corruption_and_limits();
activation_is_reversible_until_the_healthy_marker();
healthy_marker_is_the_commit_point();
commit_rejects_a_foreign_transaction();
lost_acknowledgement_is_never_a_rollback();
failed_write_without_durable_marker_is_unknown();
corrupt_journal_never_invents_a_release();
health_window_admits_reads_and_holds_writes();
std::puts("reloadable-host activation ok");
return 0;
}
@@ -0,0 +1,117 @@
#include "reloadable_host/checkpoint.hpp"
#include <cassert>
#include <cstdio>
#include <cstdint>
#include <string>
#include <string_view>
#include <vector>
namespace
{
using namespace ReloadableHost;
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
{
for (int shift = 24; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
{
for (int shift = 56; shift >= 0; shift -= 8) {
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
}
}
std::vector<std::byte> legacy(std::uint32_t version, std::uint64_t counter,
std::string_view workflow = {})
{
std::vector<std::byte> out{std::byte{'V'}, std::byte{'C'},
std::byte{'H'}, std::byte{'K'}};
append_u32(out, version);
append_u64(out, counter);
if (version >= 2) {
append_u32(out, static_cast<std::uint32_t>(workflow.size()));
for (const char ch : workflow) {
out.push_back(static_cast<std::byte>(ch));
}
}
return out;
}
void current_schema_round_trips()
{
const CheckpointState state{7, "workflow-a", 3};
auto encoded = encode_checkpoint(state);
assert(encoded.has_value());
auto decoded = decode_checkpoint(*encoded);
assert(decoded.has_value());
assert(decoded->counter == 7);
assert(decoded->workflow == "workflow-a");
assert(decoded->generation == 3);
}
void older_schemas_migrate_forward()
{
auto v1 = decode_checkpoint(legacy(1, 42));
assert(v1.has_value());
assert(v1->counter == 42);
assert(v1->workflow.empty());
assert(v1->generation == 0);
auto v2 = decode_checkpoint(legacy(2, 9, "wf"));
assert(v2.has_value());
assert(v2->counter == 9);
assert(v2->workflow == "wf");
assert(v2->generation == 0);
}
void malformed_payloads_are_rejected()
{
const CheckpointState state{1, "wf", 2};
auto encoded = encode_checkpoint(state);
assert(encoded.has_value());
// Unknown newer schema.
auto future = legacy(1, 5);
future[7] = std::byte{4}; // version field is bytes 4..7 (big-endian)
assert(!decode_checkpoint(future).has_value());
// Bad magic.
auto bad_magic = *encoded;
bad_magic[0] = std::byte{'X'};
assert(!decode_checkpoint(bad_magic).has_value());
// Truncated and trailing bytes.
auto truncated = *encoded;
truncated.pop_back();
assert(!decode_checkpoint(truncated).has_value());
auto trailing = *encoded;
trailing.push_back(std::byte{0});
assert(!decode_checkpoint(trailing).has_value());
}
void limits_are_enforced()
{
auto big = encode_checkpoint(CheckpointState{0, std::string(10, 'x'), 0});
assert(big.has_value());
assert(!decode_checkpoint(*big, CheckpointLimits{.max_workflow_bytes = 4})
.has_value());
assert(!encode_checkpoint(
CheckpointState{0, std::string(100, 'x'), 0},
CheckpointLimits{.max_workflow_bytes = 4})
.has_value());
}
} // namespace
int main()
{
current_schema_round_trips();
older_schemas_migrate_forward();
malformed_payloads_are_rejected();
limits_are_enforced();
std::puts("reloadable-host checkpoint ok");
return 0;
}
@@ -0,0 +1,166 @@
#include "reloadable_host/control.hpp"
#include <cassert>
#include <chrono>
#include <cstdio>
#include <string>
#include <utility>
namespace
{
using namespace ReloadableHost;
struct FakeHandler final : ControlHandler {
std::string inspected{
"generation=2 release=rel-b ready=1 pins=0 phase=Completed"};
bool ready{true};
int inspect_calls{0};
int reload_calls{0};
int drain_calls{0};
int shutdown_calls{0};
int validate_calls{0};
int recover_calls{0};
std::string last_candidate;
std::chrono::milliseconds last_deadline{0};
Void::Result::Result<void> drain_result{};
Void::Result::Result<std::string> inspect() override
{
++inspect_calls;
return inspected;
}
Void::Result::Result<bool> health() const override { return ready; }
Void::Result::Result<void>
validate_candidate(std::string_view candidate) override
{
++validate_calls;
last_candidate = std::string{candidate};
return {};
}
Void::Result::Result<std::uint64_t>
reload(std::string_view candidate,
std::chrono::milliseconds deadline) override
{
++reload_calls;
last_candidate = std::string{candidate};
last_deadline = deadline;
return 42;
}
Void::Result::Result<void>
drain(std::chrono::milliseconds) override
{
++drain_calls;
return drain_result;
}
Void::Result::Result<void> shutdown() override
{
++shutdown_calls;
return {};
}
Void::Result::Result<void> recover() override
{
++recover_calls;
return {};
}
};
ControlRequest request(std::string command, std::string token = "secret")
{
ControlRequest out;
out.command = std::move(command);
out.token = std::move(token);
return out;
}
void authentication_fails_closed()
{
FakeHandler handler;
ControlEndpoint endpoint{"secret", handler};
assert(endpoint.handle(request("inspect", "")).status ==
ControlStatus::Unauthenticated);
assert(endpoint.handle(request("inspect", "wrong")).status ==
ControlStatus::Unauthenticated);
assert(handler.inspect_calls == 0);
// An empty configured token authorizes nothing.
ControlEndpoint unconfigured{"", handler};
assert(unconfigured.handle(request("inspect", "")).status ==
ControlStatus::Unauthenticated);
}
void commands_dispatch_to_the_host()
{
FakeHandler handler;
ControlEndpoint endpoint{"secret", handler};
auto inspected = endpoint.handle(request("inspect"));
assert(inspected.status == ControlStatus::Ok);
assert(inspected.body == handler.inspected);
auto healthy = endpoint.handle(request("health"));
assert(healthy.status == ControlStatus::Ok);
assert(healthy.body == "ready");
handler.ready = false;
assert(endpoint.handle(request("health")).body == "not ready");
auto reload = request("reload");
reload.candidate = "rel-c";
reload.deadline = std::chrono::seconds{5};
auto reloaded = endpoint.handle(reload);
assert(reloaded.status == ControlStatus::Ok);
assert(reloaded.transaction_id == 42);
assert(handler.last_candidate == "rel-c");
assert(handler.last_deadline == std::chrono::seconds{5});
assert(endpoint.handle(request("reload")).status ==
ControlStatus::InvalidArgument);
auto validate = request("validate-candidate");
validate.candidate = "rel-d";
assert(endpoint.handle(validate).status == ControlStatus::Ok);
assert(handler.last_candidate == "rel-d");
assert(endpoint.handle(request("drain")).status == ControlStatus::Ok);
assert(endpoint.handle(request("shutdown")).status ==
ControlStatus::Ok);
assert(endpoint.handle(request("recover")).status ==
ControlStatus::Ok);
assert(handler.shutdown_calls == 1);
assert(handler.recover_calls == 1);
}
void bounds_and_error_mapping()
{
FakeHandler handler;
ControlEndpoint bounded{
"secret", handler,
ControlLimits{.max_request_bytes = 8, .max_reply_bytes = 64}};
auto oversized = request("inspect");
oversized.payload = "0123456789";
assert(bounded.handle(oversized).status ==
ControlStatus::InvalidArgument);
ControlEndpoint small_reply{
"secret", handler, ControlLimits{.max_reply_bytes = 4}};
assert(small_reply.handle(request("inspect")).body.size() == 4);
handler.drain_result = std::unexpected{
Void::Result::Error{Void::Result::ErrorKind::timeout,
"drain timed out"}};
ControlEndpoint normal{"secret", handler};
assert(normal.handle(request("drain")).status ==
ControlStatus::Timeout);
assert(normal.handle(request("bogus")).status ==
ControlStatus::InvalidArgument);
}
} // namespace
int main()
{
authentication_fails_closed();
commands_dispatch_to_the_host();
bounds_and_error_mapping();
std::puts("reloadable-host control ok");
return 0;
}
@@ -0,0 +1,98 @@
#include "reloadable_host/release_registry.hpp"
#include <cassert>
#include <cstdio>
#include <string>
namespace
{
using namespace ReloadableHost;
Void::Result::Result<void> accept(const ReleaseDescriptor&)
{
return {};
}
Void::Result::Result<void> reject(const ReleaseDescriptor&)
{
return std::unexpected{
Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
"release failed validation"}};
}
void pinned_handle_survives_reload()
{
ReleaseRegistry registry;
auto first = registry.publish({"rel-a", "/releases/a", 0}, accept);
assert(first.has_value() && *first == 1);
auto handle = registry.acquire();
assert(handle != nullptr);
assert(handle->id == "rel-a");
auto second = registry.publish({"rel-b", "/releases/b", 0}, accept);
assert(second.has_value() && *second == 2);
assert(registry.current()->id == "rel-b");
// The old read handle is still valid and pinned.
assert(handle->id == "rel-a");
assert(registry.retained() == 1);
assert(registry.collect() == 0);
handle.reset();
assert(registry.collect() == 1);
assert(registry.retained() == 0);
}
void duplicate_release_id_is_rejected()
{
ReleaseRegistry registry;
assert(registry.publish({"same", "/releases/x", 0}, accept)
.has_value());
assert(!registry.publish({"same", "/releases/y", 0}, accept)
.has_value());
}
void invalid_candidate_changes_nothing()
{
ReleaseRegistry registry;
assert(!registry.publish({"bad", "/releases/bad", 0}, reject)
.has_value());
assert(!registry.current().has_value());
assert(registry.retained() == 0);
assert(registry.acquire() == nullptr);
}
void unpinned_generations_are_reclaimed()
{
ReleaseRegistry registry{ReleaseLimits{.max_retained_generations = 1}};
assert(registry.publish({"a", "/a", 0}, accept).has_value());
assert(registry.publish({"b", "/b", 0}, accept).has_value());
assert(registry.retained() == 1);
// Publishing c reclaims the unpinned a before checking the cap.
assert(registry.publish({"c", "/c", 0}, accept).has_value());
assert(registry.retained() == 1);
}
void pinned_generation_blocks_the_cap()
{
ReleaseRegistry registry{ReleaseLimits{.max_retained_generations = 1}};
assert(registry.publish({"a", "/a", 0}, accept).has_value());
auto pin = registry.acquire();
assert(registry.publish({"b", "/b", 0}, accept).has_value());
// a is still pinned, so the cap cannot be reclaimed.
assert(!registry.publish({"c", "/c", 0}, accept).has_value());
pin.reset();
assert(registry.publish({"c", "/c", 0}, accept).has_value());
}
} // namespace
int main()
{
pinned_handle_survives_reload();
duplicate_release_id_is_rejected();
invalid_candidate_changes_nothing();
unpinned_generations_are_reclaimed();
pinned_generation_blocks_the_cap();
std::puts("reloadable-host release registry ok");
return 0;
}
@@ -0,0 +1,220 @@
#include "reloadable_host/activation.hpp"
#include "reloadable_host/release_registry.hpp"
#include "reloadable_host/reload_transaction.hpp"
#include "reloadable_host/resources.hpp"
#include <cassert>
#include <chrono>
#include <cstdio>
#include <string>
#include <vector>
namespace
{
using namespace ReloadableHost;
ReleaseDescriptor release(std::string id)
{
return ReleaseDescriptor{std::move(id), "/releases/x", 0};
}
void budget_enforces_generation_and_total_caps()
{
ResourceLimits limits;
limits.max_generation_bytes = 100;
limits.max_total_bytes = 150;
limits.max_generations = 2;
ResourceLedger ledger{limits};
// Per-generation cap.
auto oversized = ledger.reserve(1, 101);
assert(!oversized.has_value());
assert(oversized.error().kind() == Void::Result::ErrorKind::exhausted);
assert(ledger.reserve(1, 100).has_value());
// Aggregate cap (only 50 bytes left).
assert(!ledger.reserve(2, 51).has_value());
assert(ledger.reserve(2, 50).has_value());
// Generation cap.
assert(!ledger.reserve(3, 0).has_value());
// Duplicate reservation.
auto duplicate = ledger.reserve(1, 0);
assert(!duplicate.has_value());
assert(duplicate.error().kind() == Void::Result::ErrorKind::conflict);
const auto usage = ledger.usage();
assert(usage.total_bytes == 150);
assert(usage.generations == 2);
assert(ledger.peak_usage().total_bytes == 150);
// Release recovers admission.
assert(ledger.release(1));
assert(!ledger.release(1));
assert(ledger.usage().total_bytes == 50);
assert(ledger.reserve(3, 100).has_value());
assert(ledger.holds(3));
assert(!ledger.holds(1));
}
void uncooperative_pin_blocks_reload_until_released()
{
ReleaseRegistry registry{ReleaseLimits{.max_retained_generations = 1}};
assert(registry.publish(release("a"), {}).has_value());
const ReleaseHandle pinned = registry.acquire();
assert(pinned != nullptr);
assert(registry.publish(release("b"), {}).has_value());
// The pinned generation cannot be reclaimed: the cap rejects reload.
auto rejected = registry.publish(release("c"), {});
assert(!rejected.has_value());
assert(rejected.error().kind() == Void::Result::ErrorKind::exhausted);
assert(pinned->id == "a");
assert(registry.current()->id == "b");
// Dropping the pin lets collection progress.
const ReleaseHandle still_pinned = pinned;
assert(registry.collect() == 0);
assert(registry.retained() == 1);
}
void sustained_reload_stays_bounded()
{
ReleaseRegistry registry{ReleaseLimits{.max_retained_generations = 2}};
ResourceLimits limits;
limits.max_generations = 3;
limits.max_total_bytes = 3 * 1024;
limits.max_generation_bytes = 1024;
ResourceLedger ledger{limits};
MemoryActivationStorage storage;
ActivationJournal journal{storage};
Quiescence quiescence{
ReloadLimits{.drain_deadline = std::chrono::milliseconds{50},
.max_pins = 8}};
std::uint64_t next_generation = 1;
for (int cycle = 0; cycle < 200; ++cycle) {
const std::string id = "release-" + std::to_string(cycle);
assert(registry.publish(release(id), {}).has_value());
const std::uint64_t generation = next_generation++;
// Admission is checked before publishing work.
assert(ledger.reserve(generation, 512).has_value());
// A transient reader pins the generation; release it promptly.
{
assert(quiescence.admit().has_value());
const ReleaseHandle handle = registry.acquire();
assert(handle != nullptr);
quiescence.release();
}
// A reload transaction publishes and commits every cycle.
ReloadTransaction transaction{generation};
assert(transaction.prepare(
ReleaseCandidate{id, "/releases/x", generation}, {})
.has_value());
assert(transaction.drain(quiescence));
assert(transaction.publish().has_value());
transaction.commit(true);
const auto report = transaction.report();
assert(report.phase == ReloadPhase::Completed);
assert(report.outcome == ReloadOutcome::Published);
// The host reopens admissions once the new generation owns them.
quiescence.resume();
// Reclaim: registry collect plus ledger release of generations
// that are no longer pinned.
(void)registry.collect();
for (std::uint64_t old = 1; old < generation; ++old) {
(void)ledger.release(old);
}
assert(registry.retained() <= 2);
assert(ledger.usage().generations <= 2);
}
// Readers are admitted again after every drain.
assert(!quiescence.draining());
assert(quiescence.admit().has_value());
quiescence.release();
}
void drain_timeout_keeps_pins_and_blocks_publication()
{
Quiescence quiescence{
ReloadLimits{.drain_deadline = std::chrono::milliseconds{10},
.max_pins = 1}};
assert(quiescence.admit().has_value());
ReloadTransaction transaction{1};
assert(transaction
.prepare(ReleaseCandidate{"a", "/r", 1}, {})
.has_value());
auto drained = transaction.drain(quiescence);
assert(!drained.has_value());
assert(drained.error().kind() == Void::Result::ErrorKind::timeout);
// The publication point was never reached.
assert(!transaction.publish().has_value());
assert(quiescence.pins() == 1);
// Safe rollback: resume admission only after the pin drains.
quiescence.release();
quiescence.resume();
assert(!quiescence.draining());
transaction.cancel();
assert(transaction.report().outcome == ReloadOutcome::RolledBack);
}
void health_window_downtime_is_measured()
{
using Clock = std::chrono::steady_clock;
HealthWindow window{std::chrono::milliseconds{50}};
const auto start = Clock::now();
// Mutations are unavailable for the whole reversible window.
assert(!window.admit_write().has_value());
assert(window.admit_read());
assert(window.evaluate(start) == HealthWindow::Decision::Pending);
const auto commit_at = start + std::chrono::milliseconds{100};
assert(window.evaluate(commit_at) == HealthWindow::Decision::Commit);
// Downtime is at least the configured health window.
assert(commit_at - start >= std::chrono::milliseconds{50});
// A failed observation rolls back immediately instead of waiting.
HealthWindow failing{std::chrono::milliseconds{50}};
failing.observe(false);
assert(failing.evaluate(start) == HealthWindow::Decision::Rollback);
}
void committed_marker_survives_cleanup_failure()
{
MemoryActivationStorage storage;
ActivationJournal journal{storage};
ActivationRecord record;
record.transaction_id = 9;
record.previous_release = "a";
record.candidate_release = "b";
assert(journal.activate(record).has_value());
assert(journal.commit_healthy(9) == CommitOutcome::Committed);
// Cleanup is best effort after the durable marker: a failure must not
// turn the committed outcome into a rollback.
storage.fail_next_write(true);
const auto recovered = journal.reconcile();
assert(recovered.action == RecoveryAction::UseCandidate);
assert(recovered.cleanup_pending);
assert(journal.cleanup().has_value());
assert(journal.reconcile().action == RecoveryAction::None);
}
} // namespace
int main()
{
budget_enforces_generation_and_total_caps();
uncooperative_pin_blocks_reload_until_released();
sustained_reload_stays_bounded();
drain_timeout_keeps_pins_and_blocks_publication();
health_window_downtime_is_measured();
committed_marker_survives_cleanup_failure();
std::puts("reloadable-host failure matrix ok");
return 0;
}
@@ -0,0 +1,128 @@
#include "reloadable_host/reload_transaction.hpp"
#include <cassert>
#include <chrono>
#include <cstdio>
#include <string>
namespace
{
using namespace ReloadableHost;
Void::Result::Result<void> accept_all(const ReleaseCandidate&)
{
return {};
}
Void::Result::Result<void> reject_all(const ReleaseCandidate&)
{
return std::unexpected{
Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
"release failed validation"}};
}
void happy_path_stays_published()
{
ReloadTransaction tx{1};
const ReleaseCandidate candidate{"rel-a", "/releases/a", 2};
assert(tx.prepare(candidate, accept_all).has_value());
Quiescence quiescence;
assert(tx.drain(quiescence).has_value());
assert(tx.publish().has_value());
tx.commit(true);
const auto report = tx.report();
assert(report.id == 1);
assert(report.phase == ReloadPhase::Completed);
assert(report.outcome == ReloadOutcome::Published);
assert(report.candidate == "rel-a");
quiescence.resume();
}
void cancel_before_publish_rolls_back()
{
ReloadTransaction tx{2};
assert(tx.prepare({"rel-b", "/releases/b", 1}, accept_all)
.has_value());
tx.cancel();
assert(tx.report().outcome == ReloadOutcome::RolledBack);
assert(tx.report().phase == ReloadPhase::CancelledBeforePublish);
Quiescence quiescence;
assert(!tx.drain(quiescence).has_value());
}
void cancel_after_publish_is_a_noop()
{
ReloadTransaction tx{3};
assert(tx.prepare({"rel-c", "/releases/c", 1}, accept_all)
.has_value());
Quiescence quiescence;
assert(tx.drain(quiescence).has_value());
assert(tx.publish().has_value());
tx.cancel();
assert(tx.report().phase == ReloadPhase::Committing);
// A lost durable acknowledgement is Unknown, never RolledBack.
tx.commit(false);
assert(tx.report().phase == ReloadPhase::UnknownOutcome);
assert(tx.report().outcome == ReloadOutcome::UnknownOutcome);
quiescence.resume();
}
void invalid_candidate_fails_closed()
{
ReloadTransaction tx{4};
assert(!tx.prepare({"rel-d", "/releases/d", 1}, reject_all)
.has_value());
assert(tx.report().phase == ReloadPhase::Failed);
assert(tx.report().outcome == ReloadOutcome::Failed);
}
void quiescence_blocks_admission_and_drains()
{
Quiescence quiescence{ReloadLimits{
.drain_deadline = std::chrono::milliseconds{10},
.max_pins = 2}};
assert(quiescence.admit().has_value());
assert(quiescence.admit().has_value());
// Pin cap.
assert(!quiescence.admit().has_value());
// Pinned calls hold the drain until the deadline.
assert(!quiescence.drain());
assert(quiescence.draining());
quiescence.release();
quiescence.release();
assert(quiescence.drain());
// Admissions stay closed while draining.
assert(!quiescence.admit().has_value());
quiescence.resume();
assert(quiescence.admit().has_value());
quiescence.release();
}
void invalid_transitions_are_rejected()
{
ReloadTransaction tx{5};
Quiescence quiescence;
assert(!tx.publish().has_value());
assert(!tx.drain(quiescence).has_value());
}
} // namespace
int main()
{
happy_path_stays_published();
cancel_before_publish_rolls_back();
cancel_after_publish_is_a_noop();
invalid_candidate_fails_closed();
quiescence_blocks_admission_and_drains();
invalid_transitions_are_rejected();
std::puts("reloadable-host transaction ok");
return 0;
}
@@ -0,0 +1,220 @@
#include "reloadable_host/posix_worker.hpp"
#include "reloadable_host/supervisor.hpp"
#include <cassert>
#include <chrono>
#include <cstdio>
#include <optional>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace ReloadableHost;
/// Deterministic process port: exits are queued by the test.
struct FakePort final : WorkerProcessPort {
std::vector<std::string> spawns;
std::optional<WorkerExit> next_exit;
bool alive{false};
bool fail_spawn{false};
int terminations{0};
Void::Result::Result<void>
spawn(const std::string& command) override
{
if (fail_spawn) {
return std::unexpected{Void::Result::Error{
Void::Result::ErrorKind::io, "spawn failed"}};
}
spawns.push_back(command);
alive = true;
return {};
}
Void::Result::Result<std::optional<WorkerExit>>
try_wait() override
{
if (!next_exit) {
return std::optional<WorkerExit>{};
}
const WorkerExit exit = *next_exit;
next_exit.reset();
alive = false;
return std::optional<WorkerExit>{exit};
}
void terminate(std::chrono::milliseconds) noexcept override
{
++terminations;
alive = false;
}
[[nodiscard]] bool running() const noexcept override
{
return alive;
}
};
RestartPolicy policy()
{
return RestartPolicy{.max_restarts = 2,
.base_backoff = std::chrono::milliseconds{10},
.max_backoff = std::chrono::milliseconds{15}};
}
void crash_restarts_with_bounded_backoff_then_fails()
{
FakePort port;
WorkerSupervisor supervisor{port, "worker", policy()};
assert(supervisor.start().has_value());
assert(port.spawns.size() == 1);
port.next_exit = WorkerExit{.exited = true, .code = 1};
auto first = supervisor.poll();
assert(first.has_value());
assert(first->state == WorkerState::Restarting);
assert(first->restarts == 1);
assert(first->next_backoff == std::chrono::milliseconds{10});
// The next poll respawns.
auto respawned = supervisor.poll();
assert(respawned.has_value());
assert(respawned->state == WorkerState::Running);
assert(port.spawns.size() == 2);
port.next_exit = WorkerExit{.exited = true, .code = 2};
auto second = supervisor.poll();
assert(second.has_value());
assert(second->restarts == 2);
// Exponential backoff saturates at max_backoff.
assert(second->next_backoff == std::chrono::milliseconds{15});
assert(supervisor.poll()->state == WorkerState::Running);
port.next_exit = WorkerExit{.exited = true, .signal = 9};
auto exhausted = supervisor.poll();
assert(exhausted.has_value());
assert(exhausted->state == WorkerState::Failed);
assert(exhausted->next_backoff == std::chrono::milliseconds{0});
assert(exhausted->last_error.find("signal 9") != std::string::npos);
}
void clean_exit_stops_without_restart()
{
FakePort port;
WorkerSupervisor supervisor{port, "worker", policy()};
assert(supervisor.start().has_value());
port.next_exit = WorkerExit{.exited = true, .code = 0};
auto report = supervisor.poll();
assert(report.has_value());
assert(report->state == WorkerState::Stopped);
assert(report->restarts == 0);
assert(port.spawns.size() == 1);
}
void crash_with_effect_in_progress_is_unknown()
{
FakePort port;
WorkerSupervisor supervisor{port, "worker", policy()};
assert(supervisor.start().has_value());
supervisor.begin_effect();
assert(supervisor.report().effects == EffectState::InProgress);
port.next_exit = WorkerExit{.exited = true, .code = 1};
(void)supervisor.poll();
// Never reported as rolled back or completed.
assert(supervisor.report().effects == EffectState::Unknown);
// A later completion cannot prove the crashed effect finished.
supervisor.begin_effect();
supervisor.complete_effect();
assert(supervisor.report().effects == EffectState::Unknown);
}
void confirmed_effect_completes()
{
FakePort port;
WorkerSupervisor supervisor{port, "worker", policy()};
assert(supervisor.start().has_value());
supervisor.begin_effect();
supervisor.complete_effect();
assert(supervisor.report().effects == EffectState::Completed);
port.next_exit = WorkerExit{.exited = true, .code = 0};
(void)supervisor.poll();
assert(supervisor.report().effects == EffectState::Completed);
}
void stop_terminates_once_and_preserves_unknown()
{
FakePort port;
WorkerSupervisor supervisor{port, "worker", policy()};
assert(supervisor.start().has_value());
supervisor.begin_effect();
supervisor.stop();
assert(port.terminations == 1);
assert(supervisor.report().state == WorkerState::Stopped);
// Termination may have interrupted the effect.
assert(supervisor.report().effects == EffectState::Unknown);
supervisor.stop();
assert(port.terminations == 1);
}
void spawn_failure_is_terminal()
{
FakePort port;
port.fail_spawn = true;
WorkerSupervisor supervisor{port, "worker", policy()};
assert(!supervisor.start().has_value());
assert(supervisor.report().state == WorkerState::Failed);
assert(supervisor.report().last_error == "spawn failed");
}
/// Poll the supervisor until the worker leaves the running state or the
/// bounded wait expires.
SupervisorReport wait_for_exit(WorkerSupervisor& supervisor)
{
for (int i = 0; i < 500; ++i) {
(void)supervisor.poll();
if (supervisor.report().state != WorkerState::Running) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
return supervisor.report();
}
void real_posix_port_reports_exit()
{
{
PosixWorkerPort port;
WorkerSupervisor supervisor{port, "exit 0", policy()};
assert(supervisor.start().has_value());
const SupervisorReport report = wait_for_exit(supervisor);
assert(report.state == WorkerState::Stopped);
}
{
PosixWorkerPort port;
RestartPolicy none;
none.max_restarts = 0;
WorkerSupervisor supervisor{port, "exit 7", none};
assert(supervisor.start().has_value());
const SupervisorReport report = wait_for_exit(supervisor);
assert(report.state == WorkerState::Failed);
assert(report.last_error.find("code 7") != std::string::npos);
}
}
} // namespace
int main()
{
crash_restarts_with_bounded_backoff_then_fails();
clean_exit_stops_without_restart();
crash_with_effect_in_progress_is_unknown();
confirmed_effect_completes();
stop_terminates_once_and_preserves_unknown();
spawn_failure_is_terminal();
real_posix_port_reports_exit();
std::puts("reloadable-host supervisor ok");
return 0;
}
+255
View File
@@ -0,0 +1,255 @@
#pragma once
#include <Void/Math/Vec.hpp>
#include <array>
#include <cmath>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <optional>
#include <utility>
namespace Void::Algorithms
{
/// Integer cell index in the voxel grid.
struct GridCell {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto operator<=>(const GridCell&) const noexcept = default;
[[nodiscard]] bool operator==(const GridCell&) const noexcept = default;
};
enum class GridAxis : std::uint8_t {
none = 0,
x,
y,
z,
};
/// Face crossed when entering a cell.
///
/// `sign` is the direction of travel along `axis`: `+1` means the ray crossed
/// the lower boundary (entered through the cell's negative face), `-1` means
/// it crossed the upper boundary. `axis == none` is the starting cell.
struct GridFace {
GridAxis axis{GridAxis::none};
int sign{0};
[[nodiscard]] bool operator==(const GridFace&) const noexcept = default;
};
struct GridRayOptions {
/// Maximum number of cells yielded, including the start cell.
std::size_t max_steps{1024};
/// Maximum ray parameter for entering a cell. The start cell (t = 0) is
/// always yielded; a later cell is yielded only when its entry t is
/// `<= max_distance`.
double max_distance{std::numeric_limits<double>::infinity()};
};
struct GridRayVisit {
GridCell cell;
GridFace face;
/// Ray parameter at which the cell was entered (0 for the start cell).
double t{0};
};
enum class GridRayStatus : std::uint8_t {
/// More cells may be produced.
running = 0,
exhausted_steps,
exhausted_distance,
/// The direction was exactly (0, 0, 0); the start cell was still yielded.
zero_direction,
nonfinite_input,
/// A cell index would leave the int64 range.
out_of_range,
};
/// Bounded 3D grid traversal (Amanatides-Woo DDA) over integer cells.
///
/// Policy:
/// - The start cell is `floor(origin)` per axis, so a coordinate exactly on a
/// boundary belongs to the cell on the positive side.
/// - Zero direction components never cross that axis (axis-parallel rays work).
/// - At simultaneous axis crossings (edge/corner ties) the axis with the lowest
/// index is stepped first: x, then y, then z. The traversal may therefore
/// visit the intermediate edge/corner cell; each visit reports the face it
/// crossed to enter.
/// - Nonfinite origin/direction is rejected before any visit. An all-zero
/// direction yields the start cell once and then reports `zero_direction`.
/// - The work is bounded by `max_steps` and `max_distance`.
class GridRayIterator
{
public:
GridRayIterator(Void::Math::Vec3d origin,
Void::Math::Vec3d direction,
GridRayOptions options = {})
: options_(options)
{
if (!std::isfinite(origin.x) || !std::isfinite(origin.y) ||
!std::isfinite(origin.z) || !std::isfinite(direction.x) ||
!std::isfinite(direction.y) ||
!std::isfinite(direction.z) ||
std::isnan(options.max_distance)) {
status_ = GridRayStatus::nonfinite_input;
return;
}
const double origin_axis[3] = {origin.x, origin.y, origin.z};
const double direction_axis[3] = {direction.x, direction.y,
direction.z};
bool any_direction = false;
for (int axis = 0; axis < 3; ++axis) {
const double coordinate = std::floor(origin_axis[axis]);
if (coordinate <
static_cast<double>(
std::numeric_limits<std::int64_t>::min()) ||
coordinate >
static_cast<double>(
std::numeric_limits<std::int64_t>::max())) {
status_ = GridRayStatus::out_of_range;
return;
}
cell_[axis] = static_cast<std::int64_t>(coordinate);
const double direction_value = direction_axis[axis];
if (direction_value == 0.0) {
step_[axis] = 0;
t_max_[axis] =
std::numeric_limits<double>::infinity();
t_delta_[axis] =
std::numeric_limits<double>::infinity();
continue;
}
any_direction = true;
step_[axis] = direction_value > 0.0 ? 1 : -1;
const double boundary =
step_[axis] > 0
? static_cast<double>(cell_[axis]) + 1.0
: static_cast<double>(cell_[axis]);
t_max_[axis] =
(boundary - origin_axis[axis]) / direction_value;
t_delta_[axis] =
1.0 / std::abs(direction_value);
}
zero_direction_ = !any_direction;
}
[[nodiscard]] std::optional<GridRayVisit> next()
{
if (status_ != GridRayStatus::running) {
return std::nullopt;
}
if (!started_) {
if (options_.max_steps == 0) {
status_ = GridRayStatus::exhausted_steps;
return std::nullopt;
}
started_ = true;
visited_ = 1;
const GridRayVisit visit{.cell = GridCell{cell_[0], cell_[1],
cell_[2]},
.face = {},
.t = 0.0};
if (zero_direction_) {
status_ = GridRayStatus::zero_direction;
} else if (visited_ >= options_.max_steps) {
status_ = GridRayStatus::exhausted_steps;
}
return visit;
}
int axis = 0;
if (t_max_[1] < t_max_[axis]) {
axis = 1;
}
if (t_max_[2] < t_max_[axis]) {
axis = 2;
}
const double t = t_max_[axis];
if (t > options_.max_distance) {
status_ = GridRayStatus::exhausted_distance;
return std::nullopt;
}
if ((step_[axis] > 0 &&
cell_[axis] == std::numeric_limits<std::int64_t>::max()) ||
(step_[axis] < 0 &&
cell_[axis] == std::numeric_limits<std::int64_t>::min())) {
status_ = GridRayStatus::out_of_range;
return std::nullopt;
}
cell_[axis] += step_[axis];
t_max_[axis] += t_delta_[axis];
++visited_;
const GridRayVisit visit{
.cell = GridCell{cell_[0], cell_[1], cell_[2]},
.face = GridFace{
.axis = axis == 0 ? GridAxis::x
: axis == 1 ? GridAxis::y : GridAxis::z,
.sign = step_[axis]},
.t = t};
if (visited_ >= options_.max_steps) {
status_ = GridRayStatus::exhausted_steps;
}
return visit;
}
[[nodiscard]] GridRayStatus status() const noexcept
{
return status_;
}
[[nodiscard]] GridCell cell() const noexcept
{
return GridCell{cell_[0], cell_[1], cell_[2]};
}
private:
GridRayOptions options_;
std::array<std::int64_t, 3> cell_{};
std::array<int, 3> step_{};
std::array<double, 3> t_max_{};
std::array<double, 3> t_delta_{};
GridRayStatus status_{GridRayStatus::running};
std::size_t visited_{0};
bool started_{false};
bool zero_direction_{false};
};
struct GridRaycastResult {
std::optional<GridRayVisit> hit;
GridRayStatus status{GridRayStatus::running};
std::size_t visited{0};
};
/// Traverse until `occupied(cell)` is true, then return that cell and the face
/// it was entered through (the start cell reports `GridFace{}`).
template <typename Occupancy>
[[nodiscard]] GridRaycastResult
raycast_grid(Void::Math::Vec3d origin,
Void::Math::Vec3d direction,
Occupancy&& occupied,
GridRayOptions options = {})
{
GridRayIterator iterator{origin, direction, options};
GridRaycastResult result;
while (const auto visit = iterator.next()) {
++result.visited;
if (occupied(visit->cell)) {
result.hit = *visit;
return result;
}
}
result.status = iterator.status();
return result;
}
} // namespace Void::Algorithms
+156
View File
@@ -0,0 +1,156 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace Void::Algorithms
{
enum class ReadSetStatus : std::uint8_t {
/// A new key/revision pair was recorded.
recorded = 0,
/// The same key with the same revision was already recorded.
unchanged,
/// The same key was observed with a different revision.
conflicting,
/// The entry bound is reached; nothing was recorded.
capacity_exceeded,
/// The key is empty.
invalid_key,
};
enum class ReadSetValidation : std::uint8_t {
valid = 0,
/// A recorded key is missing or has a different revision.
invalidated,
/// The validating view belongs to another epoch.
epoch_changed,
/// A conflicting observation was reported; the set cannot be published.
conflicted,
/// An observation was rejected for capacity; the set is incomplete.
incomplete,
};
struct ReadSetLimits {
std::size_t max_entries{256};
};
/// Bounded set of distinct key/revision pairs consulted while computing a
/// result, qualified by an epoch.
///
/// Repeated reads of one unchanged key consume one entry. Observing the same
/// key with a different revision is reported as a conflict, and an entry over
/// the bound as capacity exhaustion; `validate` refuses to report a conflicted
/// or incomplete set as valid so a result cannot be published from it.
///
/// Validation compares the recorded set against a stable read view supplied by
/// the caller (a revision lookup per key plus the view's epoch). An epoch
/// change invalidates the set even when every numeric revision matches. Keys
/// not in the set (unrelated edits) do not affect the result.
class RevisionReadSet
{
public:
using Limits = ReadSetLimits;
explicit RevisionReadSet(std::uint64_t epoch, Limits limits = {})
: epoch_(epoch)
, limits_(limits)
{
}
[[nodiscard]] std::uint64_t epoch() const noexcept { return epoch_; }
[[nodiscard]] ReadSetStatus observe(std::string key,
std::uint64_t revision)
{
if (key.empty()) {
return ReadSetStatus::invalid_key;
}
if (const auto found = entries_.find(key);
found != entries_.end()) {
if (found->second == revision) {
return ReadSetStatus::unchanged;
}
conflicted_ = true;
return ReadSetStatus::conflicting;
}
if (entries_.size() >= limits_.max_entries) {
incomplete_ = true;
return ReadSetStatus::capacity_exceeded;
}
entries_.emplace(std::move(key), revision);
return ReadSetStatus::recorded;
}
[[nodiscard]] bool contains(std::string_view key) const
{
return entries_.contains(std::string{key});
}
[[nodiscard]] std::optional<std::uint64_t>
revision_of(std::string_view key) const
{
const auto found = entries_.find(std::string{key});
if (found == entries_.end()) {
return std::nullopt;
}
return found->second;
}
[[nodiscard]] std::size_t size() const noexcept
{
return entries_.size();
}
[[nodiscard]] bool conflicted() const noexcept { return conflicted_; }
[[nodiscard]] bool incomplete() const noexcept { return incomplete_; }
/// Recorded observations, sorted by key.
[[nodiscard]] const std::map<std::string, std::uint64_t>&
entries() const noexcept
{
return entries_;
}
/// Validate against a stable read view.
///
/// `lookup(key)` returns the current revision of `key`, or `nullopt`
/// when it no longer exists. `view_epoch` is the epoch of the view.
template <typename Lookup>
[[nodiscard]] ReadSetValidation
validate(std::uint64_t view_epoch, Lookup&& lookup) const
{
if (view_epoch != epoch_) {
return ReadSetValidation::epoch_changed;
}
if (conflicted_) {
return ReadSetValidation::conflicted;
}
if (incomplete_) {
return ReadSetValidation::incomplete;
}
for (const auto& [key, revision] : entries_) {
const auto current = lookup(key);
if (!current.has_value() || *current != revision) {
return ReadSetValidation::invalidated;
}
}
return ReadSetValidation::valid;
}
private:
std::uint64_t epoch_{0};
Limits limits_{};
std::map<std::string, std::uint64_t> entries_;
bool conflicted_{false};
bool incomplete_{false};
};
} // namespace Void::Algorithms
@@ -0,0 +1,137 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <deque>
#include <mutex>
#include <optional>
#include <utility>
namespace Void::Async
{
/// Bounded work queue whose admission is conditioned on an exact retained
/// publication token.
///
/// A producer validates a publication (and may retain its value elsewhere),
/// then submits work with that token. Comparison against the current token and
/// the capacity reservation happen under one lock, so a replacement published
/// between validation and submission is detected: the work is not moved and
/// the queue is unchanged.
///
/// Refusal outcomes are distinct: `publication_changed`, `saturated` and
/// `closed` (checked in that order). The payload is moved only when the result
/// is `admitted`. Admitted work is popped exactly once.
///
/// Thread-safe.
template <typename Work, typename Token = std::uint64_t>
class PublicationGatedQueue
{
public:
struct Limits {
std::size_t capacity{64};
};
enum class Status : std::uint8_t {
admitted = 0,
/// The current token differs from the expected one.
publication_changed,
/// The queue is at capacity.
saturated,
/// The queue no longer accepts submissions.
closed,
};
explicit PublicationGatedQueue(Token initial,
Limits limits = Limits{})
: token_(std::move(initial))
, limits_(limits)
{
}
PublicationGatedQueue(const PublicationGatedQueue&) = delete;
PublicationGatedQueue& operator=(const PublicationGatedQueue&) =
delete;
/// Publish a replacement token. Returns false once closed.
bool publish(Token next)
{
std::lock_guard lock{mutex_};
if (closed_) {
return false;
}
token_ = std::move(next);
return true;
}
[[nodiscard]] Token current() const
{
std::lock_guard lock{mutex_};
return token_;
}
/// Admit `work` only if `expected` is still the current publication and
/// capacity is available. `work` is moved only on `admitted`.
[[nodiscard]] Status try_submit(const Token& expected, Work&& work)
{
std::lock_guard lock{mutex_};
if (closed_) {
return Status::closed;
}
if (!(token_ == expected)) {
return Status::publication_changed;
}
if (queue_.size() >= limits_.capacity) {
return Status::saturated;
}
queue_.push_back(std::move(work));
return Status::admitted;
}
/// Remove one admitted item, if any.
[[nodiscard]] std::optional<Work> try_pop()
{
std::lock_guard lock{mutex_};
if (queue_.empty()) {
return std::nullopt;
}
Work work = std::move(queue_.front());
queue_.pop_front();
return work;
}
void close()
{
std::lock_guard lock{mutex_};
closed_ = true;
}
[[nodiscard]] bool closed() const
{
std::lock_guard lock{mutex_};
return closed_;
}
[[nodiscard]] std::size_t size() const
{
std::lock_guard lock{mutex_};
return queue_.size();
}
[[nodiscard]] Limits limits() const
{
std::lock_guard lock{mutex_};
return limits_;
}
private:
mutable std::mutex mutex_;
Token token_;
Limits limits_{};
std::deque<Work> queue_;
bool closed_{false};
};
} // namespace Void::Async
+218 -5
View File
@@ -2,6 +2,7 @@
#include <Void/Core/Meta.hpp>
#include <charconv>
#include <cstdint>
#include <expected>
#include <functional>
@@ -17,6 +18,7 @@ namespace Void::Argparse
enum class ParseOutcome : std::uint8_t {
Ok,
Help,
Version,
Error,
};
@@ -33,6 +35,10 @@ namespace Void::Argparse
{
return outcome == ParseOutcome::Help;
}
[[nodiscard]] bool is_version() const noexcept
{
return outcome == ParseOutcome::Version;
}
[[nodiscard]] bool is_error() const noexcept
{
return outcome == ParseOutcome::Error;
@@ -72,6 +78,14 @@ namespace Void::Argparse
std::string_view short_name,
std::string_view description, bool& out);
// Add a repeatable flag counting occurrences (-vvv -> 3).
Parser& count_flag(std::string_view long_name,
std::string_view short_name,
std::string_view description, int& out);
// Set the program version exposed as --version / -V.
Parser& version(std::string version);
// Add an option that takes a value. If not provided, out stays
// nullopt.
Parser& option(std::string_view long_name,
@@ -93,10 +107,53 @@ namespace Void::Argparse
std::string& out,
std::string_view default_value = "");
// Option restricted to a fixed set of values.
Parser& option_checked(std::string_view long_name,
std::string_view short_name,
std::string_view description,
std::optional<std::string>& out,
std::vector<std::string> allowed);
Parser& option_default_checked(
std::string_view long_name, std::string_view short_name,
std::string_view description, std::string& out,
std::string_view default_value,
std::vector<std::string> allowed);
// Mark a previously added option as required.
Parser& require_option(std::string_view long_name);
// Fallback to an environment variable when the option is absent.
Parser& env(std::string_view long_name,
std::string_view env_var);
// Two options may not be used together.
Parser& conflicts(std::string_view first, std::string_view second);
// Customize the help placeholder for an option (default "value").
Parser& value_name(std::string_view long_name,
std::string_view name);
// Accept an extra long spelling for an option or flag.
Parser& alias(std::string_view long_name, std::string_view alias);
// Omit an option or flag from the generated help.
Parser& hide(std::string_view long_name);
// Enable or disable ANSI styling in help text (default: enabled,
// unless the NO_COLOR environment variable is set).
Parser& color(bool enabled) noexcept;
// Add a required positional argument.
Parser& positional(std::string_view name,
std::string_view description, std::string& out);
// Positional restricted to a fixed set of values.
Parser& positional_checked(std::string_view name,
std::string_view description,
std::string& out,
std::vector<std::string> allowed);
// Add a variadic trailing positional argument list.
Parser& positional_many(std::string_view name,
std::string_view description,
@@ -128,18 +185,26 @@ namespace Void::Argparse
private:
struct FlagEntry {
std::string lng, sht, desc;
bool* out;
std::string lng, sht, desc, alias;
bool hidden{false};
bool* out{nullptr};
int* count_out{nullptr};
};
struct OptionEntry {
std::string lng, sht, desc, def;
std::string value_name{}, alias{};
bool hidden{false};
std::optional<std::string>* out_opt{nullptr};
std::string* out_str{nullptr};
std::vector<std::string>* out_many{nullptr};
std::vector<std::string> allowed{};
bool required{false};
std::string env_var{};
};
struct PosEntry {
std::string name, desc;
std::string* out;
std::string* out{nullptr};
std::vector<std::string> allowed{};
};
struct MultiPosEntry {
std::string name, desc;
@@ -152,7 +217,9 @@ namespace Void::Argparse
std::function<void()> on_selected;
};
std::string program_, description_;
std::string program_, description_, version_;
bool m_color{true};
std::vector<std::pair<std::string, std::string>> conflicts_;
std::vector<FlagEntry> flags_;
std::vector<OptionEntry> options_;
std::vector<PosEntry> positionals_;
@@ -191,6 +258,14 @@ namespace Void::Argparse
struct Name {
Void::Meta::Str text;
}; // long-name override (without "--")
struct ValueName {
Void::Meta::Str text;
}; // help placeholder for an option
struct Alias {
Void::Meta::Str text;
}; // extra long spelling (with "--")
struct Hide {
}; // omit from help
struct Positional {
};
@@ -204,6 +279,19 @@ namespace Void::Argparse
Opts out{};
Parser parser{std::move(program), std::move(description)};
// Numeric option sinks: the parser binds text, then converts it with
// strict validation after a successful parse.
struct NumericSink {
std::string text{};
std::vector<std::string> texts{};
std::string option{};
bool many{false};
std::function<bool(std::string_view)> assign{};
};
// Heap-owned so the parser's bound string pointer stays valid when the
// collection grows.
std::vector<std::unique_ptr<NumericSink>> numeric_sinks;
template for (constexpr auto m : Void::Meta::members_v<Opts>)
{
using MT = [:std::meta::type_of(m):];
@@ -218,18 +306,130 @@ namespace Void::Argparse
constexpr auto hp = Void::Meta::annotation_of<Help>(m);
const std::string desc =
hp.has_value() ? std::string{hp->text.view()} : std::string{};
constexpr auto vn = Void::Meta::annotation_of<ValueName>(m);
constexpr auto al = Void::Meta::annotation_of<Alias>(m);
constexpr bool hidden = Void::Meta::has_annotation<Hide>(m);
auto decorate = [&] {
if (vn.has_value()) {
parser.value_name(lng, vn->text.view());
}
if (al.has_value()) {
parser.alias(lng, al->text.view());
}
if (hidden) {
parser.hide(lng);
}
};
if constexpr (Void::Meta::has_annotation<Positional>(m)) {
parser.positional(std::meta::identifier_of(m), desc, out.[:m:]);
} else if constexpr (std::same_as<MT, bool>) {
parser.flag(lng, sht, desc, out.[:m:]);
} else if constexpr (Void::Meta::is_optional_v<MT>) {
parser.option(lng, sht, desc, out.[:m:]);
using Inner = typename MT::value_type;
if constexpr (std::same_as<Inner, std::string>) {
parser.option(lng, sht, desc, out.[:m:]);
} else {
auto sink = std::make_unique<NumericSink>();
sink->option = lng;
sink->assign = [target = &out.[:m:]](std::string_view text) {
if (text.empty()) {
target->reset();
return true;
}
Inner value{};
if constexpr (std::is_enum_v<Inner>) {
const auto parsed = Void::Meta::enum_parse<Inner>(text);
if (!parsed) {
return false;
}
*target = *parsed;
return true;
} else {
const auto result = std::from_chars(
text.data(), text.data() + text.size(), value);
if (result.ec != std::errc{} ||
result.ptr != text.data() + text.size()) {
return false;
}
*target = value;
return true;
}
};
parser.option_default(lng, sht, desc, sink->text, "");
numeric_sinks.push_back(std::move(sink));
}
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
parser.option_many(lng, sht, desc, out.[:m:]);
} else if constexpr (Void::Meta::is_vector_v<MT>) {
using Inner = typename MT::value_type;
auto sink = std::make_unique<NumericSink>();
sink->option = lng;
sink->many = true;
sink->assign = [target = &out.[:m:]](std::string_view text) {
Inner value{};
if constexpr (std::is_enum_v<Inner>) {
const auto parsed = Void::Meta::enum_parse<Inner>(text);
if (!parsed) {
return false;
}
value = *parsed;
} else {
const auto result = std::from_chars(
text.data(), text.data() + text.size(), value);
if (result.ec != std::errc{} ||
result.ptr != text.data() + text.size()) {
return false;
}
}
target->push_back(value);
return true;
};
parser.option_many(lng, sht, desc, sink->texts);
numeric_sinks.push_back(std::move(sink));
} else if constexpr (std::same_as<MT, std::string>) {
const std::string def = out.[:m:];
parser.option_default(lng, sht, desc, out.[:m:], def);
decorate();
} else if constexpr (std::is_enum_v<MT>) {
auto sink = std::make_unique<NumericSink>();
sink->option = lng;
sink->text = std::string{Void::Meta::enum_name(out.[:m:])};
const std::string initial = sink->text;
std::vector<std::string> allowed;
for (const auto& entry : Void::Meta::enum_entries<MT>()) {
allowed.emplace_back(entry.second);
}
sink->assign = [target = &out.[:m:], initial](std::string_view text) {
if (const auto parsed = Void::Meta::enum_parse<MT>(text)) {
*target = *parsed;
return true;
}
// A default that is not an enumerator name (e.g. a cast value)
// is left untouched rather than failing the whole parse.
return text == initial;
};
parser.option_default_checked(lng, sht, desc, sink->text, sink->text,
std::move(allowed));
numeric_sinks.push_back(std::move(sink));
} else if constexpr (std::is_arithmetic_v<MT>) {
auto sink = std::make_unique<NumericSink>();
sink->option = lng;
sink->text = std::to_string(out.[:m:]);
sink->assign = [target = &out.[:m:]](std::string_view text) {
using DT = std::remove_pointer_t<decltype(target)>;
DT value{};
const auto result = std::from_chars(
text.data(), text.data() + text.size(), value);
if (result.ec != std::errc{} ||
result.ptr != text.data() + text.size()) {
return false;
}
*target = value;
return true;
};
parser.option_default(lng, sht, desc, sink->text, sink->text);
numeric_sinks.push_back(std::move(sink));
}
// other field types: ignored
}
@@ -238,6 +438,19 @@ namespace Void::Argparse
if (!r) {
return std::unexpected{r.error()};
}
for (const auto& sink : numeric_sinks) {
if (sink->many) {
for (const auto& text : sink->texts) {
if (!sink->assign(text)) {
return std::unexpected{"invalid value '" + text +
"' for " + sink->option};
}
}
} else if (!sink->assign(sink->text)) {
return std::unexpected{"invalid value '" + sink->text +
"' for " + sink->option};
}
}
return out;
}
+416
View File
@@ -0,0 +1,416 @@
#pragma once
#include <algorithm>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <string>
#include <utility>
#include <vector>
namespace Void::Containers
{
using LedgerQuantity = std::uint64_t;
using LedgerAccountKey = std::string;
using LedgerOperationId = std::string;
struct LedgerDebit {
LedgerAccountKey account;
LedgerQuantity quantity{0};
[[nodiscard]] auto operator<=>(const LedgerDebit&) const noexcept = default;
[[nodiscard]] bool operator==(const LedgerDebit&) const noexcept = default;
};
enum class LedgerStatus : std::uint8_t {
committed = 0,
/// The operation already committed; the recorded outcome is returned.
replayed,
insufficient_balance,
capacity_exhausted,
overflow,
unknown_operation,
unknown_account,
/// Operation id reused with a different request or a forbidden phase.
invalid_state,
/// A released reservation cannot be delivered.
released,
limit_exceeded,
};
enum class ReservationPhase : std::uint8_t {
held = 0,
delivered,
released,
};
struct LedgerResult {
LedgerStatus status{LedgerStatus::unknown_operation};
ReservationPhase phase{ReservationPhase::held};
LedgerOperationId operation;
[[nodiscard]] bool committed() const noexcept
{
return status == LedgerStatus::committed ||
status == LedgerStatus::replayed;
}
[[nodiscard]] bool operator==(const LedgerResult&) const noexcept = default;
};
struct LedgerLimits {
std::size_t max_accounts{1024};
std::size_t max_operations{4096};
};
/// In-memory, restorable account ledger with atomic multi-account
/// reservations and repeatable transfers.
///
/// Accounts are caller-keyed and carry an owner, a balance and a capacity.
/// `reserve` debits one or more accounts atomically into a held reservation;
/// `transfer` gives the reserved quantity to a destination account (the next
/// owner); `release` returns it to the sources without changing ownership.
///
/// Every committed phase is recorded under its operation id, so repeating the
/// same request returns the recorded outcome instead of applying it twice.
/// The state is a plain value: `save()` can be persisted and `restore()`d, and
/// a replay after restoring a partially completed transfer still applies once.
/// Failed attempts (insufficient balance, capacity, overflow) change nothing
/// and are not recorded, so they can be retried after conditions change.
///
/// Single-threaded by contract; callers synchronize concurrent access.
class AccountLedger
{
public:
using Limits = LedgerLimits;
struct AccountState {
std::string owner;
LedgerQuantity balance{0};
LedgerQuantity capacity{
std::numeric_limits<LedgerQuantity>::max()};
[[nodiscard]] auto
operator<=>(const AccountState&) const noexcept = default;
[[nodiscard]] bool
operator==(const AccountState&) const noexcept = default;
};
struct OperationState {
/// Normalized (aggregated and sorted) debits of the reservation.
std::vector<LedgerDebit> sources;
ReservationPhase phase{ReservationPhase::held};
LedgerAccountKey destination;
[[nodiscard]] auto
operator<=>(const OperationState&) const noexcept = default;
[[nodiscard]] bool
operator==(const OperationState&) const noexcept = default;
};
struct State {
std::map<LedgerAccountKey, AccountState> accounts;
std::map<LedgerOperationId, OperationState> operations;
[[nodiscard]] auto
operator<=>(const State&) const noexcept = default;
[[nodiscard]] bool
operator==(const State&) const noexcept = default;
};
explicit AccountLedger(Limits limits = Limits{}) : limits_(limits) {}
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
[[nodiscard]] bool create_account(const LedgerAccountKey& key,
std::string owner,
LedgerQuantity balance = 0,
LedgerQuantity capacity =
std::numeric_limits<
LedgerQuantity>::max())
{
if (balance > capacity ||
accounts_.size() >= limits_.max_accounts ||
accounts_.contains(key)) {
return false;
}
accounts_.emplace(key,
AccountState{.owner = std::move(owner),
.balance = balance,
.capacity = capacity});
return true;
}
[[nodiscard]] bool set_capacity(const LedgerAccountKey& key,
LedgerQuantity capacity)
{
const auto found = accounts_.find(key);
if (found == accounts_.end() ||
found->second.balance > capacity) {
return false;
}
found->second.capacity = capacity;
return true;
}
[[nodiscard]] std::optional<AccountState>
account(const LedgerAccountKey& key) const
{
const auto found = accounts_.find(key);
if (found == accounts_.end()) {
return std::nullopt;
}
return found->second;
}
/// Sum of all balances plus quantities held in reservations.
[[nodiscard]] LedgerQuantity total() const
{
LedgerQuantity sum = 0;
for (const auto& [key, account] : accounts_) {
(void)key;
sum += account.balance;
}
for (const auto& [id, operation] : operations_) {
(void)id;
if (operation.phase == ReservationPhase::held) {
for (const auto& debit : operation.sources) {
sum += debit.quantity;
}
}
}
return sum;
}
[[nodiscard]] std::size_t account_count() const noexcept
{
return accounts_.size();
}
[[nodiscard]] std::size_t operation_count() const noexcept
{
return operations_.size();
}
/// Atomically debit every source into a held reservation.
[[nodiscard]] LedgerResult
reserve(const LedgerOperationId& operation,
std::vector<LedgerDebit> debits)
{
for (const auto& debit : debits) {
if (debit.account.empty() || debit.quantity == 0) {
return LedgerResult{.status = LedgerStatus::invalid_state,
.operation = operation};
}
}
auto normalized = normalize(std::move(debits));
if (!normalized.has_value()) {
return LedgerResult{.status = LedgerStatus::overflow,
.operation = operation};
}
if (const auto existing = operations_.find(operation);
existing != operations_.end()) {
if (existing->second.sources != *normalized) {
return LedgerResult{.status = LedgerStatus::invalid_state,
.phase = existing->second.phase,
.operation = operation};
}
return LedgerResult{.status = LedgerStatus::replayed,
.phase = existing->second.phase,
.operation = operation};
}
if (operations_.size() >= limits_.max_operations) {
return LedgerResult{.status = LedgerStatus::limit_exceeded,
.operation = operation};
}
for (const auto& debit : *normalized) {
const auto found = accounts_.find(debit.account);
if (found == accounts_.end()) {
return LedgerResult{
.status = LedgerStatus::unknown_account,
.operation = operation};
}
if (found->second.balance < debit.quantity) {
return LedgerResult{
.status = LedgerStatus::insufficient_balance,
.operation = operation};
}
}
// All preconditions hold: apply every debit.
for (const auto& debit : *normalized) {
accounts_.at(debit.account).balance -= debit.quantity;
}
operations_.emplace(operation,
OperationState{.sources = std::move(*normalized),
.phase = ReservationPhase::held,
.destination = {}});
return LedgerResult{.status = LedgerStatus::committed,
.phase = ReservationPhase::held,
.operation = operation};
}
/// Return a held reservation to its sources. Ownership is unchanged.
[[nodiscard]] LedgerResult release(const LedgerOperationId& operation)
{
const auto found = operations_.find(operation);
if (found == operations_.end()) {
return LedgerResult{.status = LedgerStatus::unknown_operation,
.operation = operation};
}
if (found->second.phase == ReservationPhase::released) {
return LedgerResult{.status = LedgerStatus::replayed,
.phase = ReservationPhase::released,
.operation = operation};
}
if (found->second.phase == ReservationPhase::delivered) {
return LedgerResult{
.status = LedgerStatus::invalid_state,
.phase = ReservationPhase::delivered,
.operation = operation};
}
for (const auto& debit : found->second.sources) {
accounts_.at(debit.account).balance += debit.quantity;
}
found->second.phase = ReservationPhase::released;
return LedgerResult{.status = LedgerStatus::committed,
.phase = ReservationPhase::released,
.operation = operation};
}
/// Deliver a held reservation to `destination` (the next owner).
/// On capacity/overflow failure nothing changes and the reservation
/// stays held, so the caller can retry or release it.
[[nodiscard]] LedgerResult
transfer(const LedgerOperationId& operation,
const LedgerAccountKey& destination)
{
const auto found = operations_.find(operation);
if (found == operations_.end()) {
return LedgerResult{.status = LedgerStatus::unknown_operation,
.operation = operation};
}
if (found->second.phase == ReservationPhase::released) {
return LedgerResult{.status = LedgerStatus::released,
.phase = ReservationPhase::released,
.operation = operation};
}
if (found->second.phase == ReservationPhase::delivered) {
return LedgerResult{
.status = found->second.destination == destination
? LedgerStatus::replayed
: LedgerStatus::invalid_state,
.phase = ReservationPhase::delivered,
.operation = operation};
}
const auto target = accounts_.find(destination);
if (target == accounts_.end()) {
return LedgerResult{.status = LedgerStatus::unknown_account,
.phase = ReservationPhase::held,
.operation = operation};
}
LedgerQuantity quantity = 0;
for (const auto& debit : found->second.sources) {
if (debit.quantity >
std::numeric_limits<LedgerQuantity>::max() - quantity) {
return LedgerResult{.status = LedgerStatus::overflow,
.phase = ReservationPhase::held,
.operation = operation};
}
quantity += debit.quantity;
}
if (quantity >
target->second.capacity - target->second.balance) {
return LedgerResult{.status = LedgerStatus::capacity_exhausted,
.phase = ReservationPhase::held,
.operation = operation};
}
target->second.balance += quantity;
found->second.phase = ReservationPhase::delivered;
found->second.destination = destination;
return LedgerResult{.status = LedgerStatus::committed,
.phase = ReservationPhase::delivered,
.operation = operation};
}
[[nodiscard]] State save() const
{
return State{.accounts = accounts_, .operations = operations_};
}
/// Rebuild a ledger from `save()` output. Rejects states that violate
/// the limits or the balance/capacity and reservation invariants.
[[nodiscard]] static std::optional<AccountLedger>
restore(State state, Limits limits = Limits{})
{
if (state.accounts.size() > limits.max_accounts ||
state.operations.size() > limits.max_operations) {
return std::nullopt;
}
for (const auto& [key, account] : state.accounts) {
(void)key;
if (account.balance > account.capacity) {
return std::nullopt;
}
}
for (const auto& [id, operation] : state.operations) {
(void)id;
if (operation.sources.empty()) {
return std::nullopt;
}
for (const auto& debit : operation.sources) {
if (!state.accounts.contains(debit.account)) {
return std::nullopt;
}
}
if (operation.phase == ReservationPhase::delivered &&
!state.accounts.contains(operation.destination)) {
return std::nullopt;
}
}
AccountLedger ledger{limits};
ledger.accounts_ = std::move(state.accounts);
ledger.operations_ = std::move(state.operations);
return ledger;
}
private:
[[nodiscard]] static std::optional<std::vector<LedgerDebit>>
normalize(std::vector<LedgerDebit> debits)
{
std::map<LedgerAccountKey, LedgerQuantity> aggregated;
for (const auto& debit : debits) {
LedgerQuantity& sum = aggregated[debit.account];
if (debit.quantity >
std::numeric_limits<LedgerQuantity>::max() - sum) {
return std::nullopt;
}
sum += debit.quantity;
}
std::vector<LedgerDebit> normalized;
normalized.reserve(aggregated.size());
for (auto& [account, quantity] : aggregated) {
normalized.push_back(
LedgerDebit{.account = std::move(account),
.quantity = quantity});
}
return normalized;
}
Limits limits_{};
std::map<LedgerAccountKey, AccountState> accounts_;
std::map<LedgerOperationId, OperationState> operations_;
};
} // namespace Void::Containers
+323
View File
@@ -0,0 +1,323 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <set>
#include <span>
#include <utility>
#include <vector>
namespace Void::Containers
{
/// Finite sparse 3D page table with revision-checked atomic edit batches.
///
/// Cells are grouped into fixed `PageSize`-cubed pages. Pages are allocated on
/// demand (a missing page reads as `empty` with revision 0) and bounded by
/// `Limits::max_pages`. `apply` validates every precondition, budget and
/// revision before touching the table; on failure nothing changes.
///
/// Batch semantics:
/// - Duplicate cell addresses in one batch are rejected.
/// - An edit whose value equals the current cell does not allocate a page and
/// does not bump a revision.
/// - `expected_revision` is checked against the page revision at batch start
/// (0 for a missing page).
/// - A changed page whose revision is already the maximum fails the batch.
/// - The result lists changed pages sorted by page identity with their new
/// revisions.
///
/// Single-threaded by contract; callers synchronize concurrent access.
template <typename Cell, std::size_t PageSize = 32> class SparsePageTable
{
public:
static_assert(PageSize > 0);
static constexpr std::size_t kPageSize = PageSize;
static constexpr std::size_t kCellsPerPage =
PageSize * PageSize * PageSize;
using Revision = std::uint64_t;
struct PageId {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const PageId&) const noexcept = default;
[[nodiscard]] bool
operator==(const PageId&) const noexcept = default;
};
struct CellAddress {
std::int64_t x{0};
std::int64_t y{0};
std::int64_t z{0};
[[nodiscard]] auto
operator<=>(const CellAddress&) const noexcept = default;
[[nodiscard]] bool
operator==(const CellAddress&) const noexcept = default;
};
struct Edit {
CellAddress address;
Cell value;
std::optional<Revision> expected_revision{};
[[nodiscard]] bool
operator==(const Edit&) const = default;
};
struct Limits {
std::size_t max_pages{1024};
};
enum class EditStatus : std::uint8_t {
committed = 0,
/// A page's expected revision did not match the current one.
stale_revision,
/// A changed page already has the maximum revision.
revision_exhausted,
/// The batch would allocate more pages than the budget allows.
page_budget_exceeded,
/// The same cell address appears twice in the batch.
duplicate_edit,
};
struct ChangedPage {
PageId page;
Revision revision{0};
[[nodiscard]] bool
operator==(const ChangedPage&) const = default;
};
struct EditResult {
EditStatus status{EditStatus::committed};
std::vector<ChangedPage> changed{};
[[nodiscard]] bool committed() const noexcept
{
return status == EditStatus::committed;
}
};
struct PageState {
PageId page;
Revision revision{0};
std::array<Cell, kCellsPerPage> cells{};
[[nodiscard]] bool operator==(const PageState&) const = default;
};
struct State {
std::vector<PageState> pages;
[[nodiscard]] bool operator==(const State&) const = default;
};
explicit SparsePageTable(Limits limits = Limits{},
Cell empty = Cell{})
: limits_(limits)
, empty_(std::move(empty))
{
}
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
[[nodiscard]] const Cell& empty_value() const noexcept
{
return empty_;
}
[[nodiscard]] std::size_t page_count() const noexcept
{
return pages_.size();
}
/// Cell value; a missing page yields `empty_value()`.
[[nodiscard]] Cell get(CellAddress address) const
{
const auto [id, offset] = locate(address);
const auto found = pages_.find(id);
if (found == pages_.end()) {
return empty_;
}
return found->second.cells[offset];
}
/// Page revision, or `nullopt` when the page is not allocated.
[[nodiscard]] std::optional<Revision>
page_revision(PageId page) const
{
const auto found = pages_.find(page);
if (found == pages_.end()) {
return std::nullopt;
}
return found->second.revision;
}
/// Apply all edits or none.
[[nodiscard]] EditResult apply(std::span<const Edit> edits)
{
if (edits.empty()) {
return EditResult{};
}
std::set<CellAddress> seen;
std::map<PageId, std::vector<const Edit*>> grouped;
for (const auto& edit : edits) {
if (!seen.insert(edit.address).second) {
return EditResult{.status =
EditStatus::duplicate_edit};
}
grouped[page_of(edit.address)].push_back(&edit);
}
std::map<PageId, bool> changes;
std::size_t new_pages = 0;
for (const auto& [id, page_edits] : grouped) {
const auto found = pages_.find(id);
const Page* page =
found == pages_.end() ? nullptr : &found->second;
const Revision revision = page == nullptr ? 0
: page->revision;
for (const Edit* edit : page_edits) {
if (edit->expected_revision.has_value() &&
*edit->expected_revision != revision) {
return EditResult{
.status = EditStatus::stale_revision};
}
}
bool changed = false;
for (const Edit* edit : page_edits) {
const auto offset = offset_of(edit->address);
const Cell& current =
page == nullptr ? empty_ : page->cells[offset];
if (!(current == edit->value)) {
changed = true;
break;
}
}
if (!changed) {
continue;
}
if (revision ==
std::numeric_limits<Revision>::max()) {
return EditResult{
.status = EditStatus::revision_exhausted};
}
changes.emplace(id, true);
if (page == nullptr) {
++new_pages;
}
}
if (pages_.size() + new_pages > limits_.max_pages) {
return EditResult{.status =
EditStatus::page_budget_exceeded};
}
EditResult result;
for (const auto& [id, changed] : changes) {
(void)changed;
auto& page = pages_[id];
for (const Edit* edit : grouped.at(id)) {
page.cells[offset_of(edit->address)] = edit->value;
}
++page.revision;
result.changed.push_back(
ChangedPage{.page = id, .revision = page.revision});
}
return result;
}
[[nodiscard]] State save() const
{
State state;
state.pages.reserve(pages_.size());
for (const auto& [id, page] : pages_) {
state.pages.push_back(PageState{
.page = id, .revision = page.revision, .cells = page.cells});
}
return state;
}
/// Restore saved pages. Rejects duplicate page ids, more pages than the
/// limit, or a page with no revision left for an edit.
[[nodiscard]] static std::optional<SparsePageTable>
restore(State state, Limits limits = Limits{},
Cell empty = Cell{})
{
if (state.pages.size() > limits.max_pages) {
return std::nullopt;
}
SparsePageTable table{limits, std::move(empty)};
for (auto& saved : state.pages) {
if (!table.pages_
.emplace(saved.page,
Page{.cells = saved.cells,
.revision = saved.revision})
.second) {
return std::nullopt;
}
}
return table;
}
private:
struct Page {
std::array<Cell, kCellsPerPage> cells{};
Revision revision{0};
};
[[nodiscard]] static std::pair<std::int64_t, std::size_t>
split(std::int64_t coordinate)
{
constexpr auto size = static_cast<std::int64_t>(PageSize);
std::int64_t page = coordinate / size;
std::int64_t offset = coordinate % size;
if (offset < 0) {
--page;
offset += size;
}
return {page, static_cast<std::size_t>(offset)};
}
[[nodiscard]] static PageId page_of(CellAddress address)
{
return PageId{.x = split(address.x).first,
.y = split(address.y).first,
.z = split(address.z).first};
}
[[nodiscard]] static std::size_t offset_of(CellAddress address)
{
const auto [px, ox] = split(address.x);
const auto [py, oy] = split(address.y);
const auto [pz, oz] = split(address.z);
(void)px;
(void)py;
(void)pz;
return (oz * PageSize + oy) * PageSize + ox;
}
[[nodiscard]] static std::pair<PageId, std::size_t>
locate(CellAddress address)
{
return {page_of(address), offset_of(address)};
}
Limits limits_{};
Cell empty_{};
std::map<PageId, Page> pages_;
};
} // namespace Void::Containers
+3 -1
View File
@@ -253,7 +253,9 @@ namespace Void::Meta
out += "?";
}
out += '{';
bool first = true;
// Reflectable types with no members (e.g. std::optional) leave this
// unread; the diagnostic is about a deliberately empty loop body.
[[maybe_unused]] bool first = true;
template for (constexpr auto m : members_v<T>)
{
if (!first) {
+280
View File
@@ -0,0 +1,280 @@
#pragma once
#include <atomic>
#include <compare>
#include <cstdint>
#include <memory>
#include <optional>
#include <utility>
#if !defined(__cpp_lib_atomic_shared_ptr)
#include <mutex>
#endif
namespace Void::Core
{
/// Identity of a published snapshot: an epoch (session/domain) and a revision
/// that increases within that epoch.
struct PublicationVersion {
std::uint64_t epoch{0};
std::uint64_t revision{0};
[[nodiscard]] auto operator<=>(const PublicationVersion&) const noexcept =
default;
[[nodiscard]] bool
operator==(const PublicationVersion&) const noexcept = default;
};
/// Single-writer, multi-reader publication of immutable values.
///
/// A producer prepares a complete immutable value and calls `publish` with its
/// version; readers call `acquire` and keep the returned `Snapshot` alive for
/// as long as they need a coherent view. Publishing swaps one fully built state
/// atomically: a reader sees either the previous or the next snapshot, never a
/// mixture, and a retained snapshot stays valid across any number of later
/// publications.
///
/// `publish` is compare-and-publish: when `expected_epoch` is supplied it must
/// equal the current epoch, and the new version must advance the current one
/// (higher epoch, or same epoch with a higher revision). A rejected publish
/// leaves the last good publication untouched, so a failed preparation that
/// never calls `publish` cannot corrupt readers.
///
/// The value is released when the publication and the last reader holding it
/// drop their snapshots.
template <typename T> class Publication
{
private:
struct State {
std::shared_ptr<const T> value;
PublicationVersion version;
};
public:
using Value = T;
/// Retained, immutable view of one publication.
class Snapshot
{
public:
Snapshot() noexcept = default;
[[nodiscard]] explicit operator bool() const noexcept
{
return state_ != nullptr && state_->value != nullptr;
}
[[nodiscard]] const T& operator*() const noexcept
{
return *state_->value;
}
[[nodiscard]] const T* operator->() const noexcept
{
return state_->value.get();
}
[[nodiscard]] const T* get() const noexcept
{
return state_ != nullptr ? state_->value.get()
: nullptr;
}
[[nodiscard]] PublicationVersion version() const noexcept
{
return state_ != nullptr ? state_->version
: PublicationVersion{};
}
private:
friend class Publication;
explicit Snapshot(std::shared_ptr<const State> state) noexcept
: state_(std::move(state))
{
}
std::shared_ptr<const State> state_{};
};
enum class PublishStatus : std::uint8_t {
published = 0,
/// The supplied or expected epoch is obsolete.
stale_epoch,
/// Same epoch, but the revision does not advance.
stale_revision,
/// The value is null.
invalid_value,
};
struct PublishResult {
PublishStatus status{PublishStatus::invalid_value};
PublicationVersion version{};
[[nodiscard]] bool published() const noexcept
{
return status == PublishStatus::published;
}
};
explicit Publication(std::shared_ptr<const T> initial,
PublicationVersion version = {})
: current_{std::make_shared<State>(
State{std::move(initial), version})}
{
}
Publication(const Publication&) = delete;
Publication& operator=(const Publication&) = delete;
/// Current snapshot; the returned handle keeps the value alive.
[[nodiscard]] Snapshot acquire() const
{
return Snapshot{
current_.load(std::memory_order_acquire)};
}
[[nodiscard]] PublicationVersion version() const
{
return current_.load(std::memory_order_acquire)->version;
}
[[nodiscard]] std::uint64_t epoch() const
{
return version().epoch;
}
/// The version that `publish_next` would use: same epoch, next revision.
[[nodiscard]] PublicationVersion next_version() const
{
PublicationVersion next = version();
++next.revision;
return next;
}
/// Publish `value` as `next`, optionally requiring `expected_epoch`.
///
/// The whole state (value and version) is swapped with one atomic
/// compare-exchange; on rejection nothing changes.
[[nodiscard]] PublishResult
publish(std::shared_ptr<const T> value,
PublicationVersion next,
std::optional<std::uint64_t> expected_epoch = std::nullopt)
{
if (value == nullptr) {
return PublishResult{.status = PublishStatus::invalid_value,
.version = version()};
}
std::shared_ptr<State> current =
current_.load(std::memory_order_acquire);
for (;;) {
const PublicationVersion& observed = current->version;
if (expected_epoch.has_value() &&
*expected_epoch != observed.epoch) {
return PublishResult{.status = PublishStatus::stale_epoch,
.version = observed};
}
if (next.epoch < observed.epoch) {
return PublishResult{.status = PublishStatus::stale_epoch,
.version = observed};
}
if (next.epoch == observed.epoch &&
next.revision <= observed.revision) {
return PublishResult{
.status = PublishStatus::stale_revision,
.version = observed};
}
std::shared_ptr<State> desired =
std::make_shared<State>(State{value, next});
if (current_.compare_exchange_weak(
current,
std::move(desired),
std::memory_order_acq_rel,
std::memory_order_acquire)) {
return PublishResult{.status = PublishStatus::published,
.version = next};
}
// `current` now holds the state that won the race; retry the
// validation and the exchange against it.
}
}
/// Convenience for the common case: same epoch, next revision.
[[nodiscard]] PublishResult
publish_next(std::shared_ptr<const T> value,
std::optional<std::uint64_t> expected_epoch =
std::nullopt)
{
return publish(std::move(value), next_version(), expected_epoch);
}
/// Start a new epoch at revision 0, optionally requiring the previous
/// epoch.
[[nodiscard]] PublishResult
publish_epoch(std::shared_ptr<const T> value,
std::uint64_t epoch,
std::optional<std::uint64_t> expected_epoch =
std::nullopt)
{
return publish(std::move(value),
PublicationVersion{.epoch = epoch, .revision = 0},
expected_epoch);
}
private:
#if defined(__cpp_lib_atomic_shared_ptr)
std::atomic<std::shared_ptr<State>> current_;
#else
// Older libc++ (e.g. Emscripten) does not implement the
// atomic<shared_ptr> specialization. Keep the same load /
// compare-exchange surface with a mutex-protected pointer; the
// publication is still coherent for single-writer/multi-reader use.
class AtomicStatePtr
{
public:
explicit AtomicStatePtr(std::shared_ptr<State> initial)
: current_(std::move(initial))
{
}
[[nodiscard]] std::shared_ptr<State>
load(std::memory_order) const
{
std::lock_guard lock{mutex_};
return current_;
}
bool compare_exchange_weak(std::shared_ptr<State>& expected,
std::shared_ptr<State> desired,
std::memory_order,
std::memory_order)
{
std::lock_guard lock{mutex_};
if (current_ != expected) {
expected = current_;
return false;
}
current_ = std::move(desired);
return true;
}
private:
mutable std::mutex mutex_;
std::shared_ptr<State> current_;
};
AtomicStatePtr current_;
#endif
};
} // namespace Void::Core
+183
View File
@@ -0,0 +1,183 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <optional>
namespace Void::Core
{
enum class SequenceErrorKind : std::uint8_t {
/// The requested id or batch does not fit in the remaining range.
exhausted = 0,
/// A batch of zero ids was requested.
zero_count,
/// The supplied saved state is not a valid sequence state.
invalid_state,
};
struct SequenceError {
SequenceErrorKind kind{SequenceErrorKind::exhausted};
/// How many ids were still available when the request failed.
std::uint64_t available{0};
};
/// Instance-owned, restorable id sequence with checked exhaustion.
///
/// Unlike `Void::Counted::SeqId<Tag>` (one process-wide atomic per tag), each
/// `IdSequence` owns its own state. It can be copied at a completed boundary,
/// saved and restored, and several instances (e.g. two worlds in one process)
/// allocate independently.
///
/// Ids start at 1. A removed record never gives its id back: the high-water
/// mark only moves forward, including across save/restore. `next()` and
/// `next_batch()` return `exhausted` *before* changing state when the request
/// does not fit, so a failed allocation leaves both the sequence and any
/// application record untouched.
///
/// `Rep` is the fixed-width representation used in saved state (default
/// `std::uint64_t`), making cross-platform saves reproducible. `Tag` keeps
/// unrelated id domains from being confused at compile time.
///
/// The class is not thread-safe; callers synchronize concurrent access to one
/// instance.
template <typename Tag = void, typename Rep = std::uint64_t> class IdSequence
{
public:
using value_type = Rep;
/// Serializable position. `exhausted` distinguishes "max is still
/// available" (`next == max`) from "max was already handed out".
struct State {
value_type next{1};
bool exhausted{false};
[[nodiscard]] auto
operator<=>(const State&) const noexcept = default;
[[nodiscard]] bool
operator==(const State&) const noexcept = default;
};
struct Batch {
value_type first{0};
value_type count{0};
};
constexpr IdSequence() noexcept = default;
explicit constexpr IdSequence(value_type first) noexcept
: state_{.next = first == 0 ? value_type{1} : first}
{
}
/// Allocate one id.
[[nodiscard]] std::expected<value_type, SequenceError> next()
{
if (state_.exhausted) {
return fail(SequenceErrorKind::exhausted);
}
const value_type id = state_.next;
if (id == maximum()) {
state_.exhausted = true;
} else {
state_.next = static_cast<value_type>(id + 1);
}
return id;
}
/// Reserve a contiguous batch atomically: either all `count` ids are
/// reserved or none are.
[[nodiscard]] std::expected<Batch, SequenceError>
next_batch(std::size_t count)
{
if (count == 0) {
return fail(SequenceErrorKind::zero_count);
}
if (state_.exhausted) {
return fail(SequenceErrorKind::exhausted);
}
const auto remaining = static_cast<std::uintmax_t>(available());
if (static_cast<std::uintmax_t>(count) > remaining) {
return fail(SequenceErrorKind::exhausted);
}
const value_type first = state_.next;
const auto step = static_cast<value_type>(count);
if (static_cast<std::uintmax_t>(step) == remaining) {
state_.exhausted = true;
} else {
state_.next = static_cast<value_type>(first + step);
}
return Batch{.first = first, .count = step};
}
/// How many ids can still be allocated.
[[nodiscard]] value_type available() const noexcept
{
if (state_.exhausted) {
return 0;
}
return static_cast<value_type>(maximum() - state_.next + 1);
}
[[nodiscard]] bool exhausted() const noexcept
{
return state_.exhausted;
}
/// The next id that would be handed out (or max once exhausted).
[[nodiscard]] value_type peek() const noexcept { return state_.next; }
/// Highest id ever handed out (0 before the first allocation).
[[nodiscard]] value_type high_water() const noexcept
{
if (state_.exhausted) {
return maximum();
}
return state_.next == 1 ? value_type{0}
: static_cast<value_type>(state_.next - 1);
}
[[nodiscard]] State state() const noexcept { return state_; }
/// Restore a saved state. Rejects non-canonical or impossible states;
/// on success the sequence continues exactly after the saved position.
[[nodiscard]] static std::expected<IdSequence, SequenceError>
restore(State state)
{
if (state.next == 0) {
return std::unexpected{SequenceError{
.kind = SequenceErrorKind::invalid_state, .available = 0}};
}
if (state.exhausted && state.next != maximum()) {
return std::unexpected{SequenceError{
.kind = SequenceErrorKind::invalid_state,
.available = 0}};
}
IdSequence sequence;
sequence.state_ = state;
return sequence;
}
[[nodiscard]] static constexpr value_type maximum() noexcept
{
return std::numeric_limits<value_type>::max();
}
private:
[[nodiscard]] std::unexpected<SequenceError>
fail(SequenceErrorKind kind) const
{
return std::unexpected{SequenceError{
.kind = kind,
.available = static_cast<std::uint64_t>(available())}};
}
State state_{};
};
} // namespace Void::Core
+72
View File
@@ -5,6 +5,7 @@
#include <Void/Functional/Result.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <span>
@@ -46,6 +47,16 @@ namespace Void::Crypto
/// error. Backend update/finalize failures poison the hasher.
[[nodiscard]] Void::Result::Result<Digest> finalize();
/// Serialize the in-progress state for resumable hashing. Available
/// on the built-in backend; the OpenSSL provider has no portable
/// state export and returns unsupported_algorithm.
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
export_state() const;
/// Restore a state produced by export_state() on this hasher.
[[nodiscard]] Void::Result::Result<void>
import_state(std::span<const std::byte> state);
private:
struct Impl;
@@ -166,6 +177,48 @@ namespace Void::Crypto
const Ed25519PublicKey& public_key,
const ProviderOptions& provider = {});
/// Convenience key pair returned by ed25519_keypair(). The secret seed is
/// a move-only, self-wiping handle; prefer the typed Ed25519PrivateKey APIs
/// when the key can stay inside an owning handle.
struct Ed25519KeyPair {
Ed25519Seed secret_key;
Ed25519PublicKey public_key;
};
/// Generate a fresh Ed25519 key pair. Requires the OpenSSL backend.
[[nodiscard]] Void::Result::Result<Ed25519KeyPair>
ed25519_keypair(const ProviderOptions& provider = {});
/// Sign exact message bytes with a 32-byte Ed25519 seed/secret key. The
/// temporary private-key handle is wiped when it goes out of scope; prefer
/// sign_ed25519() when the caller already owns an Ed25519PrivateKey.
[[nodiscard]] Void::Result::Result<Ed25519Signature>
ed25519_sign(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Verify a detached Ed25519 signature over exact message bytes.
/// Malformed key/signature sizes are errors; a well-formed but invalid
/// signature returns false.
[[nodiscard]] Void::Result::Result<bool>
ed25519_verify(std::span<const std::byte> public_key,
std::span<const std::byte> message,
std::span<const std::byte> signature,
const ProviderOptions& provider = {});
/// Compute HMAC-SHA-1 (RFC 2104) into a caller-owned 20-byte buffer.
/// Wipes output on backend failure and rejects overlapping buffers.
[[nodiscard]] Void::Result::Result<void>
hmac_sha1_into(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
hmac_sha1(std::span<const std::byte> secret_key,
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer.
/// Wipes output on backend failure and rejects overlapping buffers.
[[nodiscard]] Void::Result::Result<void>
@@ -179,6 +232,25 @@ namespace Void::Crypto
std::span<const std::byte> message,
const ProviderOptions& provider = {});
/// Derive key material with RFC 8018 PBKDF2-HMAC-SHA-256 into a
/// caller-owned buffer. iterations must be 1..kMaxPbkdf2Iterations, salt
/// at most kMaxPbkdf2SaltBytes and output 1..kMaxPbkdf2OutputBytes.
/// Rejects overlapping buffers and wipes output on any failure after
/// validation.
[[nodiscard]] Void::Result::Result<void>
pbkdf2_hmac_sha256_into(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::span<std::byte> output,
const ProviderOptions& provider = {});
[[nodiscard]] Void::Result::Result<Digest>
pbkdf2_hmac_sha256(std::span<const std::byte> password,
std::span<const std::byte> salt,
std::uint32_t iterations,
std::size_t output_length,
const ProviderOptions& provider = {});
/// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned
/// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping
/// buffers and wipes secret_output on any failure after validation.
+6 -1
View File
@@ -16,12 +16,16 @@ namespace Void::Crypto
inline constexpr std::size_t Ed25519PublicKeySize = 32;
inline constexpr std::size_t Ed25519SignatureSize = 64;
inline constexpr std::size_t Ed25519SeedSize = 32;
inline constexpr std::size_t HmacSha1Size = 20;
inline constexpr std::size_t HmacSha256Size = 32;
struct CryptoLimits {
static constexpr std::size_t kMaxOneShotMessageBytes =
16ULL * 1024ULL * 1024ULL;
static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL;
static constexpr std::uint32_t kMaxPbkdf2Iterations = 10'000'000U;
static constexpr std::size_t kMaxPbkdf2SaltBytes = 64ULL * 1024ULL;
static constexpr std::size_t kMaxPbkdf2OutputBytes = 1024ULL;
static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL;
static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8;
static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32;
@@ -256,7 +260,8 @@ namespace Void::Crypto
ed25519_sign,
ed25519_verify,
hmac,
hkdf
hkdf,
pbkdf2
};
struct FaultConfig {
+60 -5
View File
@@ -347,8 +347,17 @@ namespace Void::Data::Toml
};
struct ParseOptions {
/// Maximum nesting level reached from the document root. It is
/// enforced uniformly for values (arrays, inline tables), dotted key
/// paths, table headers and array-of-tables headers.
std::size_t max_depth{64};
std::size_t max_input_bytes{16ULL * 1024ULL * 1024ULL};
/// Maximum number of document nodes (table entries, array elements
/// and array-of-tables entries plus their tables). Zero disables the
/// limit, preserving the historical behaviour. `max_input_bytes`
/// already bounds node count linearly; this knob bounds the constant
/// memory factor for untrusted input.
std::size_t max_nodes{0};
};
namespace Detail
@@ -534,7 +543,7 @@ namespace Void::Data::Toml
parse_table_header(doc);
} else {
parse_key_value_into(*current_table_, *current_meta_,
false, 0U);
false, table_depth_);
skip_ws();
skip_comment_to_eol();
if (pos_ < input_.size() && !consume_newline()) {
@@ -914,11 +923,19 @@ namespace Void::Data::Toml
return KeyPart{std::move(bare), start};
}
[[nodiscard]] std::vector<KeyPart> parse_key_path()
/// Parse a dotted key path, rejecting it as soon as it grows past
/// `max_segments`. Checking while parsing keeps a pathologically
/// long path from being materialised before the depth limit applies.
[[nodiscard]] std::vector<KeyPart>
parse_key_path(std::size_t max_segments)
{
std::vector<KeyPart> path;
path.push_back(parse_simple_key());
while (true) {
if (path.size() > max_segments) {
fail("key path exceeds max_depth",
path.back().origin);
}
skip_ws();
if (pos_ < input_.size() && input_[pos_] == '.') {
(void)advance_byte();
@@ -931,6 +948,32 @@ namespace Void::Data::Toml
return path;
}
/// A dotted key of N segments nests its value N-1 levels below the
/// current base depth, so it may hold one more segment than a table
/// header at the same limit.
[[nodiscard]] std::size_t
key_path_budget(std::size_t depth) const noexcept
{
if (depth > options_.max_depth) {
return 0;
}
const std::size_t remaining = options_.max_depth - depth;
if (remaining == std::numeric_limits<std::size_t>::max()) {
return remaining;
}
return remaining + 1U;
}
void note_node()
{
++node_count_;
if (options_.max_nodes != 0 &&
node_count_ > options_.max_nodes) {
fail(std::format("TOML document exceeds max_nodes ({})",
options_.max_nodes));
}
}
void parse_table_header(Document& doc)
{
const Origin hdr_origin = here();
@@ -941,7 +984,8 @@ namespace Void::Data::Toml
(void)advance_byte();
}
skip_ws();
auto path = parse_key_path();
auto path = parse_key_path(options_.max_depth);
table_depth_ = path.size();
skip_ws();
if (pos_ >= input_.size() || input_[pos_] != ']') {
fail("expected ']' closing table header", hdr_origin);
@@ -975,6 +1019,7 @@ namespace Void::Data::Toml
auto [mit, mok] = cur_meta->children.emplace(
seg.name, std::move(meta_ptr));
static_cast<void>(mok);
note_node();
cur_tbl = it->second.as_table();
cur_meta = mit->second.get();
} else {
@@ -1014,6 +1059,7 @@ namespace Void::Data::Toml
auto [mit, mok] = cur_meta->children.emplace(
leaf.name, std::move(meta_ptr));
static_cast<void>(mok);
note_node();
current_table_ = it->second.as_table();
current_meta_ = mit->second.get();
return;
@@ -1046,6 +1092,8 @@ namespace Void::Data::Toml
MetaNode* next_meta = meta_ptr->aot_items.back().get();
cur_meta->children.emplace(leaf.name,
std::move(meta_ptr));
note_node(); // the array-of-tables value
note_node(); // its first table
current_table_ =
&it->second.as_array_of_tables()->tables.back();
current_meta_ = next_meta;
@@ -1061,6 +1109,7 @@ namespace Void::Data::Toml
}
auto* aot = existing->as_array_of_tables();
aot->tables.push_back(Table{});
note_node();
auto elem_meta = std::make_unique<MetaNode>();
elem_meta->state = NodeState::ExplicitTable;
leaf_meta->aot_items.push_back(std::move(elem_meta));
@@ -1072,14 +1121,15 @@ namespace Void::Data::Toml
void parse_key_value_into(Table& root_tbl, MetaNode& root_meta,
bool in_inline, std::size_t depth)
{
auto path = parse_key_path();
auto path = parse_key_path(key_path_budget(depth));
const std::size_t value_depth = depth + path.size() - 1U;
skip_ws();
if (pos_ >= input_.size() || input_[pos_] != '=') {
fail("expected '=' after key");
}
(void)advance_byte();
skip_ws();
Value val = parse_value(depth);
Value val = parse_value(value_depth);
Table* cur_tbl = &root_tbl;
MetaNode* cur_meta = &root_meta;
@@ -1097,6 +1147,7 @@ namespace Void::Data::Toml
auto [mit, mok] = cur_meta->children.emplace(
seg.name, std::move(meta_ptr));
static_cast<void>(mok);
note_node();
cur_tbl = it->second.as_table();
cur_meta = mit->second.get();
} else {
@@ -1134,6 +1185,7 @@ namespace Void::Data::Toml
meta_ptr->state = val_state;
cur_meta->children.emplace(leaf.name, std::move(meta_ptr));
cur_tbl->entries.emplace(leaf.name, std::move(val));
note_node();
}
[[nodiscard]] Value parse_value(std::size_t depth)
@@ -1173,6 +1225,7 @@ namespace Void::Data::Toml
return Value{std::move(arr), start};
}
arr.elements.push_back(parse_value(depth + 1U));
note_node();
skip_ws_and_comments(true);
if (pos_ >= input_.size()) {
fail("unterminated array", start);
@@ -1681,6 +1734,8 @@ namespace Void::Data::Toml
MetaNode root_meta_{};
Table* current_table_{nullptr};
MetaNode* current_meta_{nullptr};
std::size_t table_depth_{0};
std::size_t node_count_{0};
};
inline void append_escaped_basic(std::string& out, std::string_view s)
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Types.hpp>
#include <cstddef>
#include <optional>
#include <string>
#include <string_view>
namespace Void::MCP
{
/// Newline-delimited JSON-RPC framing used by the stdio transport
/// (and any custom transport built on a reliable byte stream).
///
/// A frame is one JSON-RPC message followed by `\n`; embedded newlines
/// are not allowed. A trailing `\r` is tolerated before the newline.
class LineFramer
{
public:
explicit LineFramer(McpLimits limits = {});
/// Append bytes from the stream. Fails when the unterminated
/// tail exceeds `limits.max_line_bytes`.
[[nodiscard]] Void::Result::Result<void>
append(std::string_view bytes);
/// Pop the next complete line (without the newline). Empty
/// lines are skipped. `nullopt` means more bytes are needed.
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
next();
[[nodiscard]] std::size_t buffered() const noexcept;
void reset() noexcept;
private:
McpLimits m_limits;
std::string m_buffer;
};
/// One Server-Sent Events event used by Streamable HTTP responses.
struct SseEvent {
std::string event{};
std::string data{};
std::string id{};
};
/// Serialize one SSE event (`event:`/`id:`/`data:` lines terminated by
/// a blank line). Multi-line data is split into multiple `data:` lines.
[[nodiscard]] Void::Result::Result<std::string>
encode_sse_event(const SseEvent& event, const McpLimits& limits = {});
/// Bounded incremental SSE parser. Comment lines and unknown fields
/// are ignored; `data` lines are joined with `\n`.
class SseParser
{
public:
explicit SseParser(McpLimits limits = {});
[[nodiscard]] Void::Result::Result<void>
append(std::string_view bytes);
[[nodiscard]] Void::Result::Result<std::optional<SseEvent>>
next();
[[nodiscard]] std::size_t buffered() const noexcept;
void reset() noexcept;
private:
McpLimits m_limits;
std::string m_buffer;
};
/// Append the stdio frame terminator and validate the line bound.
[[nodiscard]] Void::Result::Result<std::string>
frame_line(std::string_view json, const McpLimits& limits = {});
} // namespace Void::MCP
+88
View File
@@ -0,0 +1,88 @@
#pragma once
#include <Void/Data/StrictJson.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/MCP/Types.hpp>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace Void::MCP
{
using JsonValue = Void::Json::Strict::Value;
/// JSON-RPC request id: null, an integer, or a string.
struct JsonRpcId {
std::variant<std::monostate, std::int64_t, std::string> value{};
[[nodiscard]] bool is_null() const noexcept
{
return std::holds_alternative<std::monostate>(value);
}
[[nodiscard]] bool
operator==(const JsonRpcId&) const noexcept = default;
};
struct ErrorObject {
std::int32_t code{0};
std::string message{};
std::optional<JsonValue> data{};
};
struct Request {
JsonRpcId id{};
std::string method{};
std::optional<JsonValue> params{};
RequestMetadata metadata{};
};
struct Notification {
std::string method{};
std::optional<JsonValue> params{};
RequestMetadata metadata{};
};
struct Response {
JsonRpcId id{};
std::optional<JsonValue> result{};
std::optional<ErrorObject> error{};
};
using Message = std::variant<Request, Notification, Response>;
/// Encode one JSON-RPC message. Request/notification metadata is merged
/// into `params._meta`; responses carry exactly one of result or error.
[[nodiscard]] Void::Result::Result<std::string>
encode_message(const Message& message, const McpLimits& limits = {});
/// Decode exactly one JSON-RPC message, rejecting malformed envelopes,
/// duplicate keys, unknown id types, and limit violations.
[[nodiscard]] Void::Result::Result<Message>
decode_message(std::string_view text, const McpLimits& limits = {});
/// Parse `_meta` metadata out of a params object (or a `_meta` object).
[[nodiscard]] Void::Result::Result<RequestMetadata>
parse_metadata(const JsonValue& params, const McpLimits& limits = {});
/// Build the `_meta` object for a request metadata value.
[[nodiscard]] Void::Result::Result<JsonValue>
metadata_to_json(const RequestMetadata& metadata,
const McpLimits& limits = {});
[[nodiscard]] Void::Result::Result<std::string>
encode_json(const JsonValue& value, const McpLimits& limits = {});
[[nodiscard]] Void::Result::Result<JsonValue>
decode_json(std::string_view text, const McpLimits& limits = {});
/// Error response helper (null id is used for transport-level failures).
[[nodiscard]] Response
make_error_response(const JsonRpcId& id, std::int32_t code,
std::string message,
std::optional<JsonValue> data = {});
} // namespace Void::MCP
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more