Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3f66e0c8c | ||
|
|
60ee28e4ca | ||
|
|
aaeab50758 | ||
|
|
ec8c0bd40a | ||
|
|
0cf187d664 | ||
|
|
65ad9b3f31 |
No files matched your search
@@ -1,8 +1,8 @@
|
||||
# Workflow state
|
||||
|
||||
Updated: 2026-11-27.
|
||||
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave9` (from `main`
|
||||
at `3e25405`, merged Waves 1–8 + `VL-001`..`VL-013` and pushed to `origin/main`).
|
||||
Repository: VoidLibrary; active branch `feat/roadmap-p3-wave10` (from `main`
|
||||
at `65ad9b3`, merged Waves 1–9 + `VL-001`..`VL-013` and pushed to `origin/main`).
|
||||
|
||||
## Completed objective
|
||||
|
||||
@@ -351,9 +351,22 @@ while leaving local untracked files untouched.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w9-asan`, 48 modules, `-Werror`): `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB.
|
||||
- Debug TSan (`/tmp/void-w9-tsan`, `Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`, 22 modules, `-Werror`): `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings.
|
||||
|
||||
### Wave 10 — P3 Core Subsystems: `Discovery`, `Scheduler`, `Messaging` (`feat/roadmap-p3-wave10`)
|
||||
|
||||
- **Specs & Error Domains (`0cf187d`)**: authored `S-DISCOVERY-01-04.md`, `S-SCHEDULER-01-04.md`, `S-MESSAGING-01-04.md`; reserved `kSchedulerErrorDomain = 31` and `kMessagingErrorDomain = 32` (`kDiscoveryErrorDomain = 30` reserved in Wave 9).
|
||||
- **`Discovery` & `DiscoveryRpc` (`ec8c0bd`, `S-DISCOVERY-01..04`)**: NEW zero-external-dep `Void::Discovery` subsystem (`Catalog` with pure thread-free construction, atomic `replace_static()`, provider generation resets, local RAII `Registration` handles with steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` overflow recovery + self-cancel + `SelfJoin` diagnosis, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` endpoint adapter preserving `expected_tls_name` / blocking TLS downgrades while keeping `RPC` independent; `DiscoveryOnly` consumer (`_no_external_deps`).
|
||||
- **`Scheduler` & `SchedulerStorage` (`aaeab50`, `S-SCHEDULER-01..04`)**: NEW zero-external-dep `Void::Scheduler` subsystem (monotonic min-heap ordered by `(due_time, sequence)`, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` with DST gap/fold & unknown-zone rejection without silent UTC fallback, O(1) backward-scanning `CoalesceLatest` over millions of missed slots, 100/pass `CatchUpBounded`, `Forbid`/`QueueOne`/`AllowBounded` overlap, exponential full-jitter retries & dead-letter acknowledgement, revision invalidation watermark, `close_and_join` returning incomplete report on deadline) + durable `Void::SchedulerStorage` (`StorageJobStore` on `Void::Storage::Engine` conditional batches, exclusive owner lock, unique civil-slot dedup, startup `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause without cursor loss); `SchedulerOnly` consumer (`_no_external_deps`).
|
||||
- **`Messaging`, `MessagingStorage`, & `MessagingRpc` (`60ee28e`, `S-MESSAGING-01..04`)**: NEW zero-external-dep `Void::Messaging` subsystem (explicit `PublishDurability::{Memory,Durable}`, `InMemoryQueue` rejecting `Durable`, `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`, competing & `SingleActive` groups, stale-receipt fencing & idempotent repeat ack, bounded retries -> DLQ, corrupt-payload quarantine) + `Void::MessagingStorage` (`StorageQueue` on `Void::Storage::Engine` conditional batches, restart `InFlight -> Pending` generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency ledger refusing silent eviction, `BlockAtQuota` default & clock-health expiry pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`); `MessagingOnly` consumer (`_no_external_deps`).
|
||||
- **Full-suite & sanitizer checks**:
|
||||
- Full integrated RelWithDebInfo (`/tmp/void-w10-full`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly` with `_no_external_deps`); `VoidFoundationBench` (`rev=60ee28e4ca9b`) recorded.
|
||||
- Full Debug ASan+UBSan (`/tmp/void-w10-asan`, 55 modules, `-Werror`): `VoidTests` `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB.
|
||||
- Debug TSan (`/tmp/void-w10-tsan`, `Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`, 23 modules, `-Werror`): `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings.
|
||||
|
||||
## Ownership and next step
|
||||
|
||||
Waves 1–9 (`P0`, `P1`, all `P2` functional modules and `VL-001`..`VL-013`) are
|
||||
complete, verified, and merged to `main` via `--no-ff`. Next roadmap phase:
|
||||
**P3** (new single-node subsystems `Discovery`, `Scheduler`, `Messaging` +
|
||||
`NetworkedApplications` / `ReloadableApplications` platform integrations).
|
||||
Waves 1–10 (`P0`, `P1`, all `P2` modules, `VL-001`..`VL-013`, and P3 core
|
||||
subsystems `Discovery`, `Scheduler`, `Messaging`) are complete, verified, and
|
||||
ready for `--no-ff` merge to `main`. Next wave: **Wave 11 — P3 Completion**
|
||||
(`S-RPC-04..05` WebSocket multiplexed streaming + `NetworkedApplications` &
|
||||
`ReloadableApplications` platform integrations), followed by **P4**
|
||||
(`Coordination`, `Replication`, `DistributedStorage`, `DistributedApplications`).
|
||||
@@ -128,6 +128,14 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
|
||||
| M-SHORTURL-01..04 | Frozen `V1` ABI preserved + additive `Void::ShortUrl::V2` (`kShortUrlErrorDomain = 28`, URL/key validation, base62 rejection-sampled keys, civil expiry, tombstone non-reuse, 24h idempotency, `LocalProvider`, `V1Adapter`), separate `ShortUrlStorage` (`Void::Storage` conditional batches + `SecurityRandomBytesPort`), separate `ShortUrlRemote` (capability pre-checks, `Retry-After`, `UnknownOutcome`), `ShortUrlOnly` consumer (`691808e`) | [M-SHORTURL-01-04](tasks/M-SHORTURL-01-04.md) | VERIFIED | Standalone `ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing` `ShortUrl*` 5/5 ✔, `ctest` `2/2` (`36.84s` incl. `ShortUrlOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
|
||||
| S-RPC-01..03 | NEW `Void::RPC` subsystem (`kRpcErrorDomain = 29`), Wire v1 big-endian binary envelope codec (`VRPC`, fail-closed on unknown major/required flags/reserved/overflow, skippable minor extensions, `Binary::Reader` `std::memcpy` fix), unary `/void-rpc/v1/call` HTTP/1.1 `Server` & `Client` with `AuthHook`, schema negotiation, timeout clamping, sanitized handler exceptions, `Registration::unregister_and_drain()`, `RpcOnly` consumer (`5184d1c`) | [S-RPC-01-03](tasks/S-RPC-01-03.md) | VERIFIED | Standalone `Rpc` 2/2 ✔, `ctest` `2/2` (`36.84s` incl. `RpcOnly`); Debug TSan `940 ✔ / 3 ⊘` (`24.15s`, `0` races); full RelWithDebInfo `1,466 ✔` (`38` consumers); ASan+UBSan `1,466 ✔` (`0` leaks/UB) |
|
||||
|
||||
## Wave 10 — P3 Core Subsystems: Discovery, Scheduler, Messaging (`feat/roadmap-p3-wave10`)
|
||||
|
||||
| ID | Deliverable | Spec | State | Verification summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| S-DISCOVERY-01..04 | NEW `Void::Discovery` (`kDiscoveryErrorDomain = 30`, pure `Catalog`, atomic `replace_static()`, provider generation resets, local RAII `Registration` + steady-clock leases & zero-TTL rejection, `ManagedLeaseRenewer`, bounded `WatchHandle` with coalesced `ResyncRequired` + self-cancel + `SelfJoin`, `WeightedRoundRobinSelector`, HRW `AffinitySelector`) + separate `Void::DiscoveryRpc` (identity-preserving TLS refresh; `RPC` remains Discovery-free), `DiscoveryOnly` consumer (`ec8c0bd`) | [S-DISCOVERY-01-04](tasks/S-DISCOVERY-01-04.md) | VERIFIED | Standalone `Discovery;DiscoveryRpc;Testing` `5/5 ✔` (`9.4ms`), `ctest` `2/2` (`11.26s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔ / 4 ⊘` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
|
||||
| S-SCHEDULER-01..04 | NEW `Void::Scheduler` (`kSchedulerErrorDomain = 31`, monotonic min-heap, one-shot/fixed-delay/fixed-rate, 5-field `CalendarExpression`, explicit `TimezoneRegistry` DST gap/fold & unknown-zone rejection, O(1) `CoalesceLatest` over >2.6M missed minutes, 100/pass `CatchUpBounded`, overlap policies, retries/dead-letter, revision invalidation watermark, `close_and_join`) + durable `Void::SchedulerStorage` (`StorageJobStore` exclusive owner lock, unique civil-slot dedup, crash `Running -> Pending` recovery preserving `OccurrenceId`, `UnknownOutcome`, retention-cap pause), `SchedulerOnly` consumer (`aaeab50`) | [S-SCHEDULER-01-04](tasks/S-SCHEDULER-01-04.md) | VERIFIED | Standalone `Scheduler;SchedulerStorage;System;Testing` `5/5 ✔` (`167.3ms`), `ctest` `2/2` (`30.06s` incl. `SchedulerOnly` `_no_external_deps`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
|
||||
| S-MESSAGING-01..04 | NEW `Void::Messaging` (`kMessagingErrorDomain = 32`, explicit `PublishDurability`, nondurable `InMemoryQueue`, `Pending -> InFlight(gen, visibility) -> Acked \| Pending \| DeadLetter`, competing/`SingleActive` groups, stale-receipt fencing, idempotent ack, retries/DLQ, corrupt quarantine) + `Void::MessagingStorage` (`StorageQueue` durable batches, restart generation bump preserving attempts, atomic DLQ move & `stuck_dlq_count`, bounded 24h/100k idempotency, `BlockAtQuota` & clock-health pause, `OutboxInbox` single-batch local helper) + `Void::MessagingRpc` (`RpcQueueServer`/`RpcQueueClient`), `MessagingOnly` consumer (`60ee28e`) | [S-MESSAGING-01-04](tasks/S-MESSAGING-01-04.md) | VERIFIED | Standalone `Messaging;MessagingStorage;MessagingRpc;System;Testing` `4/4 ✔` (`217.4ms`), `ctest` `2/2` (`31.73s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`); Debug TSan `900 ✔ / 3 ⊘` (`23.20s`, `0` races); full RelWithDebInfo `1,480 ✔` (`41` consumers); ASan+UBSan `1,480 ✔` (`0` leaks/UB) |
|
||||
|
||||
All workers share the checkout and have disjoint file ownership defined in their
|
||||
persisted task specifications. Root owns all cross-cutting files and resolves contract
|
||||
changes. No worker owns application code, build files, existing docs/short-url.md, or Git
|
||||
|
||||
@@ -297,3 +297,10 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain
|
||||
| Wave 9 full Debug ASan+UBSan (`5184d1c`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w9-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 48 modules | **PASSED**: `1,470` discovered (`1,466 ✔`, `4 ⊘`, `0 ✘`) in `41.95s`, `0` leaks, `0` UB |
|
||||
| Wave 9 Debug TSan (`5184d1c`) | `dev cpp-gcc -p openssl -p libsodium` Debug TSan (`-Werror`, `/tmp/void-w9-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 22 modules (`Net;TestingMock;ShortUrl;ShortUrlStorage;ShortUrlRemote;RPC;System;Testing`) | **PASSED**: `943` discovered (`940 ✔`, `3 ⊘`, `0 ✘`) in `24.15s`, `0` data races, `0` lock-order warnings |
|
||||
| Post-W9 Benchmark (`5184d1c`, `rev=5184d1cf8cdd`) | `/tmp/void-w9-full/benchmarks/VoidFoundationBench --json /tmp/void-w9-full/post-w9.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.49ns, `core_uuid_parse_hyphenated` 25.02ns, `core_uuid_to_string` 16.55ns, `core_hash_fnv1a64_256b` 183.63ns, `core_hash_murmur3_256b` 69.12ns, `functional_result_ok_chain` 1.15ns, `functional_error_with_context` 59.06ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 8.93ns, `containers_lru_get_put` 21.47ns, `binary_reader_u64_be` 1.15ns, `data_json_parse_small_object` 297.72ns, `data_json_serialize_small_object` 172.85ns |
|
||||
| Wave 10 `Discovery` & `DiscoveryRpc` standalone (`ec8c0bd`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m1`, `Discovery;DiscoveryRpc;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `9.4ms` (`Catalog` 4/4, `EndpointAdapter` 1/1); `ctest` `2/2` in `11.26s` (`VoidTests` `0.60s`, `VoidInstalledComponentConsumers` `10.66s` incl. `DiscoveryOnly` `_no_external_deps` & `RpcOnly`) |
|
||||
| Wave 10 `Scheduler` & `SchedulerStorage` standalone (`aaeab50`) | `dev cpp-gcc -c` zero external deps RelWithDebInfo (`-Werror`, `/tmp/void-w10-m2`, `Scheduler;SchedulerStorage;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `5/5 ✔` in `167.3ms` (`Scheduler` 3/3, `StorageJobStore` 2/2); `ctest` `2/2` in `30.06s` (`VoidTests` `16.51s`, `VoidInstalledComponentConsumers` `13.54s` incl. `SchedulerOnly` `_no_external_deps`) |
|
||||
| Wave 10 `Messaging`, `MessagingStorage`, & `MessagingRpc` standalone (`60ee28e`) | `dev cpp-gcc -p openssl -c` RelWithDebInfo (`-Werror`, `/tmp/void-w10-m3`, `Messaging;MessagingStorage;MessagingRpc;System;Testing`), filtered `VoidTests` + `ctest` | **PASSED**: `4/4 ✔` in `217.4ms` (`Messaging` 1/1, `StorageQueue` 2/2, `RpcAdapter` 1/1); `ctest` `2/2` in `31.73s` (`VoidTests` `16.09s`, `VoidInstalledComponentConsumers` `15.63s` incl. `MessagingOnly` `_no_external_deps` & `RpcOnly`) |
|
||||
| Wave 10 integrated RelWithDebInfo + consumers (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w10-full`), 55 modules, `VoidTests` + `ctest` | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `23.80s`; `ctest` `2/2` in `94.93s` (`VoidTests` `23.93s`, `VoidInstalledComponentConsumers` `71.00s` across all `41` consumers incl. `DiscoveryOnly`, `SchedulerOnly`, `MessagingOnly`) |
|
||||
| Wave 10 full Debug ASan+UBSan (`60ee28e`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w10-asan`), 55 modules | **PASSED**: `1,484` discovered (`1,480 ✔`, `4 ⊘`, `0 ✘`) in `42.48s`, `0` leaks, `0` UB |
|
||||
| Wave 10 Debug TSan (`60ee28e`) | `dev cpp-gcc -p openssl` Debug TSan (`-Werror`, `/tmp/void-w10-tsan`), 23 modules (`Discovery;DiscoveryRpc;Scheduler;SchedulerStorage;Messaging;MessagingStorage;MessagingRpc;System;Testing`) | **PASSED**: `903` discovered (`900 ✔`, `3 ⊘`, `0 ✘`) in `23.20s`, `0` data races, `0` lock-order warnings |
|
||||
| Post-W10 Benchmark (`60ee28e`, `rev=60ee28e4ca9b`) | `/tmp/void-w10-full/benchmarks/VoidFoundationBench --json /tmp/void-w10-full/post-w10.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.18ns, `core_uuid_to_string` 16.66ns, `core_hash_fnv1a64_256b` 182.46ns, `core_hash_murmur3_256b` 68.53ns, `functional_result_ok_chain` 1.14ns, `functional_error_with_context` 59.10ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.85ns, `containers_lru_get_put` 20.87ns, `binary_reader_u64_be` 1.14ns, `data_json_parse_small_object` 287.18ns, `data_json_serialize_small_object` 164.76ns |
|
||||
@@ -0,0 +1,39 @@
|
||||
# S-DISCOVERY-01..04 — Discovery Subsystem (Catalog, Leases, Watches, Selectors, Optional RPC Adapter)
|
||||
|
||||
## Scope
|
||||
Implement the P1–P3 native `Void::Discovery` subsystem per `docs/roadmap/subsystems/Discovery.md` and `docs/roadmap/DEPENDENCIES.md`, plus the optional `Void::DiscoveryRpc` endpoint adapter living strictly above `RPC` and `Discovery`:
|
||||
|
||||
1. **`S-DISCOVERY-01` — Boundary, Error Domain, and Immutable Value Contracts**:
|
||||
- Module `src/Discovery/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero network, storage, or consensus dependencies.
|
||||
- Error domain `kDiscoveryErrorDomain = 30` with `DiscoveryErrorCode` covering validation, conflict, cap exhaustion, expiry, stale/unavailable freshness, cancellation, and self-join diagnosis.
|
||||
- Strict endpoint/attribute validation before publication (valid scheme/host/port, `weight > 0`, `max_attributes_per_record = 16`, `max_metadata_bytes_per_record = 4096`, `max_services = 1024`, `max_endpoints_per_service = 256`, `max_total_records = 10000`).
|
||||
2. **`S-DISCOVERY-02` — Pure Catalog, Atomic Static Snapshots, and Local RAII Registrations**:
|
||||
- Pure `Catalog` construction creating zero hidden threads.
|
||||
- Atomic candidate `replace_static()` rejecting invalid/conflicting candidates while preserving the active revision; explicit `provider_generation` bump resets revision domain and emits `ResyncRequired`.
|
||||
- Local move-only RAII `Registration` handles with explicit `LeasePolicy` (default 30s TTL / 10s renew interval via injected `MonotonicClock`; zero TTL rejected as `InvalidArgument`; unleased explicit mode valid until release; static entries never expire).
|
||||
- Duplicate `(service, instance)` returns `Conflict` without stealing existing handles.
|
||||
- Deterministic `resolve()` sorted by `instance`, filtering logically expired records before cleanup runs, respecting `ResolvePolicy::allow_stale` and `Freshness`.
|
||||
3. **`S-DISCOVERY-03` — Bounded Watches, Resync, Client Selectors, and Managed Renewal**:
|
||||
- Bounded `watch()` (`max_watches = 1024`, `max_events_per_watch = 64`, shared `16 MiB` event budget) emitting `InitialSnapshot`, serialized per-watch `Delta`, and explicit `ResyncRequired` + full latest `Snapshot` on overflow or provider-generation reset.
|
||||
- Callbacks run outside catalog and watch locks; `cancel()` stops new admission (including self-cancel inside a callback); `join()` drains admitted callbacks and diagnoses synchronous self-join (`SelfJoin`) instead of deadlocking.
|
||||
- `Catalog::shutdown_and_join()` removes local entries, cancels watches, and joins admitted callbacks; destructor only requests stop.
|
||||
- `WeightedRoundRobinSelector`, stable HRW `AffinitySelector`, and deterministic `ManagedLeaseRenewer`.
|
||||
4. **`S-DISCOVERY-04` — Optional RPC Integration (`DiscoveryRpc`)**:
|
||||
- Separate module `src/DiscoveryRpc/module.cmake` (`INTERNAL_DEPS Discovery RPC`) so `RPC` remains completely independent of `Discovery`.
|
||||
- `EndpointResolverClient` resolves endpoints from `Discovery::Catalog`, selects via client selector, preserves configured `expected_tls_name` / identity across IP/address refreshes (rejecting TLS scheme/identity downgrade), and executes unary calls via `Void::RPC::Client`.
|
||||
|
||||
## File Ownership
|
||||
- `include/Void/Discovery/{Types,Catalog}.hpp`
|
||||
- `src/Discovery/{module.cmake,Catalog.cpp}`
|
||||
- `include/Void/DiscoveryRpc/EndpointAdapter.hpp`
|
||||
- `src/DiscoveryRpc/{module.cmake,EndpointAdapter.cpp}`
|
||||
- `tests/standalone/Discovery/Catalog.cpp`
|
||||
- `tests/standalone/DiscoveryRpc/EndpointAdapter.cpp`
|
||||
- `tests/package/DiscoveryOnly/{CMakeLists.txt,main.cpp}`
|
||||
- `tests/package/InstalledComponents.cmake`
|
||||
|
||||
## Acceptance & Verification
|
||||
- Standalone `Discovery;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `DiscoveryOnly` consumer with `_no_external_deps`.
|
||||
- `DiscoveryRpc` identity-preserving refresh + RPC round-trip tests; `RpcOnly` remains Discovery-free.
|
||||
- Deterministic fake-clock lease expiry/renewal, atomic bad/good config replacement, duplicate registration conflict, watch overflow -> `ResyncRequired`, self-cancel/self-join, and selector determinism.
|
||||
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
|
||||
@@ -0,0 +1,41 @@
|
||||
# S-MESSAGING-01..04 — Messaging Subsystem (Delivery Model, Ephemeral Queue, Durable Storage Queue, Outbox/Inbox, RPC Adapter)
|
||||
|
||||
## Scope
|
||||
Implement the P1–P3 native `Void::Messaging` subsystem, `Void::MessagingStorage` durable adapter + outbox/inbox helper, and `Void::MessagingRpc` remote adapter per `docs/roadmap/subsystems/Messaging.md` and `docs/roadmap/DEPENDENCIES.md`:
|
||||
|
||||
1. **`S-MESSAGING-01..02` — Delivery Model, Receipts, State Machine, and Bounded Ephemeral Queue**:
|
||||
- Module `src/Messaging/module.cmake` (`INTERNAL_DEPS Core Functional Binary Time Async`) with zero `Storage`, `Net`, or `RPC` dependency.
|
||||
- Error domain `kMessagingErrorDomain = 32` (`MessagingErrorCode`).
|
||||
- Explicit `PublishDurability::{Memory, Durable}`: `InMemoryQueue` strictly rejects `PublishDurability::Durable` (`UnsupportedDurability`) and `PublishReceipt` records exact durability so nondurable channels never claim durable success.
|
||||
- Native state machine `Pending -> InFlight(generation, visibility_deadline) -> Acked | Pending | DeadLetter`.
|
||||
- FIFO per-queue competing consumers and `ConsumerMode::SingleActive` (blocking group head on retry until ack).
|
||||
- Visibility timeout (default 30s, explicit extension up to 5m via injected `MonotonicClock`), stale-receipt fencing (`StaleReceipt`), idempotent repeat ack, retry bound (default 5 attempts, full jitter 1s..60s via injectable RNG), corrupt-payload quarantine, and bounded caps (768 KiB message, 8 KiB / 32 headers, 1024 queues, 32 groups/queue, 64 in-flight/group, 1024 waiting receives, 64 MiB transient payload budget).
|
||||
- Clean `close_and_join()` stopping admission, waking/cancelling waiting receives, and draining active deliveries.
|
||||
2. **`S-MESSAGING-03` — Durable Storage Queue (`MessagingStorage`)**:
|
||||
- Module `src/MessagingStorage/module.cmake` (`INTERNAL_DEPS Messaging Storage`).
|
||||
- `StorageQueue` persists payload, sequence, group state, delivery generation/attempt, DLQ records, and bounded 24h / 100k publish idempotency ledger via `Void::Storage::Engine` conditional batches (`Durability::Sync`).
|
||||
- At idempotency capacity, rejects new publish (`IdempotencyCapacityExceeded`) instead of silently evicting live contracts.
|
||||
- On restart/reopen, promotes all prior `InFlight` records to `Pending` with bumped generation so stale worker receipts fail with `StaleReceipt`, preserving attempt counters across restarts.
|
||||
- Atomic DLQ move (DLQ insert + source group removal in one `Storage::Batch`); when DLQ or persistent quota is full, keeps the message durable, drops zero data, blocks affected admission, and exposes `stuck_dlq_count()`.
|
||||
- Explicit `RetentionPolicy::BlockAtQuota` default (unread work never silently expired) vs opt-in `DropOldestLossy`, pausing expiry when civil clock health fails; `UnknownOutcome` surfaced on uncertain storage commit.
|
||||
3. **`S-MESSAGING-04` — Outbox/Inbox Local-Batch Helper and Remote RPC Adapter (`MessagingRpc`)**:
|
||||
- `OutboxInbox` helper in `MessagingStorage` enabling single-batch local business mutation + outbox insert and single-batch local effect + inbox dedup insert, with explicit documentation that external effects remain outside the local batch boundary.
|
||||
- Separate module `src/MessagingRpc/module.cmake` (`INTERNAL_DEPS Messaging RPC`) exposing `RpcQueueServer` and `RpcQueueClient` for remote `publish`, `receive`, `ack`, `nack`, and `query_receipt` over Wire v1 unary RPC.
|
||||
|
||||
## File Ownership
|
||||
- `include/Void/Messaging/{Types,Queue}.hpp`
|
||||
- `src/Messaging/{module.cmake,Queue.cpp}`
|
||||
- `include/Void/MessagingStorage/{StorageQueue,OutboxInbox}.hpp`
|
||||
- `src/MessagingStorage/{module.cmake,StorageQueue.cpp}`
|
||||
- `include/Void/MessagingRpc/RpcAdapter.hpp`
|
||||
- `src/MessagingRpc/{module.cmake,RpcAdapter.cpp}`
|
||||
- `tests/standalone/Messaging/Messaging.cpp`
|
||||
- `tests/standalone/MessagingStorage/StorageQueue.cpp`
|
||||
- `tests/standalone/MessagingRpc/RpcAdapter.cpp`
|
||||
- `tests/package/MessagingOnly/{CMakeLists.txt,main.cpp}`
|
||||
- `tests/package/InstalledComponents.cmake`
|
||||
|
||||
## Acceptance & Verification
|
||||
- Standalone `Messaging;MessagingStorage;MessagingRpc;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `MessagingOnly` consumer with `_no_external_deps`.
|
||||
- Deterministic tests for ephemeral/durable separation, competing vs single-active ordering, visibility expiry & stale receipt fencing, idempotent ack/publish, restart recovery preserving attempts, poison -> atomic DLQ move, DLQ/quota/idempotency cap pressure, clock-health pause, outbox/inbox single-batch atomicity, and remote RPC round-trip.
|
||||
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
|
||||
@@ -0,0 +1,40 @@
|
||||
# S-SCHEDULER-01..04 — Scheduler Subsystem (Timers, Calendar, Durable Storage Store, Operator Controls)
|
||||
|
||||
## Scope
|
||||
Implement the P1–P3 native `Void::Scheduler` subsystem and `Void::SchedulerStorage` durable adapter per `docs/roadmap/subsystems/Scheduler.md` and `docs/roadmap/DEPENDENCIES.md`:
|
||||
|
||||
1. **`S-SCHEDULER-01` — In-Memory Heap, Recurrence, Overlap, Cancellation & Shutdown**:
|
||||
- Module `src/Scheduler/module.cmake` (`INTERNAL_DEPS Core Functional Time Async`) with zero `Storage` dependency.
|
||||
- Error domain `kSchedulerErrorDomain = 31` (`SchedulerErrorCode`).
|
||||
- Monotonic min-heap ordered by `(due_time, sequence)` using injected `MonotonicClock` and `CivilClock`, pure construction (no hidden background threads), and `Async::OperationOptions` for deadlines/cancellation.
|
||||
- One-shot, fixed-delay (advances from durable completion), and fixed-rate (advances from intended schedule time) schedules; `OverlapPolicy` (`Forbid`, `QueueOne`, `AllowBounded`); `RetryPolicy` (default 5 attempts, exponential backoff 1s..5m, x2, injectable full-jitter RNG); callbacks run outside scheduler/store locks.
|
||||
- `close_and_join()` stops materialization/dispatch, signals active handlers, joins within deadline, and returns `ShutdownReport` preserving running records on timeout.
|
||||
2. **`S-SCHEDULER-02` — Calendar Grammar, Explicit Timezones/DST, and Bounded Misfire**:
|
||||
- 5-field cron-like grammar (`minute hour day month weekday` with `*`, lists, ranges, steps; both day-of-month and weekday constraints apply).
|
||||
- Explicit `TimezoneRegistry` supporting `"UTC"`, fixed offsets (`+HH:MM`/`-HH:MM`), and explicit DST transition rules (`DstGapPolicy::Skip`/`NextValid`, `DstFoldPolicy::First`/`Second`/`Twice` with persisted `fold_index`). Unknown timezone fails with `UnsupportedTimezone` (never silent UTC fallback).
|
||||
- `MisfirePolicy` (`Skip`, `CoalesceLatest`, `CatchUpBounded` capped at `100` slots/job/pass while preserving remaining cursor state even across millions of missed slots).
|
||||
3. **`S-SCHEDULER-03` — Durable Persistence Port and `SchedulerStorage` Adapter**:
|
||||
- `JobStore` port + `InMemoryJobStore` (in `Scheduler`) and `StorageJobStore` (in `src/SchedulerStorage/module.cmake`, `INTERNAL_DEPS Scheduler Storage`) backed by `Void::Storage::Engine` conditional batches (`Durability::Sync`, 1 MiB batch cap).
|
||||
- Exclusive ownership lock rejecting second concurrent scheduler owner (`OwnershipLocked`).
|
||||
- Atomic occurrence materialization + cursor advance with unique `(job, revision, civil_slot, fold)` dedup key preventing duplicate materialization on wall-clock rollback.
|
||||
- Atomic `Pending -> Running` claim checking job tombstone and revision invalidation watermark in the same conditional batch; `Running -> Completed` / `Pending` / `Dead` transitions; `UnknownOutcome` surfaced faithfully on unknown storage write outcome.
|
||||
- Startup crash recovery returning `Running` occurrences to `Pending` with the exact same `OccurrenceId` (explicit at-least-once semantics).
|
||||
4. **`S-SCHEDULER-04` — Revision Updates, Tombstone Removal, Retention Caps, and Operator Inspection**:
|
||||
- `update_job()` bumps revision and atomically writes old-revision invalidation watermark so unstarted old occurrences are cancelled without racing active claims; failed updates leave prior policy intact.
|
||||
- `remove_job()` writes tombstone, stops admission, and requests stop for active handlers.
|
||||
- Retention count cap pauses materialization without advancing cursors or deleting unacknowledged work; dead occurrences require explicit `acknowledge_dead()` before pruning; bounded `prune_completed()` / `reclaim_invalidated()` and inspection APIs.
|
||||
|
||||
## File Ownership
|
||||
- `include/Void/Scheduler/{Types,Calendar,Store,Scheduler}.hpp`
|
||||
- `src/Scheduler/{module.cmake,Calendar.cpp,Scheduler.cpp}`
|
||||
- `include/Void/SchedulerStorage/StorageJobStore.hpp`
|
||||
- `src/SchedulerStorage/{module.cmake,StorageJobStore.cpp}`
|
||||
- `tests/standalone/Scheduler/Scheduler.cpp`
|
||||
- `tests/standalone/SchedulerStorage/StorageJobStore.cpp`
|
||||
- `tests/package/SchedulerOnly/{CMakeLists.txt,main.cpp}`
|
||||
- `tests/package/InstalledComponents.cmake`
|
||||
|
||||
## Acceptance & Verification
|
||||
- Standalone `Scheduler;SchedulerStorage;Testing` (`-DVOID_WARNINGS_AS_ERRORS=ON`) + `SchedulerOnly` consumer with `_no_external_deps`.
|
||||
- Deterministic fake-clock ordering, overlap, retry/dead-letter, DST gap/fold/unknown-tz, millions-of-missed-slots coalesce/catch-up cap, crash/reopen recovery preserving `OccurrenceId`, revision watermark race, unknown outcome, and retention-cap cursor preservation tests.
|
||||
- Full `RelWithDebInfo`, `Debug` `ASan+UBSan`, and `Debug` `TSan` with 0 leaks, 0 UB, 0 races.
|
||||
@@ -0,0 +1,216 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Discovery/Types.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Discovery
|
||||
{
|
||||
class Catalog;
|
||||
|
||||
/// Move-only RAII handle for a local endpoint registration.
|
||||
/// Destruction releases the registration from future snapshots.
|
||||
class Registration final
|
||||
{
|
||||
public:
|
||||
|
||||
Registration() noexcept = default;
|
||||
~Registration() noexcept;
|
||||
|
||||
Registration(Registration&& other) noexcept;
|
||||
Registration& operator=(Registration&& other) noexcept;
|
||||
Registration(const Registration&) = delete;
|
||||
Registration& operator=(const Registration&) = delete;
|
||||
|
||||
[[nodiscard]] bool active() const noexcept;
|
||||
[[nodiscard]] const std::string& service() const noexcept
|
||||
{
|
||||
return m_service;
|
||||
}
|
||||
[[nodiscard]] const std::string& instance() const noexcept
|
||||
{
|
||||
return m_instance;
|
||||
}
|
||||
[[nodiscard]] std::optional<Void::Time::MonotonicClock::time_point>
|
||||
expires_at() const noexcept;
|
||||
|
||||
[[nodiscard]] Result<Void::Time::MonotonicClock::time_point> renew();
|
||||
void release() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class Catalog;
|
||||
struct State;
|
||||
std::shared_ptr<void> m_catalog_state{};
|
||||
std::string m_service{};
|
||||
std::string m_instance{};
|
||||
std::uint64_t m_token{0};
|
||||
bool m_leased{false};
|
||||
std::chrono::milliseconds m_ttl{0};
|
||||
bool m_active{false};
|
||||
};
|
||||
|
||||
/// Move-only handle for a bounded service watch.
|
||||
/// `cancel()` stops new admission and is safe from inside the callback.
|
||||
/// `join()` waits for already-admitted callbacks and returns `SelfJoin`
|
||||
/// instead of deadlocking when called synchronously from the callback itself.
|
||||
class WatchHandle final
|
||||
{
|
||||
public:
|
||||
|
||||
WatchHandle() noexcept = default;
|
||||
~WatchHandle() noexcept;
|
||||
|
||||
WatchHandle(WatchHandle&& other) noexcept;
|
||||
WatchHandle& operator=(WatchHandle&& other) noexcept;
|
||||
WatchHandle(const WatchHandle&) = delete;
|
||||
WatchHandle& operator=(const WatchHandle&) = delete;
|
||||
|
||||
[[nodiscard]] bool active() const noexcept;
|
||||
[[nodiscard]] std::size_t pending_events() const noexcept;
|
||||
|
||||
void cancel() noexcept;
|
||||
[[nodiscard]] Result<void> join() noexcept;
|
||||
|
||||
/// Explicit deterministic delivery step for `Manual` watch mode.
|
||||
/// Returns true if an event was delivered.
|
||||
bool deliver_one();
|
||||
std::size_t deliver_all();
|
||||
|
||||
private:
|
||||
|
||||
friend class Catalog;
|
||||
std::shared_ptr<void> m_catalog_state{};
|
||||
std::shared_ptr<void> m_watch_node{};
|
||||
std::uint64_t m_watch_id{0};
|
||||
};
|
||||
|
||||
/// Pure, thread-free service endpoint catalog supporting atomic static
|
||||
/// snapshots, local RAII leased/unleased registrations, and bounded watches.
|
||||
class Catalog final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Catalog(CatalogOptions options = {});
|
||||
~Catalog() noexcept;
|
||||
|
||||
Catalog(Catalog&&) noexcept;
|
||||
Catalog& operator=(Catalog&&) noexcept;
|
||||
Catalog(const Catalog&) = delete;
|
||||
Catalog& operator=(const Catalog&) = delete;
|
||||
|
||||
/// Validate candidate static snapshot completely before atomic
|
||||
/// publication. On any validation/conflict/cap error, preserves the
|
||||
/// active revision unchanged.
|
||||
[[nodiscard]] Result<std::uint64_t>
|
||||
replace_static(std::vector<EndpointRecord> candidate,
|
||||
bool bump_provider_generation = false);
|
||||
|
||||
/// Explicitly set provider health (e.g. for stale/unavailable
|
||||
/// resolution policy testing or upper replicated directory adapters).
|
||||
void set_provider_health(Freshness freshness,
|
||||
std::optional<Error> provider_error =
|
||||
std::nullopt);
|
||||
|
||||
[[nodiscard]] Result<Snapshot>
|
||||
resolve(std::string_view service,
|
||||
ResolvePolicy policy = {}) const;
|
||||
|
||||
[[nodiscard]] Result<Registration>
|
||||
register_local(EndpointRecord record,
|
||||
LeasePolicy lease = LeasePolicy::unleased());
|
||||
|
||||
[[nodiscard]] Result<WatchHandle>
|
||||
watch(std::string service, std::uint64_t after_revision,
|
||||
WatchCallback callback, WatchOptions options = {});
|
||||
|
||||
/// Process at most `limits.max_expirations_per_turn` logically
|
||||
/// expired local leases, advancing revision and notifying watches.
|
||||
std::size_t reap_expired();
|
||||
|
||||
/// Remove local entries, stop watch admission, and join admitted
|
||||
/// callbacks. Destruction alone only requests stop.
|
||||
[[nodiscard]] Result<void> shutdown_and_join() noexcept;
|
||||
|
||||
[[nodiscard]] std::uint64_t revision() const noexcept;
|
||||
[[nodiscard]] std::uint64_t provider_generation() const noexcept;
|
||||
[[nodiscard]] std::size_t active_record_count() const noexcept;
|
||||
[[nodiscard]] std::size_t active_watch_count() const noexcept;
|
||||
[[nodiscard]] std::size_t shared_watch_event_bytes() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class Registration;
|
||||
friend class WatchHandle;
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
/// Explicit, thread-free lease renewal helper driven by injected steady time.
|
||||
class ManagedLeaseRenewer final
|
||||
{
|
||||
public:
|
||||
|
||||
ManagedLeaseRenewer(
|
||||
Registration& registration,
|
||||
std::chrono::milliseconds renew_interval =
|
||||
std::chrono::seconds{10},
|
||||
const Void::Time::MonotonicClock* clock =
|
||||
&Void::Time::SystemMonotonicClock::instance()) noexcept;
|
||||
|
||||
[[nodiscard]] bool due() const noexcept;
|
||||
[[nodiscard]] Result<bool> tick();
|
||||
[[nodiscard]] std::size_t consecutive_failures() const noexcept
|
||||
{
|
||||
return m_consecutive_failures;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Registration* m_registration{nullptr};
|
||||
std::chrono::milliseconds m_interval{std::chrono::seconds{10}};
|
||||
const Void::Time::MonotonicClock* m_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
Void::Time::MonotonicClock::time_point m_next_renew{};
|
||||
std::size_t m_consecutive_failures{0};
|
||||
};
|
||||
|
||||
/// Deterministic client-side smooth weighted round-robin selector over an
|
||||
/// immutable Snapshot.
|
||||
class WeightedRoundRobinSelector final
|
||||
{
|
||||
public:
|
||||
|
||||
WeightedRoundRobinSelector() = default;
|
||||
|
||||
[[nodiscard]] Result<EndpointRecord>
|
||||
select(const Snapshot& snapshot);
|
||||
|
||||
void reset() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex m_mu{};
|
||||
std::map<std::string, std::int64_t, std::less<>> m_current_weights{};
|
||||
};
|
||||
|
||||
/// Deterministic client-side affinity selector using weighted Rendezvous
|
||||
/// (HRW) hashing over `Void::Hash::fnv1a64`.
|
||||
class AffinitySelector final
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Result<EndpointRecord>
|
||||
select(const Snapshot& snapshot, std::string_view affinity_key);
|
||||
};
|
||||
|
||||
} // namespace Void::Discovery
|
||||
@@ -0,0 +1,245 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Discovery
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class DiscoveryErrorCode : std::int32_t {
|
||||
None = 0,
|
||||
InvalidArgument = 1,
|
||||
NotFound = 2,
|
||||
Conflict = 3,
|
||||
LimitExceeded = 4,
|
||||
Expired = 5,
|
||||
Unavailable = 6,
|
||||
Stale = 7,
|
||||
Cancelled = 8,
|
||||
SelfJoin = 9,
|
||||
Closed = 10,
|
||||
TlsIdentityMismatch = 11,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_discovery_error(DiscoveryErrorCode code,
|
||||
std::string message)
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case DiscoveryErrorCode::None:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case DiscoveryErrorCode::InvalidArgument:
|
||||
case DiscoveryErrorCode::TlsIdentityMismatch:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case DiscoveryErrorCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case DiscoveryErrorCode::Conflict:
|
||||
case DiscoveryErrorCode::Expired:
|
||||
case DiscoveryErrorCode::SelfJoin:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case DiscoveryErrorCode::LimitExceeded:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case DiscoveryErrorCode::Unavailable:
|
||||
case DiscoveryErrorCode::Stale:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case DiscoveryErrorCode::Cancelled:
|
||||
case DiscoveryErrorCode::Closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kDiscoveryErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
enum class Freshness : std::uint8_t {
|
||||
Fresh = 0,
|
||||
Stale = 1,
|
||||
Unavailable = 2,
|
||||
};
|
||||
|
||||
struct EndpointAddress {
|
||||
std::string scheme{"http"};
|
||||
std::string host{};
|
||||
std::uint16_t port{0};
|
||||
/// Configured peer identity retained across IP/address refreshes
|
||||
/// so DNS/address updates cannot downgrade TLS expected-name checks.
|
||||
std::string expected_tls_name{};
|
||||
|
||||
[[nodiscard]] std::string_view effective_tls_name() const noexcept
|
||||
{
|
||||
return expected_tls_name.empty()
|
||||
? std::string_view{host}
|
||||
: std::string_view{expected_tls_name};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string to_origin_url() const
|
||||
{
|
||||
return scheme + "://" + host + ":" + std::to_string(port);
|
||||
}
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const EndpointAddress&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct EndpointRecord {
|
||||
std::string instance{};
|
||||
std::string service{};
|
||||
EndpointAddress endpoint{};
|
||||
std::uint32_t weight{1};
|
||||
bool ready{true};
|
||||
std::map<std::string, std::string, std::less<>> attributes{};
|
||||
|
||||
[[nodiscard]] bool
|
||||
operator==(const EndpointRecord&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct Snapshot {
|
||||
std::uint64_t provider_generation{1};
|
||||
std::uint64_t revision{0};
|
||||
std::vector<EndpointRecord> records{};
|
||||
Freshness freshness{Freshness::Fresh};
|
||||
std::optional<Error> provider_error{};
|
||||
};
|
||||
|
||||
struct ResolvePolicy {
|
||||
bool allow_stale{false};
|
||||
bool include_unready{false};
|
||||
};
|
||||
|
||||
struct LeasePolicy {
|
||||
bool leased{false};
|
||||
std::chrono::milliseconds ttl{std::chrono::seconds{30}};
|
||||
std::chrono::milliseconds renew_interval{std::chrono::seconds{10}};
|
||||
|
||||
[[nodiscard]] static constexpr LeasePolicy unleased() noexcept
|
||||
{
|
||||
return LeasePolicy{
|
||||
.leased = false,
|
||||
.ttl = std::chrono::seconds{30},
|
||||
.renew_interval = std::chrono::seconds{10},
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] static constexpr LeasePolicy with_ttl(
|
||||
std::chrono::milliseconds lease_ttl,
|
||||
std::chrono::milliseconds renewal =
|
||||
std::chrono::seconds{10}) noexcept
|
||||
{
|
||||
return LeasePolicy{
|
||||
.leased = true,
|
||||
.ttl = lease_ttl,
|
||||
.renew_interval = renewal,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
struct CatalogLimits {
|
||||
std::size_t max_services{1024};
|
||||
std::size_t max_endpoints_per_service{256};
|
||||
std::size_t max_total_records{10000};
|
||||
std::size_t max_attributes_per_record{16};
|
||||
std::size_t max_metadata_bytes_per_record{4096};
|
||||
std::size_t max_watches{1024};
|
||||
std::size_t max_events_per_watch{64};
|
||||
std::size_t max_shared_event_bytes{16ULL * 1024 * 1024};
|
||||
std::size_t max_expirations_per_turn{256};
|
||||
};
|
||||
|
||||
enum class WatchEventKind : std::uint8_t {
|
||||
InitialSnapshot = 0,
|
||||
Delta = 1,
|
||||
ResyncRequired = 2,
|
||||
};
|
||||
|
||||
struct WatchEvent {
|
||||
WatchEventKind kind{WatchEventKind::InitialSnapshot};
|
||||
std::string service{};
|
||||
std::uint64_t provider_generation{1};
|
||||
std::uint64_t revision{0};
|
||||
std::optional<Snapshot> snapshot{};
|
||||
std::vector<EndpointRecord> added{};
|
||||
std::vector<EndpointRecord> updated{};
|
||||
std::vector<std::string> removed_instances{};
|
||||
};
|
||||
|
||||
using WatchCallback = std::function<void(WatchEvent)>;
|
||||
|
||||
enum class WatchDispatchMode : std::uint8_t {
|
||||
/// Deliver outside catalog locks immediately on admission/mutation.
|
||||
Inline = 0,
|
||||
/// Queue events for explicit `WatchHandle::deliver_one()`/`deliver_all()`.
|
||||
Manual = 1,
|
||||
/// Serialize delivery on an injected `Void::Async::Executor`.
|
||||
Executor = 2,
|
||||
};
|
||||
|
||||
struct WatchOptions {
|
||||
WatchDispatchMode dispatch_mode{WatchDispatchMode::Inline};
|
||||
Void::Async::Executor* executor{nullptr};
|
||||
std::size_t max_queued_events{0}; // 0 => CatalogLimits::max_events_per_watch
|
||||
};
|
||||
|
||||
enum class ObservationKind : std::uint8_t {
|
||||
Resolve = 0,
|
||||
Register = 1,
|
||||
Renew = 2,
|
||||
Release = 3,
|
||||
Expire = 4,
|
||||
ReplaceStatic = 5,
|
||||
WatchResync = 6,
|
||||
};
|
||||
|
||||
/// Bounded low-cardinality observation event (never includes arbitrary
|
||||
/// per-instance metric labels).
|
||||
struct ObservationEvent {
|
||||
ObservationKind kind{ObservationKind::Resolve};
|
||||
bool ok{true};
|
||||
std::size_t count{0};
|
||||
};
|
||||
|
||||
using ObservationHook = std::function<void(const ObservationEvent&)>;
|
||||
|
||||
struct CatalogOptions {
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
CatalogLimits limits{};
|
||||
ObservationHook observer{};
|
||||
};
|
||||
|
||||
[[nodiscard]] Result<void>
|
||||
validate_endpoint_record(const EndpointRecord& record,
|
||||
const CatalogLimits& limits = {});
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
estimate_record_bytes(const EndpointRecord& record) noexcept;
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
estimate_watch_event_bytes(const WatchEvent& event) noexcept;
|
||||
|
||||
} // namespace Void::Discovery
|
||||
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Discovery/Catalog.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::DiscoveryRpc
|
||||
{
|
||||
struct EndpointResolverOptions {
|
||||
std::string service{};
|
||||
/// Optional pinned TLS peer identity. When set, any refreshed
|
||||
/// endpoint whose effective TLS name differs or attempts to
|
||||
/// downgrade from `https` is rejected with `TlsIdentityMismatch`.
|
||||
std::string expected_tls_name{};
|
||||
bool require_tls{false};
|
||||
Void::Discovery::ResolvePolicy resolve_policy{};
|
||||
Void::Net::HttpClientOptions http_options{
|
||||
.verify_tls = true,
|
||||
};
|
||||
Void::RPC::RpcLimits rpc_limits{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
std::size_t max_outstanding_ops{128};
|
||||
std::chrono::milliseconds total_deadline{std::chrono::seconds{5}};
|
||||
};
|
||||
|
||||
struct SelectedEndpoint {
|
||||
Void::Discovery::EndpointRecord record{};
|
||||
std::string origin_url{};
|
||||
std::string effective_tls_name{};
|
||||
};
|
||||
|
||||
/// Optional RPC endpoint adapter living strictly above `Discovery` and
|
||||
/// `RPC` (preserving `RPC`'s independence from `Discovery`).
|
||||
class EndpointResolverClient final
|
||||
{
|
||||
public:
|
||||
|
||||
EndpointResolverClient(const Void::Discovery::Catalog& catalog,
|
||||
EndpointResolverOptions options);
|
||||
|
||||
[[nodiscard]] Void::Discovery::Result<SelectedEndpoint>
|
||||
select_endpoint(
|
||||
std::optional<std::string_view> affinity_key = std::nullopt);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Void::RPC::OwnedBytes>
|
||||
call(Void::RPC::MethodId method,
|
||||
Void::RPC::OwnedBytes payload,
|
||||
Void::RPC::CallOptions options = {},
|
||||
std::optional<std::string_view> affinity_key =
|
||||
std::nullopt);
|
||||
|
||||
[[nodiscard]] std::size_t outstanding_ops() const noexcept
|
||||
{
|
||||
return m_outstanding.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
const Void::Discovery::Catalog* m_catalog{nullptr};
|
||||
EndpointResolverOptions m_options{};
|
||||
Void::Discovery::WeightedRoundRobinSelector m_rr{};
|
||||
std::atomic<std::size_t> m_outstanding{0};
|
||||
};
|
||||
|
||||
} // namespace Void::DiscoveryRpc
|
||||
@@ -80,6 +80,8 @@ namespace Void::Result
|
||||
inline constexpr std::uint32_t kShortUrlErrorDomain = 28;
|
||||
inline constexpr std::uint32_t kRpcErrorDomain = 29;
|
||||
inline constexpr std::uint32_t kDiscoveryErrorDomain = 30;
|
||||
inline constexpr std::uint32_t kSchedulerErrorDomain = 31;
|
||||
inline constexpr std::uint32_t kMessagingErrorDomain = 32;
|
||||
|
||||
struct ErrorCode {
|
||||
std::uint32_t domain{kGenericErrorDomain};
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Types.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Messaging
|
||||
{
|
||||
/// Abstract queue interface implemented by both explicitly nondurable
|
||||
/// `InMemoryQueue` and durable `MessagingStorage::StorageQueue`.
|
||||
class Queue
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~Queue() = default;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
create_queue(QueueConfig config) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
create_group(std::string_view queue, GroupConfig config) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<PublishReceipt> publish(
|
||||
std::string_view queue, Message message,
|
||||
PublishDurability durability,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::optional<Delivery>>
|
||||
try_receive(std::string_view queue, std::string_view group) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<Delivery> receive(
|
||||
std::string_view queue, std::string_view group,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
ack(const Receipt& receipt,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void> nack(
|
||||
const Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay = std::nullopt,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<Void::Time::MonotonicClock::time_point>
|
||||
extend_visibility(
|
||||
const Receipt& receipt, std::chrono::milliseconds extension,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
/// Quarantine an unparseable or schema-incompatible message into
|
||||
/// DLQ without falsely acknowledging it as processed.
|
||||
[[nodiscard]] virtual Result<void> quarantine_corrupt(
|
||||
const Receipt& receipt, std::string reason,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<DeliveryState>
|
||||
query_receipt(const Receipt& receipt) const = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::vector<DeadLetterEntry>>
|
||||
list_dead_letters(std::string_view queue,
|
||||
std::string_view group,
|
||||
std::size_t limit = 100) const = 0;
|
||||
|
||||
[[nodiscard]] virtual std::size_t
|
||||
stuck_dlq_count(std::string_view queue,
|
||||
std::string_view group) const noexcept = 0;
|
||||
|
||||
/// Reclaim expired `InFlight` deliveries into `Pending` (with retry
|
||||
/// backoff) or atomically move exhausted messages to DLQ.
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
reap_expired_visibility() = 0;
|
||||
|
||||
/// Apply configured retention policy (paused when civil clock
|
||||
/// health is degraded).
|
||||
[[nodiscard]] virtual Result<std::size_t> expire_retention() = 0;
|
||||
|
||||
virtual void set_clock_healthy(bool healthy) noexcept = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<ShutdownReport> close_and_join(
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<QueueStats> stats() const = 0;
|
||||
};
|
||||
|
||||
struct InMemoryQueueOptions {
|
||||
QueueLimits limits{};
|
||||
const Void::Time::MonotonicClock* monotonic_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
const Void::Time::CivilClock* civil_clock{
|
||||
&Void::Time::SystemCivilClock::instance()};
|
||||
RandomU64Fn rng{};
|
||||
};
|
||||
|
||||
/// Explicitly nondurable in-process queue implementing the full native
|
||||
/// delivery state machine (`PublishDurability::Durable` is rejected with
|
||||
/// `UnsupportedDurability`).
|
||||
class InMemoryQueue final : public Queue
|
||||
{
|
||||
public:
|
||||
|
||||
explicit InMemoryQueue(InMemoryQueueOptions options = {});
|
||||
~InMemoryQueue() noexcept override;
|
||||
|
||||
InMemoryQueue(InMemoryQueue&&) noexcept;
|
||||
InMemoryQueue& operator=(InMemoryQueue&&) noexcept;
|
||||
InMemoryQueue(const InMemoryQueue&) = delete;
|
||||
InMemoryQueue& operator=(const InMemoryQueue&) = delete;
|
||||
|
||||
[[nodiscard]] Result<void> create_queue(QueueConfig config) override;
|
||||
[[nodiscard]] Result<void>
|
||||
create_group(std::string_view queue,
|
||||
GroupConfig config) override;
|
||||
|
||||
[[nodiscard]] Result<PublishReceipt> publish(
|
||||
std::string_view queue, Message message,
|
||||
PublishDurability durability,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<std::optional<Delivery>>
|
||||
try_receive(std::string_view queue,
|
||||
std::string_view group) override;
|
||||
|
||||
[[nodiscard]] Result<Delivery> receive(
|
||||
std::string_view queue, std::string_view group,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<void>
|
||||
ack(const Receipt& receipt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<void> nack(
|
||||
const Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay = std::nullopt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<Void::Time::MonotonicClock::time_point>
|
||||
extend_visibility(
|
||||
const Receipt& receipt, std::chrono::milliseconds extension,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<void> quarantine_corrupt(
|
||||
const Receipt& receipt, std::string reason,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<DeliveryState>
|
||||
query_receipt(const Receipt& receipt) const override;
|
||||
|
||||
[[nodiscard]] Result<std::vector<DeadLetterEntry>>
|
||||
list_dead_letters(std::string_view queue,
|
||||
std::string_view group,
|
||||
std::size_t limit = 100) const override;
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
stuck_dlq_count(std::string_view queue,
|
||||
std::string_view group) const noexcept override;
|
||||
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
reap_expired_visibility() override;
|
||||
|
||||
[[nodiscard]] Result<std::size_t> expire_retention() override;
|
||||
|
||||
void set_clock_healthy(bool healthy) noexcept override;
|
||||
|
||||
[[nodiscard]] Result<ShutdownReport> close_and_join(
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<QueueStats> stats() const override;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::Messaging
|
||||
@@ -0,0 +1,260 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Messaging
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class MessagingErrorCode : std::int32_t {
|
||||
None = 0,
|
||||
InvalidArgument = 1,
|
||||
NotFound = 2,
|
||||
Conflict = 3,
|
||||
StaleReceipt = 4,
|
||||
Overloaded = 5,
|
||||
QuotaExceeded = 6,
|
||||
IdempotencyCapacityExceeded = 7,
|
||||
DlqFull = 8,
|
||||
UnsupportedDurability = 9,
|
||||
CorruptPayload = 10,
|
||||
PersistenceError = 11,
|
||||
UnknownOutcome = 12,
|
||||
Cancelled = 13,
|
||||
Timeout = 14,
|
||||
Closed = 15,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_messaging_error(MessagingErrorCode code,
|
||||
std::string message)
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case MessagingErrorCode::None:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case MessagingErrorCode::InvalidArgument:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case MessagingErrorCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case MessagingErrorCode::Conflict:
|
||||
case MessagingErrorCode::StaleReceipt:
|
||||
case MessagingErrorCode::UnknownOutcome:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case MessagingErrorCode::Overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case MessagingErrorCode::QuotaExceeded:
|
||||
case MessagingErrorCode::IdempotencyCapacityExceeded:
|
||||
case MessagingErrorCode::DlqFull:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case MessagingErrorCode::UnsupportedDurability:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case MessagingErrorCode::CorruptPayload:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case MessagingErrorCode::PersistenceError:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case MessagingErrorCode::Cancelled:
|
||||
case MessagingErrorCode::Closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case MessagingErrorCode::Timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kMessagingErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
/// Explicit publish durability contract. Nondurable queues must reject
|
||||
/// `PublishDurability::Durable` rather than returning a false durable OK.
|
||||
enum class PublishDurability : std::uint8_t {
|
||||
Memory = 0,
|
||||
Durable = 1,
|
||||
};
|
||||
|
||||
enum class ConsumerMode : std::uint8_t {
|
||||
Competing = 0,
|
||||
SingleActive = 1,
|
||||
};
|
||||
|
||||
enum class RetentionPolicy : std::uint8_t {
|
||||
/// Initial default: block further publish at quota rather than silently
|
||||
/// expiring unread work.
|
||||
BlockAtQuota = 0,
|
||||
/// Explicit opt-in lossy mode allowing retention expiry of unread work.
|
||||
DropOldestLossy = 1,
|
||||
};
|
||||
|
||||
enum class DeliveryState : std::uint8_t {
|
||||
Pending = 0,
|
||||
InFlight = 1,
|
||||
Acked = 2,
|
||||
DeadLetter = 3,
|
||||
};
|
||||
|
||||
struct Message {
|
||||
std::string id{};
|
||||
std::vector<std::byte> payload{};
|
||||
std::map<std::string, std::string, std::less<>> headers{};
|
||||
std::uint32_t schema_version{1};
|
||||
|
||||
[[nodiscard]] bool
|
||||
operator==(const Message&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct Receipt {
|
||||
std::string queue{};
|
||||
std::string group{};
|
||||
std::string message_id{};
|
||||
std::uint64_t sequence{0};
|
||||
std::uint64_t generation{0};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const Receipt&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct PublishReceipt {
|
||||
std::string queue{};
|
||||
std::string message_id{};
|
||||
std::uint64_t sequence{0};
|
||||
PublishDurability durability{PublishDurability::Memory};
|
||||
bool deduplicated{false};
|
||||
};
|
||||
|
||||
struct Delivery {
|
||||
Message message{};
|
||||
Receipt receipt{};
|
||||
std::uint32_t attempt{1};
|
||||
Void::Time::MonotonicClock::time_point visibility_deadline{};
|
||||
};
|
||||
|
||||
struct DeadLetterEntry {
|
||||
Message message{};
|
||||
std::string queue{};
|
||||
std::string group{};
|
||||
std::uint64_t sequence{0};
|
||||
std::uint32_t attempts{0};
|
||||
std::string reason{};
|
||||
std::int64_t dead_lettered_utc_ms{0};
|
||||
};
|
||||
|
||||
struct RetryPolicy {
|
||||
std::uint32_t max_attempts{5};
|
||||
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
|
||||
std::chrono::milliseconds max_delay{std::chrono::seconds{60}};
|
||||
};
|
||||
|
||||
struct QueueLimits {
|
||||
std::size_t max_message_bytes{768ULL * 1024};
|
||||
std::size_t max_headers_bytes{8ULL * 1024};
|
||||
std::size_t max_header_count{32};
|
||||
std::size_t max_queues{1024};
|
||||
std::size_t max_groups_per_queue{32};
|
||||
std::size_t max_in_flight_per_group{64};
|
||||
std::size_t max_waiting_receives{1024};
|
||||
std::size_t max_transient_payload_bytes{64ULL * 1024 * 1024};
|
||||
std::uint64_t persistent_quota_bytes{1024ULL * 1024 * 1024};
|
||||
std::size_t max_dlq_messages{10000};
|
||||
std::chrono::milliseconds idempotency_retention{
|
||||
std::chrono::hours{24}};
|
||||
std::size_t max_idempotency_entries{100000};
|
||||
std::chrono::milliseconds default_visibility_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
std::chrono::milliseconds max_visibility_extension{
|
||||
std::chrono::minutes{5}};
|
||||
std::chrono::milliseconds logical_retention{
|
||||
std::chrono::hours{24 * 7}};
|
||||
std::chrono::milliseconds shutdown_drain_timeout{
|
||||
std::chrono::seconds{10}};
|
||||
};
|
||||
|
||||
struct QueueConfig {
|
||||
std::string name{};
|
||||
RetentionPolicy retention_policy{RetentionPolicy::BlockAtQuota};
|
||||
RetryPolicy retry{};
|
||||
};
|
||||
|
||||
struct GroupConfig {
|
||||
std::string name{};
|
||||
ConsumerMode mode{ConsumerMode::Competing};
|
||||
std::chrono::milliseconds visibility_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
std::size_t max_in_flight{64};
|
||||
};
|
||||
|
||||
struct QueueStats {
|
||||
std::size_t queues{0};
|
||||
std::size_t pending{0};
|
||||
std::size_t in_flight{0};
|
||||
std::size_t acked{0};
|
||||
std::size_t dead_letter{0};
|
||||
std::size_t stuck_dlq{0};
|
||||
std::uint64_t retained_bytes{0};
|
||||
std::size_t idempotency_entries{0};
|
||||
};
|
||||
|
||||
struct ShutdownReport {
|
||||
bool complete{true};
|
||||
std::size_t remaining_in_flight{0};
|
||||
};
|
||||
|
||||
using RandomU64Fn = std::function<std::uint64_t()>;
|
||||
|
||||
[[nodiscard]] Result<void>
|
||||
validate_identifier(std::string_view name, std::string_view label);
|
||||
|
||||
[[nodiscard]] Result<void> validate_message(const Message& message,
|
||||
const QueueLimits& limits);
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
estimate_message_bytes(const Message& message) noexcept;
|
||||
|
||||
[[nodiscard]] std::int64_t
|
||||
compute_retry_backoff_ms(const RetryPolicy& retry,
|
||||
std::uint32_t attempt,
|
||||
const RandomU64Fn& rng);
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_mono_ns(Void::Time::MonotonicClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
} // namespace Void::Messaging
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::MessagingRpc
|
||||
{
|
||||
inline constexpr std::uint64_t kMessagingRpcServiceId = 0x564D534752504301ULL;
|
||||
inline constexpr Void::RPC::MethodId kPublishMethod{
|
||||
kMessagingRpcServiceId, 1U};
|
||||
inline constexpr Void::RPC::MethodId kTryReceiveMethod{
|
||||
kMessagingRpcServiceId, 2U};
|
||||
inline constexpr Void::RPC::MethodId kAckMethod{
|
||||
kMessagingRpcServiceId, 3U};
|
||||
inline constexpr Void::RPC::MethodId kNackMethod{
|
||||
kMessagingRpcServiceId, 4U};
|
||||
inline constexpr Void::RPC::MethodId kQueryReceiptMethod{
|
||||
kMessagingRpcServiceId, 5U};
|
||||
|
||||
/// Mounts remote Messaging operations (`publish`, `try_receive`, `ack`,
|
||||
/// `nack`, `query_receipt`) onto a `Void::RPC::Server`.
|
||||
class RpcQueueServer final
|
||||
{
|
||||
public:
|
||||
|
||||
RpcQueueServer() = default;
|
||||
~RpcQueueServer() noexcept;
|
||||
|
||||
RpcQueueServer(RpcQueueServer&&) noexcept = default;
|
||||
RpcQueueServer& operator=(RpcQueueServer&&) noexcept = default;
|
||||
RpcQueueServer(const RpcQueueServer&) = delete;
|
||||
RpcQueueServer& operator=(const RpcQueueServer&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
mount(Void::RPC::Server& server,
|
||||
Void::Messaging::Queue& queue);
|
||||
|
||||
void unmount_and_drain() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
std::vector<Void::RPC::Registration> m_registrations{};
|
||||
};
|
||||
|
||||
/// Remote client executing Messaging operations over unary `Void::RPC::Client`,
|
||||
/// propagating `UnknownOutcome` faithfully when network replies are lost.
|
||||
class RpcQueueClient final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit RpcQueueClient(Void::RPC::ClientOptions options);
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
|
||||
publish(std::string_view queue,
|
||||
const Void::Messaging::Message& message,
|
||||
Void::Messaging::PublishDurability durability,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
std::optional<Void::Messaging::Delivery>>
|
||||
try_receive(std::string_view queue, std::string_view group,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
ack(const Void::Messaging::Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
nack(const Void::Messaging::Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay =
|
||||
std::nullopt,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
|
||||
query_receipt(const Void::Messaging::Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
private:
|
||||
|
||||
Void::RPC::Client m_client;
|
||||
};
|
||||
|
||||
} // namespace Void::MessagingRpc
|
||||
@@ -0,0 +1,260 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Storage/Batch.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::MessagingStorage
|
||||
{
|
||||
struct OutboxRecord {
|
||||
std::string outbox_id{};
|
||||
std::string target_queue{};
|
||||
Void::Messaging::Message message{};
|
||||
};
|
||||
|
||||
/// Atomic local-batch helpers for the Outbox and Inbox patterns over a
|
||||
/// single shared `Void::Storage::Engine`.
|
||||
///
|
||||
/// Boundary guarantee:
|
||||
/// - Business state + outbox insert (or consumer state + inbox dedup key)
|
||||
/// commit atomically ONLY within the same `Void::Storage::Batch`.
|
||||
/// - External effects (email, HTTP/RPC calls, separate databases) remain
|
||||
/// strictly outside this batch boundary and still require downstream
|
||||
/// idempotency or compensation.
|
||||
class OutboxInbox final
|
||||
{
|
||||
public:
|
||||
|
||||
static void append_outbox_in_batch(
|
||||
Void::Storage::Batch& batch, const OutboxRecord& record,
|
||||
std::string_view prefix = "outbox:v1:")
|
||||
{
|
||||
const std::string key =
|
||||
std::string{prefix} + record.outbox_id;
|
||||
batch.require_absent(key);
|
||||
batch.put(key, encode_outbox(record));
|
||||
}
|
||||
|
||||
/// Record inbox deduplication key inside the consumer's SAME
|
||||
/// `Void::Storage::Batch` as its local business mutation. If the
|
||||
/// message was already applied, the batch fails with `Conflict`
|
||||
/// (duplicate prevented atomically).
|
||||
static void apply_inbox_in_batch(
|
||||
Void::Storage::Batch& batch, std::string_view consumer_id,
|
||||
std::string_view message_id,
|
||||
std::string_view prefix = "inbox:v1:")
|
||||
{
|
||||
const std::string key = std::string{prefix} +
|
||||
std::string{consumer_id} + "\x1F" +
|
||||
std::string{message_id};
|
||||
batch.require_absent(key);
|
||||
batch.put(key, "1");
|
||||
}
|
||||
|
||||
/// Relay pending outbox entries to `queue` using stable
|
||||
/// `Message::id` (idempotent on retry) and delete confirmed entries.
|
||||
[[nodiscard]] static Void::Messaging::Result<std::size_t>
|
||||
relay_outbox(Void::Storage::Engine& engine,
|
||||
Void::Messaging::Queue& queue,
|
||||
std::string_view prefix = "outbox:v1:",
|
||||
std::size_t max_entries = 64)
|
||||
{
|
||||
auto snap = engine.snapshot();
|
||||
if (!snap.has_value()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::PersistenceError,
|
||||
snap.error().message()));
|
||||
}
|
||||
auto cur = engine.scan(
|
||||
std::move(*snap),
|
||||
Void::Storage::ScanBounds::prefix(prefix));
|
||||
if (!cur.has_value()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::PersistenceError,
|
||||
cur.error().message()));
|
||||
}
|
||||
|
||||
std::size_t relayed = 0;
|
||||
for (;;) {
|
||||
auto page = cur->next_page();
|
||||
if (!page.has_value()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
PersistenceError,
|
||||
page.error().message()));
|
||||
}
|
||||
for (const auto& entry : page->entries) {
|
||||
if (relayed >= max_entries) {
|
||||
return relayed;
|
||||
}
|
||||
auto decoded = decode_outbox(
|
||||
Void::Storage::to_string_view(entry.value));
|
||||
if (!decoded.has_value()) {
|
||||
return Void::Result::fail(decoded.error());
|
||||
}
|
||||
auto pub = queue.publish(
|
||||
decoded->target_queue, decoded->message,
|
||||
Void::Messaging::PublishDurability::Durable);
|
||||
if (!pub.has_value()) {
|
||||
return Void::Result::fail(pub.error());
|
||||
}
|
||||
Void::Storage::Batch erase_b{};
|
||||
erase_b.require_version(entry.key, entry.version);
|
||||
erase_b.erase(entry.key);
|
||||
auto wr = engine.write(std::move(erase_b),
|
||||
Void::Storage::Durability::Sync);
|
||||
if (!wr.has_value()) {
|
||||
if (wr.error().outcome ==
|
||||
Void::Storage::Outcome::Unknown) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
UnknownOutcome,
|
||||
"Outbox relay delete outcome unknown"));
|
||||
}
|
||||
if (wr.error().cause.code !=
|
||||
Void::Storage::StorageErrorCode::conflict) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
PersistenceError,
|
||||
wr.error().cause.error.message()));
|
||||
}
|
||||
}
|
||||
++relayed;
|
||||
}
|
||||
if (!page->has_more) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return relayed;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static void append_u32(std::string& out, std::uint32_t v)
|
||||
{
|
||||
out.push_back(static_cast<char>((v >> 24U) & 0xFFU));
|
||||
out.push_back(static_cast<char>((v >> 16U) & 0xFFU));
|
||||
out.push_back(static_cast<char>((v >> 8U) & 0xFFU));
|
||||
out.push_back(static_cast<char>(v & 0xFFU));
|
||||
}
|
||||
|
||||
static void append_str(std::string& out, std::string_view s)
|
||||
{
|
||||
append_u32(out, static_cast<std::uint32_t>(s.size()));
|
||||
out.append(s);
|
||||
}
|
||||
|
||||
[[nodiscard]] static bool read_u32(std::string_view& in,
|
||||
std::uint32_t& out) noexcept
|
||||
{
|
||||
if (in.size() < 4U) return false;
|
||||
out = (static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[0]))
|
||||
<< 24U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[1]))
|
||||
<< 16U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[2]))
|
||||
<< 8U) |
|
||||
static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[3]));
|
||||
in.remove_prefix(4U);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] static bool read_str(std::string_view& in,
|
||||
std::string& out)
|
||||
{
|
||||
std::uint32_t len = 0;
|
||||
if (!read_u32(in, len) || len > in.size()) return false;
|
||||
out.assign(in.data(), len);
|
||||
in.remove_prefix(len);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::string
|
||||
encode_outbox(const OutboxRecord& r)
|
||||
{
|
||||
std::string out;
|
||||
append_u32(out, 1U);
|
||||
append_str(out, r.outbox_id);
|
||||
append_str(out, r.target_queue);
|
||||
append_str(out, r.message.id);
|
||||
append_u32(out, r.message.schema_version);
|
||||
append_u32(out,
|
||||
static_cast<std::uint32_t>(r.message.payload.size()));
|
||||
if (!r.message.payload.empty()) {
|
||||
out.append(
|
||||
reinterpret_cast<const char*>(r.message.payload.data()),
|
||||
r.message.payload.size());
|
||||
}
|
||||
append_u32(
|
||||
out, static_cast<std::uint32_t>(r.message.headers.size()));
|
||||
for (const auto& [k, v] : r.message.headers) {
|
||||
append_str(out, k);
|
||||
append_str(out, v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Messaging::Result<OutboxRecord>
|
||||
decode_outbox(std::string_view raw)
|
||||
{
|
||||
std::uint32_t ver = 0;
|
||||
if (!read_u32(raw, ver) || ver != 1U) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::CorruptPayload,
|
||||
"Outbox: unsupported schema version"));
|
||||
}
|
||||
OutboxRecord r{};
|
||||
std::uint32_t plen = 0;
|
||||
std::uint32_t hcount = 0;
|
||||
if (!read_str(raw, r.outbox_id) ||
|
||||
!read_str(raw, r.target_queue) ||
|
||||
!read_str(raw, r.message.id) ||
|
||||
!read_u32(raw, r.message.schema_version) ||
|
||||
!read_u32(raw, plen) || plen > raw.size()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::CorruptPayload,
|
||||
"Outbox: truncated payload"));
|
||||
}
|
||||
r.message.payload.resize(plen);
|
||||
if (plen > 0U) {
|
||||
std::memcpy(r.message.payload.data(), raw.data(), plen);
|
||||
raw.remove_prefix(plen);
|
||||
}
|
||||
if (!read_u32(raw, hcount)) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::CorruptPayload,
|
||||
"Outbox: truncated header count"));
|
||||
}
|
||||
for (std::uint32_t i = 0; i < hcount; ++i) {
|
||||
std::string k, v;
|
||||
if (!read_str(raw, k) || !read_str(raw, v)) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
CorruptPayload,
|
||||
"Outbox: truncated header"));
|
||||
}
|
||||
r.message.headers.emplace(std::move(k), std::move(v));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::MessagingStorage
|
||||
@@ -0,0 +1,121 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Void::MessagingStorage
|
||||
{
|
||||
struct StorageQueueOptions {
|
||||
Void::Messaging::QueueLimits limits{};
|
||||
std::string key_prefix{"msg:v1:"};
|
||||
const Void::Time::MonotonicClock* monotonic_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
const Void::Time::CivilClock* civil_clock{
|
||||
&Void::Time::SystemCivilClock::instance()};
|
||||
Void::Messaging::RandomU64Fn rng{};
|
||||
};
|
||||
|
||||
/// Single-node durable `Void::Messaging::Queue` backed by
|
||||
/// `Void::Storage::Engine` conditional batches (`Durability::Sync` for
|
||||
/// `PublishDurability::Durable`).
|
||||
///
|
||||
/// Explicit at-least-once delivery:
|
||||
/// - On open/restart, all prior `InFlight` records are promoted to
|
||||
/// `Pending` with a bumped delivery generation so stale worker receipts
|
||||
/// fail with `StaleReceipt` while preserving attempt counters.
|
||||
/// - DLQ insertion and source delivery update execute in one atomic batch.
|
||||
class StorageQueue final : public Void::Messaging::Queue
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Messaging::Result<StorageQueue>
|
||||
open(Void::Storage::Engine& engine,
|
||||
StorageQueueOptions options = {});
|
||||
|
||||
~StorageQueue() noexcept override;
|
||||
StorageQueue(StorageQueue&&) noexcept;
|
||||
StorageQueue& operator=(StorageQueue&&) noexcept;
|
||||
StorageQueue(const StorageQueue&) = delete;
|
||||
StorageQueue& operator=(const StorageQueue&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
create_queue(Void::Messaging::QueueConfig config) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
create_group(std::string_view queue,
|
||||
Void::Messaging::GroupConfig config) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
|
||||
publish(std::string_view queue, Void::Messaging::Message message,
|
||||
Void::Messaging::PublishDurability durability,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
std::optional<Void::Messaging::Delivery>>
|
||||
try_receive(std::string_view queue,
|
||||
std::string_view group) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::Delivery>
|
||||
receive(std::string_view queue, std::string_view group,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
ack(const Void::Messaging::Receipt& receipt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void> nack(
|
||||
const Void::Messaging::Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay = std::nullopt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
Void::Time::MonotonicClock::time_point>
|
||||
extend_visibility(
|
||||
const Void::Messaging::Receipt& receipt,
|
||||
std::chrono::milliseconds extension,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void> quarantine_corrupt(
|
||||
const Void::Messaging::Receipt& receipt, std::string reason,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
|
||||
query_receipt(
|
||||
const Void::Messaging::Receipt& receipt) const override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
std::vector<Void::Messaging::DeadLetterEntry>>
|
||||
list_dead_letters(std::string_view queue,
|
||||
std::string_view group,
|
||||
std::size_t limit = 100) const override;
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
stuck_dlq_count(std::string_view queue,
|
||||
std::string_view group) const noexcept override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<std::size_t>
|
||||
reap_expired_visibility() override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<std::size_t>
|
||||
expire_retention() override;
|
||||
|
||||
void set_clock_healthy(bool healthy) noexcept override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::ShutdownReport>
|
||||
close_and_join(
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::QueueStats>
|
||||
stats() const override;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
explicit StorageQueue(std::shared_ptr<State> state) noexcept;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::MessagingStorage
|
||||
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
struct CivilMinute {
|
||||
std::int32_t year{1970};
|
||||
std::uint32_t month{1}; // 1..12
|
||||
std::uint32_t day{1}; // 1..31
|
||||
std::uint32_t hour{0}; // 0..23
|
||||
std::uint32_t minute{0}; // 0..59
|
||||
std::uint32_t weekday{4}; // 0=Sunday .. 6=Saturday
|
||||
};
|
||||
|
||||
/// Convert civil UTC components to minutes since 1970-01-01T00:00Z.
|
||||
[[nodiscard]] std::int64_t
|
||||
civil_to_epoch_minute(std::int32_t year, std::uint32_t month,
|
||||
std::uint32_t day, std::uint32_t hour,
|
||||
std::uint32_t minute) noexcept;
|
||||
|
||||
/// Convert minutes since 1970-01-01T00:00Z to civil components + weekday.
|
||||
[[nodiscard]] CivilMinute
|
||||
epoch_minute_to_civil(std::int64_t epoch_minute) noexcept;
|
||||
|
||||
/// Explicit DST transition rule for deterministic timezone resolution
|
||||
/// without relying on ambient OS tzdata behavior.
|
||||
struct DstTransitionRule {
|
||||
std::string name{};
|
||||
std::int32_t standard_offset_minutes{0};
|
||||
std::int32_t dst_offset_minutes{0};
|
||||
/// Spring-forward gap window in local wall minutes `[start, end)`.
|
||||
std::optional<std::int64_t> gap_start_local_min{};
|
||||
std::optional<std::int64_t> gap_end_local_min{};
|
||||
/// Fall-back fold window in local wall minutes `[start, end)`.
|
||||
/// Minutes in `[start, end)` happen twice: fold 0 at `dst_offset`,
|
||||
/// fold 1 at `standard_offset`.
|
||||
std::optional<std::int64_t> fold_start_local_min{};
|
||||
std::optional<std::int64_t> fold_end_local_min{};
|
||||
};
|
||||
|
||||
struct ResolvedSlot {
|
||||
std::int64_t utc_ms{0};
|
||||
std::uint8_t fold_index{0};
|
||||
};
|
||||
|
||||
/// Explicit timezone registry. Recognizes `"UTC"`, `"Z"`, fixed numeric
|
||||
/// offsets (`+HH:MM`, `-HH:MM`, `UTC+HH:MM`, `UTC-HH:MM`), and explicitly
|
||||
/// registered `DstTransitionRule` zones. Unknown zones fail with
|
||||
/// `UnsupportedTimezone` (never silent UTC fallback).
|
||||
class TimezoneRegistry final
|
||||
{
|
||||
public:
|
||||
|
||||
TimezoneRegistry() = default;
|
||||
|
||||
void register_dst_zone(DstTransitionRule rule);
|
||||
|
||||
[[nodiscard]] Result<void>
|
||||
validate_timezone(std::string_view tz) const;
|
||||
|
||||
[[nodiscard]] Result<std::vector<ResolvedSlot>>
|
||||
resolve_local_minute(std::string_view tz,
|
||||
std::int64_t local_epoch_minute,
|
||||
DstGapPolicy gap_policy,
|
||||
DstFoldPolicy fold_policy) const;
|
||||
|
||||
/// Approximate local epoch minute range covering `[utc_min_lo,
|
||||
/// utc_min_hi]` for `tz`.
|
||||
[[nodiscard]] Result<std::pair<std::int64_t, std::int64_t>>
|
||||
local_minute_bounds(std::string_view tz,
|
||||
std::int64_t utc_min_lo,
|
||||
std::int64_t utc_min_hi) const;
|
||||
|
||||
private:
|
||||
|
||||
std::map<std::string, DstTransitionRule, std::less<>> m_dst_zones{};
|
||||
};
|
||||
|
||||
struct MaterializedSlots {
|
||||
std::vector<ResolvedSlot> slots{};
|
||||
std::int64_t next_cursor_utc_ms{0};
|
||||
bool more_pending{false};
|
||||
};
|
||||
|
||||
/// 5-field cron-like calendar expression (`minute hour day month weekday`)
|
||||
/// supporting `*`, lists, ranges, and steps. Both day-of-month and weekday
|
||||
/// constraints apply.
|
||||
class CalendarExpression final
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Result<CalendarExpression>
|
||||
parse(std::string_view expression);
|
||||
|
||||
[[nodiscard]] bool matches(const CivilMinute& cm) const noexcept;
|
||||
|
||||
/// Next matching local epoch minute strictly >= `from_local_min`,
|
||||
/// capped by `max_local_min`.
|
||||
[[nodiscard]] std::optional<std::int64_t>
|
||||
next_matching_minute(std::int64_t from_local_min,
|
||||
std::int64_t max_local_min) const noexcept;
|
||||
|
||||
/// Latest matching local epoch minute <= `from_local_min` and
|
||||
/// >= `min_local_min`. Allows O(1) coalescing across millions of
|
||||
/// missed minutes.
|
||||
[[nodiscard]] std::optional<std::int64_t>
|
||||
prev_matching_minute(std::int64_t from_local_min,
|
||||
std::int64_t min_local_min) const noexcept;
|
||||
|
||||
[[nodiscard]] Result<MaterializedSlots>
|
||||
materialize_range(const CalendarSpec& spec,
|
||||
const TimezoneRegistry& tz_registry,
|
||||
std::int64_t after_utc_ms,
|
||||
std::int64_t up_to_utc_ms,
|
||||
MisfirePolicy misfire,
|
||||
std::size_t max_catch_up) const;
|
||||
|
||||
private:
|
||||
|
||||
std::uint64_t m_minutes{0}; // bits 0..59
|
||||
std::uint32_t m_hours{0}; // bits 0..23
|
||||
std::uint32_t m_days{0}; // bits 1..31
|
||||
std::uint32_t m_months{0}; // bits 1..12
|
||||
std::uint32_t m_weekdays{0}; // bits 0..6 (0 = Sunday)
|
||||
};
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,100 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Calendar.hpp>
|
||||
#include <Void/Scheduler/Store.hpp>
|
||||
#include <Void/Scheduler/Types.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
struct SchedulerOptions {
|
||||
std::string owner_id{"scheduler-default"};
|
||||
std::shared_ptr<JobStore> store{};
|
||||
const Void::Time::MonotonicClock* monotonic_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
const Void::Time::CivilClock* civil_clock{
|
||||
&Void::Time::SystemCivilClock::instance()};
|
||||
TimezoneRegistry timezones{};
|
||||
SchedulerLimits limits{};
|
||||
RandomU64Fn rng{};
|
||||
ObservationHook observer{};
|
||||
};
|
||||
|
||||
/// Pure, thread-free timer/calendar job scheduler with pluggable durable
|
||||
/// persistence (`InMemoryJobStore` or `SchedulerStorage::StorageJobStore`).
|
||||
class Scheduler final
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Result<Scheduler>
|
||||
create(SchedulerOptions options = {});
|
||||
|
||||
Scheduler(Scheduler&&) noexcept;
|
||||
Scheduler& operator=(Scheduler&&) noexcept;
|
||||
Scheduler(const Scheduler&) = delete;
|
||||
Scheduler& operator=(const Scheduler&) = delete;
|
||||
~Scheduler() noexcept;
|
||||
|
||||
[[nodiscard]] Result<void> register_handler(std::string handler_id,
|
||||
HandlerFn handler);
|
||||
|
||||
[[nodiscard]] Result<std::uint64_t>
|
||||
add_job(JobSpec spec,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Increment revision and atomically record an old-revision
|
||||
/// invalidation watermark. Failed updates leave prior policy intact.
|
||||
[[nodiscard]] Result<std::uint64_t>
|
||||
update_job(JobSpec spec,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Write a job tombstone, stop new admission, and signal stop to
|
||||
/// active handlers for the job.
|
||||
[[nodiscard]] Result<void>
|
||||
remove_job(std::string_view job_id,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Run one bounded scheduling pass: materialize due occurrences
|
||||
/// under misfire/catch-up/retention limits and dispatch ready
|
||||
/// occurrences outside scheduler/store locks. Returns count of
|
||||
/// occurrences executed in this pass.
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
tick(Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Execute at most one ready occurrence from the monotonic min-heap
|
||||
/// outside scheduler/store locks.
|
||||
[[nodiscard]] Result<bool>
|
||||
dispatch_one(Void::Async::OperationOptions options = {});
|
||||
|
||||
/// Stop materialization/dispatch, signal stop to active handlers,
|
||||
/// and wait up to `options.deadline` for live handlers to exit.
|
||||
/// Never erases running records or abandons active frames.
|
||||
[[nodiscard]] Result<ShutdownReport>
|
||||
close_and_join(Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Result<std::vector<JobRecord>> list_jobs() const;
|
||||
[[nodiscard]] Result<std::vector<OccurrenceRecord>>
|
||||
list_occurrences() const;
|
||||
[[nodiscard]] Result<void>
|
||||
acknowledge_dead(const OccurrenceId& id);
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
prune_completed(std::size_t max_count = 256);
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
reclaim_invalidated(std::size_t max_count = 256);
|
||||
[[nodiscard]] Result<StoreStats> stats() const;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
explicit Scheduler(std::shared_ptr<State> state) noexcept;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,105 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
/// Persistence port for Scheduler state transitions.
|
||||
/// Implementations guarantee atomic conditional commits (in-memory mutex
|
||||
/// or `Void::Storage::Engine` conditional batches).
|
||||
class JobStore
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~JobStore() = default;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
acquire_ownership(std::string_view owner_id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void> release_ownership() = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void> put_job(const JobRecord& job) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
update_job(const JobRecord& updated,
|
||||
std::uint64_t expected_revision) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
tombstone_job(std::string_view job_id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::vector<JobRecord>>
|
||||
load_jobs() const = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::vector<OccurrenceRecord>>
|
||||
load_occurrences() const = 0;
|
||||
|
||||
/// Atomically insert new occurrences (enforcing unique
|
||||
/// `(job, revision, intended_utc_ms, fold_index)` dedup and
|
||||
/// retention cap) AND advance the job's cursor/sequence.
|
||||
[[nodiscard]] virtual Result<std::size_t> materialize_occurrences(
|
||||
std::string_view job_id, std::uint64_t expected_revision,
|
||||
std::int64_t new_cursor_utc_ms,
|
||||
std::int64_t new_cursor_monotonic_ns, bool cursor_initialized,
|
||||
bool one_shot_materialized, std::uint64_t next_sequence,
|
||||
const std::vector<OccurrenceRecord>& records) = 0;
|
||||
|
||||
/// Atomically verify job is not tombstoned, check old-revision
|
||||
/// invalidation watermark, and transition `Pending -> Running`
|
||||
/// bumping `attempt`.
|
||||
[[nodiscard]] virtual Result<OccurrenceRecord>
|
||||
claim_occurrence(const OccurrenceId& id,
|
||||
std::uint32_t expected_attempt) = 0;
|
||||
|
||||
/// Atomically transition `Running -> Completed` and optionally
|
||||
/// advance a FixedDelay job's monotonic cursor.
|
||||
[[nodiscard]] virtual Result<void> complete_occurrence(
|
||||
const OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t completed_utc_ms,
|
||||
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
|
||||
std::nullopt) = 0;
|
||||
|
||||
/// Atomically transition `Running -> Pending` (retry) or
|
||||
/// `Running -> Dead` (exhausted).
|
||||
[[nodiscard]] virtual Result<void> fail_occurrence(
|
||||
const OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t next_due_monotonic_ns,
|
||||
std::int64_t next_due_utc_ms, bool mark_dead,
|
||||
std::string diagnostic_category) = 0;
|
||||
|
||||
/// Return a `Running` occurrence to `Pending` during host shutdown
|
||||
/// without consuming a retry attempt.
|
||||
[[nodiscard]] virtual Result<void>
|
||||
requeue_on_shutdown(const OccurrenceId& id,
|
||||
std::uint32_t attempt) = 0;
|
||||
|
||||
/// Startup recovery: return every `Running` record to `Pending`
|
||||
/// preserving its exact `OccurrenceId` and attempt counter.
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
recover_running_occurrences() = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
acknowledge_dead(const OccurrenceId& id) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
prune_completed(std::int64_t before_utc_ms,
|
||||
std::size_t max_count) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
reclaim_invalidated(std::size_t max_count) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<StoreStats> stats() const = 0;
|
||||
};
|
||||
|
||||
/// Default in-memory `JobStore` implementation requiring zero `Storage`
|
||||
/// dependency.
|
||||
[[nodiscard]] std::shared_ptr<JobStore>
|
||||
make_in_memory_job_store(SchedulerLimits limits = {});
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,339 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class SchedulerErrorCode : std::int32_t {
|
||||
None = 0,
|
||||
InvalidArgument = 1,
|
||||
InvalidRule = 2,
|
||||
UnsupportedTimezone = 3,
|
||||
NotFound = 4,
|
||||
Conflict = 5,
|
||||
Overloaded = 6,
|
||||
RetentionFull = 7,
|
||||
PersistenceError = 8,
|
||||
UnknownOutcome = 9,
|
||||
HandlerFailed = 10,
|
||||
Cancelled = 11,
|
||||
Closed = 12,
|
||||
SelfJoin = 13,
|
||||
OwnershipLocked = 14,
|
||||
CorruptRecord = 15,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_scheduler_error(SchedulerErrorCode code,
|
||||
std::string message)
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case SchedulerErrorCode::None:
|
||||
case SchedulerErrorCode::HandlerFailed:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SchedulerErrorCode::InvalidArgument:
|
||||
case SchedulerErrorCode::InvalidRule:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case SchedulerErrorCode::UnsupportedTimezone:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case SchedulerErrorCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case SchedulerErrorCode::Conflict:
|
||||
case SchedulerErrorCode::UnknownOutcome:
|
||||
case SchedulerErrorCode::SelfJoin:
|
||||
case SchedulerErrorCode::OwnershipLocked:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case SchedulerErrorCode::Overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case SchedulerErrorCode::RetentionFull:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case SchedulerErrorCode::PersistenceError:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case SchedulerErrorCode::CorruptRecord:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case SchedulerErrorCode::Cancelled:
|
||||
case SchedulerErrorCode::Closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kSchedulerErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct OccurrenceId {
|
||||
std::string job_id{};
|
||||
std::uint64_t revision{0};
|
||||
std::uint64_t sequence{0};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const OccurrenceId&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] std::string to_idempotency_key() const
|
||||
{
|
||||
return job_id + "#" + std::to_string(revision) + "#" +
|
||||
std::to_string(sequence);
|
||||
}
|
||||
};
|
||||
|
||||
enum class MisfirePolicy : std::uint8_t {
|
||||
Skip = 0,
|
||||
CoalesceLatest = 1,
|
||||
CatchUpBounded = 2,
|
||||
};
|
||||
|
||||
enum class OverlapPolicy : std::uint8_t {
|
||||
Forbid = 0,
|
||||
QueueOne = 1,
|
||||
AllowBounded = 2,
|
||||
};
|
||||
|
||||
enum class DstGapPolicy : std::uint8_t {
|
||||
Skip = 0,
|
||||
NextValid = 1,
|
||||
};
|
||||
|
||||
enum class DstFoldPolicy : std::uint8_t {
|
||||
First = 0,
|
||||
Second = 1,
|
||||
Twice = 2,
|
||||
};
|
||||
|
||||
enum class ScheduleKind : std::uint8_t {
|
||||
OneShot = 0,
|
||||
FixedDelay = 1,
|
||||
FixedRate = 2,
|
||||
Calendar = 3,
|
||||
};
|
||||
|
||||
struct RetryPolicy {
|
||||
std::uint32_t max_attempts{5};
|
||||
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
|
||||
std::chrono::milliseconds max_delay{std::chrono::minutes{5}};
|
||||
std::uint32_t multiplier{2};
|
||||
};
|
||||
|
||||
struct CalendarSpec {
|
||||
std::string expression{};
|
||||
std::string timezone{"UTC"};
|
||||
std::uint32_t tz_data_version{1};
|
||||
DstGapPolicy gap_policy{DstGapPolicy::Skip};
|
||||
DstFoldPolicy fold_policy{DstFoldPolicy::First};
|
||||
};
|
||||
|
||||
struct Schedule {
|
||||
ScheduleKind kind{ScheduleKind::OneShot};
|
||||
std::int64_t start_utc_ms{0};
|
||||
std::optional<Void::Time::MonotonicClock::time_point>
|
||||
due_monotonic{};
|
||||
std::chrono::milliseconds interval{0};
|
||||
CalendarSpec calendar{};
|
||||
|
||||
[[nodiscard]] static Schedule
|
||||
one_shot_monotonic(Void::Time::MonotonicClock::time_point due)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::OneShot;
|
||||
s.due_monotonic = due;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule one_shot_utc(std::int64_t utc_ms)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::OneShot;
|
||||
s.start_utc_ms = utc_ms;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule fixed_delay(
|
||||
std::chrono::milliseconds delay,
|
||||
std::optional<Void::Time::MonotonicClock::time_point>
|
||||
first_due = std::nullopt)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::FixedDelay;
|
||||
s.interval = delay;
|
||||
s.due_monotonic = first_due;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule fixed_rate(
|
||||
std::chrono::milliseconds period,
|
||||
std::optional<Void::Time::MonotonicClock::time_point>
|
||||
first_due = std::nullopt)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::FixedRate;
|
||||
s.interval = period;
|
||||
s.due_monotonic = first_due;
|
||||
return s;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Schedule calendar_schedule(CalendarSpec spec)
|
||||
{
|
||||
Schedule s{};
|
||||
s.kind = ScheduleKind::Calendar;
|
||||
s.calendar = std::move(spec);
|
||||
return s;
|
||||
}
|
||||
};
|
||||
|
||||
struct JobSpec {
|
||||
std::string id{};
|
||||
Schedule schedule{};
|
||||
std::string handler_id{};
|
||||
std::uint32_t payload_schema{1};
|
||||
std::vector<std::byte> payload{};
|
||||
MisfirePolicy misfire{MisfirePolicy::CoalesceLatest};
|
||||
OverlapPolicy overlap{OverlapPolicy::Forbid};
|
||||
std::uint32_t max_concurrent{1};
|
||||
RetryPolicy retry{};
|
||||
};
|
||||
|
||||
enum class OccurrenceStatus : std::uint8_t {
|
||||
Pending = 0,
|
||||
Running = 1,
|
||||
Completed = 2,
|
||||
Dead = 3,
|
||||
Cancelled = 4,
|
||||
};
|
||||
|
||||
struct JobRecord {
|
||||
std::uint32_t format_version{1};
|
||||
JobSpec spec{};
|
||||
std::uint64_t revision{1};
|
||||
/// Unstarted occurrences with `revision < invalidated_before_revision`
|
||||
/// are logically cancelled and cannot be claimed.
|
||||
std::uint64_t invalidated_before_revision{1};
|
||||
bool tombstoned{false};
|
||||
std::int64_t cursor_utc_ms{0};
|
||||
std::int64_t cursor_monotonic_ns{0};
|
||||
bool cursor_initialized{false};
|
||||
bool one_shot_materialized{false};
|
||||
std::uint64_t next_sequence{1};
|
||||
};
|
||||
|
||||
struct OccurrenceRecord {
|
||||
std::uint32_t format_version{1};
|
||||
OccurrenceId id{};
|
||||
std::int64_t intended_utc_ms{0};
|
||||
std::int64_t due_monotonic_ns{0};
|
||||
std::uint8_t fold_index{0};
|
||||
OccurrenceStatus status{OccurrenceStatus::Pending};
|
||||
std::uint32_t attempt{0};
|
||||
std::string handler_id{};
|
||||
std::uint32_t payload_schema{1};
|
||||
std::vector<std::byte> payload{};
|
||||
std::string diagnostic_category{};
|
||||
std::int64_t completed_utc_ms{0};
|
||||
bool dead_acknowledged{false};
|
||||
};
|
||||
|
||||
struct SchedulerLimits {
|
||||
std::size_t max_jobs{10000};
|
||||
std::size_t max_retained_occurrences{100000};
|
||||
std::size_t max_payload_bytes{64ULL * 1024};
|
||||
std::size_t max_loaded_payload_bytes{16ULL * 1024 * 1024};
|
||||
std::size_t max_ready_dispatches{256};
|
||||
std::size_t max_active_handlers{32};
|
||||
std::size_t max_catch_up_per_job_per_pass{100};
|
||||
std::size_t max_retries_per_turn{64};
|
||||
std::size_t max_durable_batch_bytes{1024ULL * 1024};
|
||||
std::chrono::milliseconds completed_retention{
|
||||
std::chrono::hours{24 * 7}};
|
||||
};
|
||||
|
||||
struct ShutdownReport {
|
||||
bool complete{true};
|
||||
std::vector<OccurrenceId> live_occurrences{};
|
||||
};
|
||||
|
||||
struct StoreStats {
|
||||
std::size_t jobs{0};
|
||||
std::size_t pending{0};
|
||||
std::size_t running{0};
|
||||
std::size_t completed{0};
|
||||
std::size_t dead{0};
|
||||
std::size_t cancelled{0};
|
||||
std::size_t total_retained{0};
|
||||
bool retention_saturated{false};
|
||||
};
|
||||
|
||||
enum class ObservationKind : std::uint8_t {
|
||||
Materialize = 0,
|
||||
Dispatch = 1,
|
||||
Complete = 2,
|
||||
Retry = 3,
|
||||
DeadLetter = 4,
|
||||
RetentionPause = 5,
|
||||
Recover = 6,
|
||||
};
|
||||
|
||||
struct ObservationEvent {
|
||||
ObservationKind kind{ObservationKind::Dispatch};
|
||||
std::size_t count{1};
|
||||
std::int64_t lag_ms{0};
|
||||
};
|
||||
|
||||
using ObservationHook = std::function<void(const ObservationEvent&)>;
|
||||
using RandomU64Fn = std::function<std::uint64_t()>;
|
||||
|
||||
struct OccurrenceContext {
|
||||
OccurrenceId id{};
|
||||
std::uint32_t attempt{1};
|
||||
std::uint32_t payload_schema{1};
|
||||
std::int64_t intended_utc_ms{0};
|
||||
std::uint8_t fold_index{0};
|
||||
};
|
||||
|
||||
using HandlerFn = std::function<Result<void>(
|
||||
const OccurrenceContext&, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions)>;
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_ns(Void::Time::MonotonicClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Scheduler/Store.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Void::SchedulerStorage
|
||||
{
|
||||
struct StorageJobStoreOptions {
|
||||
Void::Scheduler::SchedulerLimits limits{};
|
||||
/// Key prefix namespace within the shared `Void::Storage::Engine`.
|
||||
std::string key_prefix{"sched:v1:"};
|
||||
/// Set true only when explicitly recovering after a process crash
|
||||
/// where the previous owner exited without calling
|
||||
/// `release_ownership()` (the underlying `Storage::Engine` OS lock
|
||||
/// guarantees single-process directory ownership).
|
||||
bool recover_stale_owner{false};
|
||||
};
|
||||
|
||||
/// Durable `Void::Scheduler::JobStore` backed by `Void::Storage::Engine`
|
||||
/// conditional `Batch` writes (`Durability::Sync`, 1 MiB batch cap,
|
||||
/// exclusive logical owner lock, unique civil-slot dedup index, and
|
||||
/// `UnknownOutcome` propagation).
|
||||
class StorageJobStore final : public Void::Scheduler::JobStore
|
||||
{
|
||||
public:
|
||||
|
||||
StorageJobStore(Void::Storage::Engine& engine,
|
||||
StorageJobStoreOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
acquire_ownership(std::string_view owner_id) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
release_ownership() override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
put_job(const Void::Scheduler::JobRecord& job) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
update_job(const Void::Scheduler::JobRecord& updated,
|
||||
std::uint64_t expected_revision) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
tombstone_job(std::string_view job_id) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<
|
||||
std::vector<Void::Scheduler::JobRecord>>
|
||||
load_jobs() const override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<
|
||||
std::vector<Void::Scheduler::OccurrenceRecord>>
|
||||
load_occurrences() const override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
materialize_occurrences(
|
||||
std::string_view job_id, std::uint64_t expected_revision,
|
||||
std::int64_t new_cursor_utc_ms,
|
||||
std::int64_t new_cursor_monotonic_ns,
|
||||
bool cursor_initialized, bool one_shot_materialized,
|
||||
std::uint64_t next_sequence,
|
||||
const std::vector<Void::Scheduler::OccurrenceRecord>&
|
||||
records) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<
|
||||
Void::Scheduler::OccurrenceRecord>
|
||||
claim_occurrence(const Void::Scheduler::OccurrenceId& id,
|
||||
std::uint32_t expected_attempt) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void> complete_occurrence(
|
||||
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t completed_utc_ms,
|
||||
std::optional<std::int64_t> fixed_delay_next_monotonic_ns =
|
||||
std::nullopt) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void> fail_occurrence(
|
||||
const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt,
|
||||
std::int64_t next_due_monotonic_ns,
|
||||
std::int64_t next_due_utc_ms, bool mark_dead,
|
||||
std::string diagnostic_category) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
requeue_on_shutdown(const Void::Scheduler::OccurrenceId& id,
|
||||
std::uint32_t attempt) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
recover_running_occurrences() override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<void>
|
||||
acknowledge_dead(const Void::Scheduler::OccurrenceId& id) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
prune_completed(std::int64_t before_utc_ms,
|
||||
std::size_t max_count) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<std::size_t>
|
||||
reclaim_invalidated(std::size_t max_count) override;
|
||||
|
||||
[[nodiscard]] Void::Scheduler::Result<Void::Scheduler::StoreStats>
|
||||
stats() const override;
|
||||
|
||||
private:
|
||||
|
||||
Void::Storage::Engine* m_engine{nullptr};
|
||||
StorageJobStoreOptions m_options{};
|
||||
std::string m_owner_id{};
|
||||
};
|
||||
|
||||
} // namespace Void::SchedulerStorage
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(Discovery
|
||||
INTERNAL_DEPS Core Functional Time Async
|
||||
)
|
||||
@@ -0,0 +1,144 @@
|
||||
#include <Void/DiscoveryRpc/EndpointAdapter.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::DiscoveryRpc
|
||||
{
|
||||
namespace
|
||||
{
|
||||
struct OutstandingGuard {
|
||||
std::atomic<std::size_t>& counter;
|
||||
~OutstandingGuard() noexcept
|
||||
{
|
||||
counter.fetch_sub(1, std::memory_order_acq_rel);
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
EndpointResolverClient::EndpointResolverClient(
|
||||
const Void::Discovery::Catalog& catalog,
|
||||
EndpointResolverOptions options)
|
||||
: m_catalog(&catalog), m_options(std::move(options))
|
||||
{
|
||||
if (m_options.clock == nullptr) {
|
||||
m_options.clock = &Void::Time::SystemMonotonicClock::instance();
|
||||
}
|
||||
if (m_options.require_tls) {
|
||||
m_options.http_options.verify_tls = true;
|
||||
}
|
||||
}
|
||||
|
||||
Void::Discovery::Result<SelectedEndpoint>
|
||||
EndpointResolverClient::select_endpoint(
|
||||
std::optional<std::string_view> affinity_key)
|
||||
{
|
||||
if (m_catalog == nullptr) {
|
||||
return Void::Result::fail(Void::Discovery::make_discovery_error(
|
||||
Void::Discovery::DiscoveryErrorCode::InvalidArgument,
|
||||
"EndpointResolverClient: null catalog"));
|
||||
}
|
||||
|
||||
auto snap =
|
||||
m_catalog->resolve(m_options.service, m_options.resolve_policy);
|
||||
if (!snap.has_value()) {
|
||||
return Void::Result::fail(snap.error());
|
||||
}
|
||||
|
||||
auto selected =
|
||||
affinity_key.has_value()
|
||||
? Void::Discovery::AffinitySelector::select(*snap, *affinity_key)
|
||||
: m_rr.select(*snap);
|
||||
if (!selected.has_value()) {
|
||||
return Void::Result::fail(selected.error());
|
||||
}
|
||||
|
||||
if (m_options.require_tls && selected->endpoint.scheme != "https") {
|
||||
return Void::Result::fail(Void::Discovery::make_discovery_error(
|
||||
Void::Discovery::DiscoveryErrorCode::TlsIdentityMismatch,
|
||||
"EndpointResolverClient: refusing non-TLS endpoint when "
|
||||
"require_tls is enabled"));
|
||||
}
|
||||
|
||||
const std::string effective_tls{
|
||||
selected->endpoint.effective_tls_name()};
|
||||
if (!m_options.expected_tls_name.empty() &&
|
||||
effective_tls != m_options.expected_tls_name) {
|
||||
return Void::Result::fail(Void::Discovery::make_discovery_error(
|
||||
Void::Discovery::DiscoveryErrorCode::TlsIdentityMismatch,
|
||||
"EndpointResolverClient: endpoint TLS identity mismatch "
|
||||
"(expected '" +
|
||||
m_options.expected_tls_name + "', got '" + effective_tls +
|
||||
"')"));
|
||||
}
|
||||
|
||||
SelectedEndpoint out{};
|
||||
out.origin_url = selected->endpoint.to_origin_url();
|
||||
out.effective_tls_name = effective_tls;
|
||||
out.record = std::move(*selected);
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<Void::RPC::OwnedBytes>
|
||||
EndpointResolverClient::call(
|
||||
Void::RPC::MethodId method, Void::RPC::OwnedBytes payload,
|
||||
Void::RPC::CallOptions options,
|
||||
std::optional<std::string_view> affinity_key)
|
||||
{
|
||||
// Enforce bounded outstanding operations.
|
||||
std::size_t cur = m_outstanding.load(std::memory_order_acquire);
|
||||
for (;;) {
|
||||
if (cur >= m_options.max_outstanding_ops) {
|
||||
return Void::Result::fail(Void::Discovery::make_discovery_error(
|
||||
Void::Discovery::DiscoveryErrorCode::LimitExceeded,
|
||||
"EndpointResolverClient: max_outstanding_ops reached"));
|
||||
}
|
||||
if (m_outstanding.compare_exchange_weak(
|
||||
cur, cur + 1, std::memory_order_acq_rel,
|
||||
std::memory_order_acquire)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
OutstandingGuard guard{m_outstanding};
|
||||
|
||||
auto selected = select_endpoint(affinity_key);
|
||||
if (!selected.has_value()) {
|
||||
return Void::Result::fail(selected.error());
|
||||
}
|
||||
|
||||
Void::RPC::ClientOptions copts{};
|
||||
copts.endpoint_base_url = selected->origin_url;
|
||||
copts.http_options = m_options.http_options;
|
||||
if (m_options.require_tls) {
|
||||
copts.http_options.verify_tls = true;
|
||||
}
|
||||
copts.limits = m_options.rpc_limits;
|
||||
copts.clock = m_options.clock;
|
||||
|
||||
if (options.timeout <= std::chrono::milliseconds{0} ||
|
||||
options.timeout > m_options.total_deadline) {
|
||||
options.timeout = m_options.total_deadline;
|
||||
}
|
||||
// Retain peer identity header when address refreshes to an IP while
|
||||
// expected_tls_name preserves the logical authority.
|
||||
if (!selected->record.endpoint.expected_tls_name.empty()) {
|
||||
bool has_authority = false;
|
||||
for (const auto& m : options.metadata) {
|
||||
if (m.key == "void-expected-authority") {
|
||||
has_authority = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!has_authority) {
|
||||
options.metadata.push_back(Void::RPC::MetadataEntry{
|
||||
.key = "void-expected-authority",
|
||||
.value = selected->effective_tls_name,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Void::RPC::Client client{std::move(copts)};
|
||||
return client.call(method, std::move(payload), options);
|
||||
}
|
||||
|
||||
} // namespace Void::DiscoveryRpc
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(DiscoveryRpc
|
||||
INTERNAL_DEPS Discovery RPC
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(Messaging
|
||||
INTERNAL_DEPS Core Functional Binary Time Async
|
||||
)
|
||||
@@ -0,0 +1,513 @@
|
||||
#include <Void/MessagingRpc/RpcAdapter.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::MessagingRpc
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using Void::Messaging::Result;
|
||||
|
||||
namespace
|
||||
{
|
||||
void put_u8(Void::RPC::OwnedBytes& out, std::uint8_t v)
|
||||
{
|
||||
out.push_back(static_cast<std::byte>(v));
|
||||
}
|
||||
|
||||
void put_u32(Void::RPC::OwnedBytes& out, std::uint32_t v)
|
||||
{
|
||||
out.push_back(static_cast<std::byte>((v >> 24U) & 0xFFU));
|
||||
out.push_back(static_cast<std::byte>((v >> 16U) & 0xFFU));
|
||||
out.push_back(static_cast<std::byte>((v >> 8U) & 0xFFU));
|
||||
out.push_back(static_cast<std::byte>(v & 0xFFU));
|
||||
}
|
||||
|
||||
void put_u64(Void::RPC::OwnedBytes& out, std::uint64_t v)
|
||||
{
|
||||
for (int shift = 56; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((v >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
void put_i64(Void::RPC::OwnedBytes& out, std::int64_t v)
|
||||
{
|
||||
put_u64(out, static_cast<std::uint64_t>(v));
|
||||
}
|
||||
|
||||
void put_str(Void::RPC::OwnedBytes& out, std::string_view s)
|
||||
{
|
||||
put_u32(out, static_cast<std::uint32_t>(s.size()));
|
||||
for (char c : s) {
|
||||
out.push_back(static_cast<std::byte>(c));
|
||||
}
|
||||
}
|
||||
|
||||
void put_bytes(Void::RPC::OwnedBytes& out,
|
||||
const std::vector<std::byte>& b)
|
||||
{
|
||||
put_u32(out, static_cast<std::uint32_t>(b.size()));
|
||||
out.insert(out.end(), b.begin(), b.end());
|
||||
}
|
||||
|
||||
void put_message(Void::RPC::OwnedBytes& out, const Message& m)
|
||||
{
|
||||
put_str(out, m.id);
|
||||
put_u32(out, m.schema_version);
|
||||
put_bytes(out, m.payload);
|
||||
put_u32(out, static_cast<std::uint32_t>(m.headers.size()));
|
||||
for (const auto& [k, v] : m.headers) {
|
||||
put_str(out, k);
|
||||
put_str(out, v);
|
||||
}
|
||||
}
|
||||
|
||||
void put_receipt(Void::RPC::OwnedBytes& out, const Receipt& r)
|
||||
{
|
||||
put_str(out, r.queue);
|
||||
put_str(out, r.group);
|
||||
put_str(out, r.message_id);
|
||||
put_u64(out, r.sequence);
|
||||
put_u64(out, r.generation);
|
||||
}
|
||||
|
||||
struct Cursor {
|
||||
std::span<const std::byte> data{};
|
||||
std::size_t pos{0};
|
||||
|
||||
[[nodiscard]] bool read_u8(std::uint8_t& v) noexcept
|
||||
{
|
||||
if (pos + 1U > data.size()) return false;
|
||||
v = std::to_integer<std::uint8_t>(data[pos++]);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u32(std::uint32_t& v) noexcept
|
||||
{
|
||||
if (pos + 4U > data.size()) return false;
|
||||
v = (static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos]))
|
||||
<< 24U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + 1]))
|
||||
<< 16U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + 2]))
|
||||
<< 8U) |
|
||||
static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + 3]));
|
||||
pos += 4U;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u64(std::uint64_t& v) noexcept
|
||||
{
|
||||
if (pos + 8U > data.size()) return false;
|
||||
v = 0;
|
||||
for (std::size_t i = 0; i < 8U; ++i) {
|
||||
v = (v << 8U) |
|
||||
static_cast<std::uint64_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + i]));
|
||||
}
|
||||
pos += 8U;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_i64(std::int64_t& v) noexcept
|
||||
{
|
||||
std::uint64_t u = 0;
|
||||
if (!read_u64(u)) return false;
|
||||
v = static_cast<std::int64_t>(u);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_str(std::string& s)
|
||||
{
|
||||
std::uint32_t len = 0;
|
||||
if (!read_u32(len) || pos + len > data.size()) return false;
|
||||
s.resize(len);
|
||||
if (len > 0U) {
|
||||
std::memcpy(s.data(), data.data() + pos, len);
|
||||
}
|
||||
pos += len;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_bytes(std::vector<std::byte>& b)
|
||||
{
|
||||
std::uint32_t len = 0;
|
||||
if (!read_u32(len) || pos + len > data.size()) return false;
|
||||
b.resize(len);
|
||||
if (len > 0U) {
|
||||
std::memcpy(b.data(), data.data() + pos, len);
|
||||
}
|
||||
pos += len;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_message(Message& m)
|
||||
{
|
||||
std::uint32_t hcount = 0;
|
||||
if (!read_str(m.id) || !read_u32(m.schema_version) ||
|
||||
!read_bytes(m.payload) || !read_u32(hcount)) {
|
||||
return false;
|
||||
}
|
||||
m.headers.clear();
|
||||
for (std::uint32_t i = 0; i < hcount; ++i) {
|
||||
std::string k, v;
|
||||
if (!read_str(k) || !read_str(v)) return false;
|
||||
m.headers.emplace(std::move(k), std::move(v));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_receipt(Receipt& r)
|
||||
{
|
||||
return read_str(r.queue) && read_str(r.group) &&
|
||||
read_str(r.message_id) && read_u64(r.sequence) &&
|
||||
read_u64(r.generation);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool eof() const noexcept
|
||||
{
|
||||
return pos == data.size();
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Error
|
||||
map_rpc_err(const Void::Result::Error& err)
|
||||
{
|
||||
if (err.code().domain == Void::Result::kMessagingErrorDomain) {
|
||||
return err;
|
||||
}
|
||||
const auto status = Void::RPC::rpc_status_from_error(err);
|
||||
if (status == Void::RPC::RpcStatusCode::UnknownOutcome) {
|
||||
return make_messaging_error(MessagingErrorCode::UnknownOutcome,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::FailedPrecondition) {
|
||||
return make_messaging_error(MessagingErrorCode::StaleReceipt,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::NotFound) {
|
||||
return make_messaging_error(MessagingErrorCode::NotFound,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::ResourceExhausted) {
|
||||
return make_messaging_error(MessagingErrorCode::QuotaExceeded,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::DeadlineExceeded) {
|
||||
return make_messaging_error(MessagingErrorCode::Timeout,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::Cancelled) {
|
||||
return make_messaging_error(MessagingErrorCode::Cancelled,
|
||||
err.message());
|
||||
}
|
||||
return make_messaging_error(MessagingErrorCode::PersistenceError,
|
||||
err.message());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
RpcQueueServer::~RpcQueueServer() noexcept { unmount_and_drain(); }
|
||||
|
||||
void RpcQueueServer::unmount_and_drain() noexcept
|
||||
{
|
||||
for (auto& reg : m_registrations) {
|
||||
reg.unregister_and_drain();
|
||||
}
|
||||
m_registrations.clear();
|
||||
}
|
||||
|
||||
Result<void> RpcQueueServer::mount(Void::RPC::Server& server, Queue& queue)
|
||||
{
|
||||
auto bind_one = [&](Void::RPC::MethodId id, std::string name,
|
||||
Void::RPC::UnaryHandler handler) -> Result<void> {
|
||||
auto reg = server.bind(
|
||||
Void::RPC::MethodDescriptor{
|
||||
.id = id,
|
||||
.service_name = "void.messaging.v1",
|
||||
.method_name = std::move(name),
|
||||
.schema_version = 1,
|
||||
},
|
||||
std::move(handler));
|
||||
if (!reg.has_value()) {
|
||||
return Void::Result::fail(reg.error());
|
||||
}
|
||||
m_registrations.push_back(std::move(*reg));
|
||||
return {};
|
||||
};
|
||||
|
||||
if (auto r = bind_one(
|
||||
kPublishMethod, "publish",
|
||||
[&queue](const Void::RPC::CallContext& ctx,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
std::string qname;
|
||||
std::uint8_t dur = 0;
|
||||
Message msg{};
|
||||
if (!c.read_str(qname) || !c.read_u8(dur) ||
|
||||
!c.read_message(msg) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed publish request"));
|
||||
}
|
||||
Void::Async::OperationOptions opts{.stop = ctx.stop};
|
||||
auto res = queue.publish(
|
||||
qname, std::move(msg),
|
||||
static_cast<PublishDurability>(dur), opts);
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
Void::RPC::OwnedBytes out;
|
||||
put_str(out, res->queue);
|
||||
put_str(out, res->message_id);
|
||||
put_u64(out, res->sequence);
|
||||
put_u8(out, static_cast<std::uint8_t>(res->durability));
|
||||
put_u8(out, res->deduplicated ? 1U : 0U);
|
||||
return out;
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kTryReceiveMethod, "try_receive",
|
||||
[&queue](const Void::RPC::CallContext&,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
std::string qname, gname;
|
||||
if (!c.read_str(qname) || !c.read_str(gname) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed try_receive request"));
|
||||
}
|
||||
auto res = queue.try_receive(qname, gname);
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
Void::RPC::OwnedBytes out;
|
||||
if (!res->has_value()) {
|
||||
put_u8(out, 0U);
|
||||
return out;
|
||||
}
|
||||
put_u8(out, 1U);
|
||||
put_message(out, (*res)->message);
|
||||
put_receipt(out, (*res)->receipt);
|
||||
put_u32(out, (*res)->attempt);
|
||||
put_i64(out, to_mono_ns((*res)->visibility_deadline));
|
||||
return out;
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kAckMethod, "ack",
|
||||
[&queue](const Void::RPC::CallContext& ctx,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
Receipt rec{};
|
||||
if (!c.read_receipt(rec) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed ack request"));
|
||||
}
|
||||
auto res =
|
||||
queue.ack(rec, Void::Async::OperationOptions{.stop = ctx.stop});
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
return Void::RPC::OwnedBytes{};
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kNackMethod, "nack",
|
||||
[&queue](const Void::RPC::CallContext& ctx,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
Receipt rec{};
|
||||
std::uint8_t has_delay = 0;
|
||||
std::int64_t delay_ms = 0;
|
||||
if (!c.read_receipt(rec) || !c.read_u8(has_delay) ||
|
||||
!c.read_i64(delay_ms) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed nack request"));
|
||||
}
|
||||
std::optional<std::chrono::milliseconds> d{};
|
||||
if (has_delay != 0U) {
|
||||
d = std::chrono::milliseconds{delay_ms};
|
||||
}
|
||||
auto res = queue.nack(
|
||||
rec, d, Void::Async::OperationOptions{.stop = ctx.stop});
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
return Void::RPC::OwnedBytes{};
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kQueryReceiptMethod, "query_receipt",
|
||||
[&queue](const Void::RPC::CallContext&,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
Receipt rec{};
|
||||
if (!c.read_receipt(rec) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed query_receipt request"));
|
||||
}
|
||||
auto res = queue.query_receipt(rec);
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
Void::RPC::OwnedBytes out;
|
||||
put_u8(out, static_cast<std::uint8_t>(*res));
|
||||
return out;
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── RpcQueueClient ────────────────────────────────────────────────────────
|
||||
|
||||
RpcQueueClient::RpcQueueClient(Void::RPC::ClientOptions options)
|
||||
: m_client(std::move(options))
|
||||
{
|
||||
}
|
||||
|
||||
Result<PublishReceipt> RpcQueueClient::publish(
|
||||
std::string_view queue, const Message& message,
|
||||
PublishDurability durability, const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_str(req, queue);
|
||||
put_u8(req, static_cast<std::uint8_t>(durability));
|
||||
put_message(req, message);
|
||||
|
||||
auto resp = m_client.call(kPublishMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
Cursor c{*resp, 0};
|
||||
PublishReceipt pr{};
|
||||
std::uint8_t dur = 0, dedup = 0;
|
||||
if (!c.read_str(pr.queue) || !c.read_str(pr.message_id) ||
|
||||
!c.read_u64(pr.sequence) || !c.read_u8(dur) || !c.read_u8(dedup) ||
|
||||
!c.eof()) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt publish response"));
|
||||
}
|
||||
pr.durability = static_cast<PublishDurability>(dur);
|
||||
pr.deduplicated = (dedup != 0U);
|
||||
return pr;
|
||||
}
|
||||
|
||||
Result<std::optional<Delivery>>
|
||||
RpcQueueClient::try_receive(std::string_view queue,
|
||||
std::string_view group,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_str(req, queue);
|
||||
put_str(req, group);
|
||||
|
||||
auto resp = m_client.call(kTryReceiveMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
Cursor c{*resp, 0};
|
||||
std::uint8_t present = 0;
|
||||
if (!c.read_u8(present)) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt try_receive response"));
|
||||
}
|
||||
if (present == 0U) {
|
||||
return std::optional<Delivery>{std::nullopt};
|
||||
}
|
||||
Delivery d{};
|
||||
std::int64_t dl_ns = 0;
|
||||
if (!c.read_message(d.message) || !c.read_receipt(d.receipt) ||
|
||||
!c.read_u32(d.attempt) || !c.read_i64(dl_ns) || !c.eof()) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt delivery response"));
|
||||
}
|
||||
d.visibility_deadline = Void::Time::MonotonicClock::time_point{
|
||||
std::chrono::duration_cast<
|
||||
Void::Time::MonotonicClock::time_point::duration>(
|
||||
std::chrono::nanoseconds{dl_ns})};
|
||||
return std::optional<Delivery>{std::move(d)};
|
||||
}
|
||||
|
||||
Result<void> RpcQueueClient::ack(const Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_receipt(req, receipt);
|
||||
auto resp = m_client.call(kAckMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<void>
|
||||
RpcQueueClient::nack(const Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_receipt(req, receipt);
|
||||
put_u8(req, delay.has_value() ? 1U : 0U);
|
||||
put_i64(req, delay.has_value() ? delay->count() : 0LL);
|
||||
auto resp = m_client.call(kNackMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<DeliveryState>
|
||||
RpcQueueClient::query_receipt(const Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_receipt(req, receipt);
|
||||
auto resp = m_client.call(kQueryReceiptMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
Cursor c{*resp, 0};
|
||||
std::uint8_t st = 0;
|
||||
if (!c.read_u8(st) || !c.eof() ||
|
||||
st > static_cast<std::uint8_t>(DeliveryState::DeadLetter)) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt query_receipt response"));
|
||||
}
|
||||
return static_cast<DeliveryState>(st);
|
||||
}
|
||||
|
||||
} // namespace Void::MessagingRpc
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(MessagingRpc
|
||||
INTERNAL_DEPS Messaging RPC
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(MessagingStorage
|
||||
INTERNAL_DEPS Messaging Storage
|
||||
)
|
||||
@@ -0,0 +1,632 @@
|
||||
#include <Void/Scheduler/Calendar.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Scheduler
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// Howard Hinnant's exact civil-from-days / days-from-civil algorithms.
|
||||
[[nodiscard]] constexpr std::int64_t
|
||||
days_from_civil(std::int32_t y, std::uint32_t m,
|
||||
std::uint32_t d) noexcept
|
||||
{
|
||||
const std::int64_t y_adj = static_cast<std::int64_t>(y) - (m <= 2);
|
||||
const std::int64_t era =
|
||||
(y_adj >= 0 ? y_adj : y_adj - 399) / 400;
|
||||
const auto yoe =
|
||||
static_cast<std::uint64_t>(y_adj - era * 400); // [0, 399]
|
||||
const std::uint64_t doy =
|
||||
(153U * (m + (m > 2 ? static_cast<std::uint32_t>(-3) : 9U)) +
|
||||
2U) /
|
||||
5U +
|
||||
d - 1U; // [0, 365]
|
||||
const std::uint64_t doe =
|
||||
yoe * 365U + yoe / 4U - yoe / 100U + doy; // [0, 146096]
|
||||
return era * 146097 + static_cast<std::int64_t>(doe) - 719468;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool is_leap_year(std::int32_t y) noexcept
|
||||
{
|
||||
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::uint32_t
|
||||
days_in_month(std::int32_t y, std::uint32_t m) noexcept
|
||||
{
|
||||
switch (m) {
|
||||
case 1:
|
||||
case 3:
|
||||
case 5:
|
||||
case 7:
|
||||
case 8:
|
||||
case 10:
|
||||
case 12:
|
||||
return 31U;
|
||||
case 4:
|
||||
case 6:
|
||||
case 9:
|
||||
case 11:
|
||||
return 30U;
|
||||
case 2:
|
||||
return is_leap_year(y) ? 29U : 28U;
|
||||
default:
|
||||
return 30U;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<std::int32_t>
|
||||
parse_fixed_offset_minutes(std::string_view tz) noexcept
|
||||
{
|
||||
if (tz == "UTC" || tz == "Z") {
|
||||
return 0;
|
||||
}
|
||||
if (tz.starts_with("UTC")) {
|
||||
tz.remove_prefix(3U);
|
||||
}
|
||||
if (tz.size() != 6U || (tz[0] != '+' && tz[0] != '-') ||
|
||||
tz[3] != ':') {
|
||||
return std::nullopt;
|
||||
}
|
||||
const int sign = tz[0] == '-' ? -1 : 1;
|
||||
std::uint32_t hh = 0;
|
||||
std::uint32_t mm = 0;
|
||||
auto r1 = std::from_chars(tz.data() + 1, tz.data() + 3, hh);
|
||||
auto r2 = std::from_chars(tz.data() + 4, tz.data() + 6, mm);
|
||||
if (r1.ec != std::errc{} || r1.ptr != tz.data() + 3 ||
|
||||
r2.ec != std::errc{} || r2.ptr != tz.data() + 6 || hh > 14U ||
|
||||
mm > 59U || (hh == 14U && mm > 0U)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return sign * static_cast<std::int32_t>(hh * 60U + mm);
|
||||
}
|
||||
|
||||
[[nodiscard]] Result<std::uint64_t> parse_field(std::string_view field,
|
||||
std::uint32_t min_val,
|
||||
std::uint32_t max_val,
|
||||
bool map_7_to_0 = false)
|
||||
{
|
||||
if (field.empty()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar empty field"));
|
||||
}
|
||||
std::uint64_t mask = 0;
|
||||
std::size_t pos = 0;
|
||||
while (pos <= field.size()) {
|
||||
const std::size_t comma = field.find(',', pos);
|
||||
const std::string_view part =
|
||||
comma == std::string_view::npos
|
||||
? field.substr(pos)
|
||||
: field.substr(pos, comma - pos);
|
||||
if (part.empty()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar empty list item"));
|
||||
}
|
||||
|
||||
std::string_view range_part = part;
|
||||
std::uint32_t step = 1;
|
||||
if (const std::size_t slash = part.find('/');
|
||||
slash != std::string_view::npos) {
|
||||
range_part = part.substr(0, slash);
|
||||
const std::string_view step_sv = part.substr(slash + 1);
|
||||
if (step_sv.empty() || step_sv.find('/') !=
|
||||
std::string_view::npos) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar invalid step syntax"));
|
||||
}
|
||||
auto sr = std::from_chars(
|
||||
step_sv.data(), step_sv.data() + step_sv.size(), step);
|
||||
if (sr.ec != std::errc{} ||
|
||||
sr.ptr != step_sv.data() + step_sv.size() ||
|
||||
step == 0U) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar step must be positive"));
|
||||
}
|
||||
}
|
||||
|
||||
std::uint32_t lo = min_val;
|
||||
std::uint32_t hi = max_val;
|
||||
const std::uint32_t parse_max = map_7_to_0 ? 7U : max_val;
|
||||
|
||||
if (range_part == "*") {
|
||||
lo = min_val;
|
||||
hi = max_val;
|
||||
} else if (const std::size_t dash = range_part.find('-');
|
||||
dash != std::string_view::npos) {
|
||||
const std::string_view a_sv = range_part.substr(0, dash);
|
||||
const std::string_view b_sv = range_part.substr(dash + 1);
|
||||
if (a_sv.empty() || b_sv.empty() ||
|
||||
b_sv.find('-') != std::string_view::npos) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar invalid range syntax"));
|
||||
}
|
||||
auto r1 = std::from_chars(
|
||||
a_sv.data(), a_sv.data() + a_sv.size(), lo);
|
||||
auto r2 = std::from_chars(
|
||||
b_sv.data(), b_sv.data() + b_sv.size(), hi);
|
||||
if (r1.ec != std::errc{} ||
|
||||
r1.ptr != a_sv.data() + a_sv.size() ||
|
||||
r2.ec != std::errc{} ||
|
||||
r2.ptr != b_sv.data() + b_sv.size() || lo < min_val ||
|
||||
hi > parse_max || lo > hi) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar range bounds invalid"));
|
||||
}
|
||||
} else {
|
||||
std::uint32_t val = 0;
|
||||
auto rv = std::from_chars(
|
||||
range_part.data(),
|
||||
range_part.data() + range_part.size(), val);
|
||||
if (rv.ec != std::errc{} ||
|
||||
rv.ptr != range_part.data() + range_part.size() ||
|
||||
val < min_val || val > parse_max) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar field value out of range"));
|
||||
}
|
||||
lo = val;
|
||||
hi = (part.find('/') != std::string_view::npos) ? max_val
|
||||
: val;
|
||||
}
|
||||
|
||||
for (std::uint32_t v = lo; v <= hi; v += step) {
|
||||
const std::uint32_t bit =
|
||||
(map_7_to_0 && v == 7U) ? 0U : v;
|
||||
mask |= (1ULL << bit);
|
||||
if (hi - v < step) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (comma == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = comma + 1;
|
||||
}
|
||||
if (mask == 0ULL) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::Calendar field matched zero values"));
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::int64_t civil_to_epoch_minute(std::int32_t year, std::uint32_t month,
|
||||
std::uint32_t day, std::uint32_t hour,
|
||||
std::uint32_t minute) noexcept
|
||||
{
|
||||
const std::int64_t days = days_from_civil(year, month, day);
|
||||
return days * 1440LL + static_cast<std::int64_t>(hour) * 60LL +
|
||||
static_cast<std::int64_t>(minute);
|
||||
}
|
||||
|
||||
CivilMinute epoch_minute_to_civil(std::int64_t epoch_minute) noexcept
|
||||
{
|
||||
std::int64_t days = epoch_minute / 1440LL;
|
||||
std::int64_t rem = epoch_minute % 1440LL;
|
||||
if (rem < 0) {
|
||||
rem += 1440LL;
|
||||
--days;
|
||||
}
|
||||
const auto hour = static_cast<std::uint32_t>(rem / 60LL);
|
||||
const auto minute = static_cast<std::uint32_t>(rem % 60LL);
|
||||
|
||||
const std::int64_t z = days + 719468;
|
||||
const std::int64_t era = (z >= 0 ? z : z - 146096) / 146097;
|
||||
const auto doe =
|
||||
static_cast<std::uint64_t>(z - era * 146097); // [0, 146096]
|
||||
const std::uint64_t yoe =
|
||||
(doe - doe / 1460U + doe / 36524U - doe / 146096U) /
|
||||
365U; // [0, 399]
|
||||
const std::int64_t y = static_cast<std::int64_t>(yoe) + era * 400;
|
||||
const std::uint64_t doy =
|
||||
doe - (365U * yoe + yoe / 4U - yoe / 100U); // [0, 365]
|
||||
const std::uint64_t mp = (5U * doy + 2U) / 153U; // [0, 11]
|
||||
const auto d = static_cast<std::uint32_t>(
|
||||
doy - (153U * mp + 2U) / 5U + 1U); // [1, 31]
|
||||
const auto m =
|
||||
static_cast<std::uint32_t>(mp < 10U ? mp + 3U : mp - 9U); // [1, 12]
|
||||
const auto year = static_cast<std::int32_t>(y + (m <= 2U ? 1 : 0));
|
||||
|
||||
// 1970-01-01 was Thursday (4).
|
||||
std::int64_t wd = (days + 4LL) % 7LL;
|
||||
if (wd < 0) {
|
||||
wd += 7LL;
|
||||
}
|
||||
|
||||
return CivilMinute{
|
||||
.year = year,
|
||||
.month = m,
|
||||
.day = d,
|
||||
.hour = hour,
|
||||
.minute = minute,
|
||||
.weekday = static_cast<std::uint32_t>(wd),
|
||||
};
|
||||
}
|
||||
|
||||
// ── TimezoneRegistry ──────────────────────────────────────────────────────
|
||||
|
||||
void TimezoneRegistry::register_dst_zone(DstTransitionRule rule)
|
||||
{
|
||||
if (!rule.name.empty()) {
|
||||
m_dst_zones[rule.name] = std::move(rule);
|
||||
}
|
||||
}
|
||||
|
||||
Result<void> TimezoneRegistry::validate_timezone(std::string_view tz) const
|
||||
{
|
||||
if (parse_fixed_offset_minutes(tz).has_value() ||
|
||||
m_dst_zones.contains(tz)) {
|
||||
return {};
|
||||
}
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::UnsupportedTimezone,
|
||||
"Scheduler: unsupported or unknown timezone '" + std::string{tz} +
|
||||
"' (silent UTC fallback is forbidden)"));
|
||||
}
|
||||
|
||||
Result<std::vector<ResolvedSlot>> TimezoneRegistry::resolve_local_minute(
|
||||
std::string_view tz, std::int64_t local_epoch_minute,
|
||||
DstGapPolicy gap_policy, DstFoldPolicy fold_policy) const
|
||||
{
|
||||
if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) {
|
||||
const std::int64_t utc_min =
|
||||
local_epoch_minute - static_cast<std::int64_t>(*fixed);
|
||||
return std::vector<ResolvedSlot>{
|
||||
ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}};
|
||||
}
|
||||
|
||||
auto it = m_dst_zones.find(tz);
|
||||
if (it == m_dst_zones.end()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::UnsupportedTimezone,
|
||||
"Scheduler: unsupported timezone '" + std::string{tz} + "'"));
|
||||
}
|
||||
|
||||
const auto& rule = it->second;
|
||||
|
||||
// Check spring-forward gap window.
|
||||
if (rule.gap_start_local_min.has_value() &&
|
||||
rule.gap_end_local_min.has_value() &&
|
||||
local_epoch_minute >= *rule.gap_start_local_min &&
|
||||
local_epoch_minute < *rule.gap_end_local_min) {
|
||||
if (gap_policy == DstGapPolicy::Skip) {
|
||||
return std::vector<ResolvedSlot>{};
|
||||
}
|
||||
const std::int64_t shifted_utc_min =
|
||||
*rule.gap_end_local_min -
|
||||
static_cast<std::int64_t>(rule.dst_offset_minutes);
|
||||
return std::vector<ResolvedSlot>{ResolvedSlot{
|
||||
.utc_ms = shifted_utc_min * 60000LL,
|
||||
.fold_index = 0,
|
||||
}};
|
||||
}
|
||||
|
||||
// Check fall-back fold window.
|
||||
if (rule.fold_start_local_min.has_value() &&
|
||||
rule.fold_end_local_min.has_value() &&
|
||||
local_epoch_minute >= *rule.fold_start_local_min &&
|
||||
local_epoch_minute < *rule.fold_end_local_min) {
|
||||
const std::int64_t first_utc_min =
|
||||
local_epoch_minute -
|
||||
static_cast<std::int64_t>(rule.dst_offset_minutes);
|
||||
const std::int64_t second_utc_min =
|
||||
local_epoch_minute -
|
||||
static_cast<std::int64_t>(rule.standard_offset_minutes);
|
||||
switch (fold_policy) {
|
||||
case DstFoldPolicy::First:
|
||||
return std::vector<ResolvedSlot>{ResolvedSlot{
|
||||
.utc_ms = first_utc_min * 60000LL, .fold_index = 0}};
|
||||
case DstFoldPolicy::Second:
|
||||
return std::vector<ResolvedSlot>{ResolvedSlot{
|
||||
.utc_ms = second_utc_min * 60000LL, .fold_index = 1}};
|
||||
case DstFoldPolicy::Twice:
|
||||
return std::vector<ResolvedSlot>{
|
||||
ResolvedSlot{.utc_ms = first_utc_min * 60000LL,
|
||||
.fold_index = 0},
|
||||
ResolvedSlot{.utc_ms = second_utc_min * 60000LL,
|
||||
.fold_index = 1},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Outside gap/fold: determine whether DST or standard offset applies.
|
||||
bool in_dst = false;
|
||||
if (rule.gap_end_local_min.has_value() &&
|
||||
rule.fold_start_local_min.has_value()) {
|
||||
in_dst = (local_epoch_minute >= *rule.gap_end_local_min &&
|
||||
local_epoch_minute < *rule.fold_start_local_min);
|
||||
} else if (rule.gap_end_local_min.has_value()) {
|
||||
in_dst = (local_epoch_minute >= *rule.gap_end_local_min);
|
||||
}
|
||||
const std::int32_t off =
|
||||
in_dst ? rule.dst_offset_minutes : rule.standard_offset_minutes;
|
||||
const std::int64_t utc_min =
|
||||
local_epoch_minute - static_cast<std::int64_t>(off);
|
||||
return std::vector<ResolvedSlot>{
|
||||
ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}};
|
||||
}
|
||||
|
||||
Result<std::pair<std::int64_t, std::int64_t>>
|
||||
TimezoneRegistry::local_minute_bounds(std::string_view tz,
|
||||
std::int64_t utc_min_lo,
|
||||
std::int64_t utc_min_hi) const
|
||||
{
|
||||
if (auto fixed = parse_fixed_offset_minutes(tz); fixed.has_value()) {
|
||||
return std::pair{utc_min_lo + *fixed, utc_min_hi + *fixed};
|
||||
}
|
||||
auto it = m_dst_zones.find(tz);
|
||||
if (it == m_dst_zones.end()) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::UnsupportedTimezone,
|
||||
"Scheduler: unsupported timezone '" + std::string{tz} + "'"));
|
||||
}
|
||||
const std::int32_t min_off = std::min(it->second.standard_offset_minutes,
|
||||
it->second.dst_offset_minutes);
|
||||
const std::int32_t max_off = std::max(it->second.standard_offset_minutes,
|
||||
it->second.dst_offset_minutes);
|
||||
return std::pair{utc_min_lo + min_off - 120LL,
|
||||
utc_min_hi + max_off + 120LL};
|
||||
}
|
||||
|
||||
// ── CalendarExpression ────────────────────────────────────────────────────
|
||||
|
||||
Result<CalendarExpression>
|
||||
CalendarExpression::parse(std::string_view expression)
|
||||
{
|
||||
std::vector<std::string_view> tokens;
|
||||
std::size_t i = 0;
|
||||
while (i < expression.size()) {
|
||||
while (i < expression.size() &&
|
||||
(expression[i] == ' ' || expression[i] == '\t')) {
|
||||
++i;
|
||||
}
|
||||
if (i >= expression.size()) {
|
||||
break;
|
||||
}
|
||||
const std::size_t start = i;
|
||||
while (i < expression.size() && expression[i] != ' ' &&
|
||||
expression[i] != '\t') {
|
||||
++i;
|
||||
}
|
||||
tokens.push_back(expression.substr(start, i - start));
|
||||
}
|
||||
|
||||
if (tokens.size() != 5U) {
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::InvalidRule,
|
||||
"Scheduler::CalendarExpression requires exactly 5 fields "
|
||||
"(minute hour day month weekday)"));
|
||||
}
|
||||
|
||||
auto min_m = parse_field(tokens[0], 0, 59);
|
||||
if (!min_m.has_value()) return Void::Result::fail(min_m.error());
|
||||
auto hr_m = parse_field(tokens[1], 0, 23);
|
||||
if (!hr_m.has_value()) return Void::Result::fail(hr_m.error());
|
||||
auto day_m = parse_field(tokens[2], 1, 31);
|
||||
if (!day_m.has_value()) return Void::Result::fail(day_m.error());
|
||||
auto mon_m = parse_field(tokens[3], 1, 12);
|
||||
if (!mon_m.has_value()) return Void::Result::fail(mon_m.error());
|
||||
auto wd_m = parse_field(tokens[4], 0, 6, true);
|
||||
if (!wd_m.has_value()) return Void::Result::fail(wd_m.error());
|
||||
|
||||
CalendarExpression expr{};
|
||||
expr.m_minutes = *min_m;
|
||||
expr.m_hours = static_cast<std::uint32_t>(*hr_m);
|
||||
expr.m_days = static_cast<std::uint32_t>(*day_m);
|
||||
expr.m_months = static_cast<std::uint32_t>(*mon_m);
|
||||
expr.m_weekdays = static_cast<std::uint32_t>(*wd_m);
|
||||
return expr;
|
||||
}
|
||||
|
||||
bool CalendarExpression::matches(const CivilMinute& cm) const noexcept
|
||||
{
|
||||
return ((m_minutes & (1ULL << cm.minute)) != 0ULL) &&
|
||||
((m_hours & (1U << cm.hour)) != 0U) &&
|
||||
((m_days & (1U << cm.day)) != 0U) &&
|
||||
((m_months & (1U << cm.month)) != 0U) &&
|
||||
((m_weekdays & (1U << cm.weekday)) != 0U);
|
||||
}
|
||||
|
||||
std::optional<std::int64_t> CalendarExpression::next_matching_minute(
|
||||
std::int64_t from_local_min, std::int64_t max_local_min) const noexcept
|
||||
{
|
||||
if (from_local_min > max_local_min) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::int64_t cur = from_local_min;
|
||||
// Guard iteration count against unsatisfiable combinations (e.g. Feb 31).
|
||||
for (int guard = 0; guard < 100000 && cur <= max_local_min; ++guard) {
|
||||
const CivilMinute cm = epoch_minute_to_civil(cur);
|
||||
if ((m_months & (1U << cm.month)) == 0U) {
|
||||
std::int32_t ny = cm.year;
|
||||
std::uint32_t nm = cm.month + 1U;
|
||||
if (nm > 12U) {
|
||||
nm = 1U;
|
||||
++ny;
|
||||
}
|
||||
cur = civil_to_epoch_minute(ny, nm, 1U, 0U, 0U);
|
||||
continue;
|
||||
}
|
||||
if ((m_days & (1U << cm.day)) == 0U ||
|
||||
(m_weekdays & (1U << cm.weekday)) == 0U) {
|
||||
// Jump to 00:00 of next day.
|
||||
const std::int64_t next_day_min =
|
||||
civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) +
|
||||
1440LL;
|
||||
cur = next_day_min;
|
||||
continue;
|
||||
}
|
||||
if ((m_hours & (1U << cm.hour)) == 0U) {
|
||||
const std::int64_t next_hr_min =
|
||||
civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour,
|
||||
0U) +
|
||||
60LL;
|
||||
cur = next_hr_min;
|
||||
continue;
|
||||
}
|
||||
if ((m_minutes & (1ULL << cm.minute)) == 0U) {
|
||||
++cur;
|
||||
continue;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<std::int64_t> CalendarExpression::prev_matching_minute(
|
||||
std::int64_t from_local_min, std::int64_t min_local_min) const noexcept
|
||||
{
|
||||
if (from_local_min < min_local_min) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::int64_t cur = from_local_min;
|
||||
for (int guard = 0; guard < 100000 && cur >= min_local_min; ++guard) {
|
||||
const CivilMinute cm = epoch_minute_to_civil(cur);
|
||||
if ((m_months & (1U << cm.month)) == 0U) {
|
||||
std::int32_t py = cm.year;
|
||||
std::uint32_t pm = cm.month - 1U;
|
||||
if (pm == 0U) {
|
||||
pm = 12U;
|
||||
--py;
|
||||
}
|
||||
cur = civil_to_epoch_minute(py, pm, days_in_month(py, pm), 23U,
|
||||
59U);
|
||||
continue;
|
||||
}
|
||||
if ((m_days & (1U << cm.day)) == 0U ||
|
||||
(m_weekdays & (1U << cm.weekday)) == 0U) {
|
||||
// Jump to 23:59 of previous day.
|
||||
cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, 0U, 0U) -
|
||||
1LL;
|
||||
continue;
|
||||
}
|
||||
if ((m_hours & (1U << cm.hour)) == 0U) {
|
||||
cur = civil_to_epoch_minute(cm.year, cm.month, cm.day, cm.hour,
|
||||
0U) -
|
||||
1LL;
|
||||
continue;
|
||||
}
|
||||
if ((m_minutes & (1ULL << cm.minute)) == 0U) {
|
||||
--cur;
|
||||
continue;
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Result<MaterializedSlots> CalendarExpression::materialize_range(
|
||||
const CalendarSpec& spec, const TimezoneRegistry& tz_registry,
|
||||
std::int64_t after_utc_ms, std::int64_t up_to_utc_ms,
|
||||
MisfirePolicy misfire, std::size_t max_catch_up) const
|
||||
{
|
||||
if (auto tz_ok = tz_registry.validate_timezone(spec.timezone);
|
||||
!tz_ok.has_value()) {
|
||||
return Void::Result::fail(tz_ok.error());
|
||||
}
|
||||
|
||||
MaterializedSlots out{};
|
||||
out.next_cursor_utc_ms = after_utc_ms;
|
||||
if (up_to_utc_ms <= after_utc_ms) {
|
||||
return out;
|
||||
}
|
||||
|
||||
const std::int64_t utc_min_lo = after_utc_ms / 60000LL - 1LL;
|
||||
const std::int64_t utc_min_hi = up_to_utc_ms / 60000LL + 1LL;
|
||||
auto bounds =
|
||||
tz_registry.local_minute_bounds(spec.timezone, utc_min_lo, utc_min_hi);
|
||||
if (!bounds.has_value()) {
|
||||
return Void::Result::fail(bounds.error());
|
||||
}
|
||||
const auto [local_lo, local_hi] = *bounds;
|
||||
|
||||
if (misfire == MisfirePolicy::Skip) {
|
||||
out.next_cursor_utc_ms = up_to_utc_ms;
|
||||
return out;
|
||||
}
|
||||
|
||||
if (misfire == MisfirePolicy::CoalesceLatest) {
|
||||
// Scan backward from local_hi to coalesce arbitrarily many missed
|
||||
// slots (even millions) in bounded O(1) jumps!
|
||||
std::int64_t probe = local_hi;
|
||||
std::optional<ResolvedSlot> best{};
|
||||
while (probe >= local_lo) {
|
||||
auto found = prev_matching_minute(probe, local_lo);
|
||||
if (!found.has_value()) {
|
||||
break;
|
||||
}
|
||||
auto resolved = tz_registry.resolve_local_minute(
|
||||
spec.timezone, *found, spec.gap_policy, spec.fold_policy);
|
||||
if (!resolved.has_value()) {
|
||||
return Void::Result::fail(resolved.error());
|
||||
}
|
||||
for (const auto& slot : *resolved) {
|
||||
if (slot.utc_ms > after_utc_ms &&
|
||||
slot.utc_ms <= up_to_utc_ms) {
|
||||
if (!best.has_value() ||
|
||||
slot.utc_ms > best->utc_ms ||
|
||||
(slot.utc_ms == best->utc_ms &&
|
||||
slot.fold_index > best->fold_index)) {
|
||||
best = slot;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (best.has_value()) {
|
||||
break;
|
||||
}
|
||||
probe = *found - 1LL;
|
||||
}
|
||||
if (best.has_value()) {
|
||||
out.slots.push_back(*best);
|
||||
}
|
||||
out.next_cursor_utc_ms = up_to_utc_ms;
|
||||
return out;
|
||||
}
|
||||
|
||||
// CatchUpBounded: scan forward up to `max_catch_up` slots, preserving
|
||||
// remaining cursor state when more slots remain!
|
||||
const std::size_t cap = max_catch_up > 0U ? max_catch_up : 1U;
|
||||
std::int64_t probe = local_lo;
|
||||
while (probe <= local_hi) {
|
||||
auto found = next_matching_minute(probe, local_hi);
|
||||
if (!found.has_value()) {
|
||||
break;
|
||||
}
|
||||
auto resolved = tz_registry.resolve_local_minute(
|
||||
spec.timezone, *found, spec.gap_policy, spec.fold_policy);
|
||||
if (!resolved.has_value()) {
|
||||
return Void::Result::fail(resolved.error());
|
||||
}
|
||||
for (const auto& slot : *resolved) {
|
||||
if (slot.utc_ms > after_utc_ms && slot.utc_ms <= up_to_utc_ms) {
|
||||
if (out.slots.size() < cap) {
|
||||
out.slots.push_back(slot);
|
||||
out.next_cursor_utc_ms =
|
||||
std::max(out.next_cursor_utc_ms, slot.utc_ms);
|
||||
} else {
|
||||
out.more_pending = true;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
probe = *found + 1LL;
|
||||
}
|
||||
|
||||
out.next_cursor_utc_ms = up_to_utc_ms;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Scheduler
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(Scheduler
|
||||
INTERNAL_DEPS Core Functional Time Async
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(SchedulerStorage
|
||||
INTERNAL_DEPS Scheduler Storage
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidDiscoveryOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void REQUIRED CONFIG COMPONENTS Discovery)
|
||||
|
||||
add_executable(discovery_only main.cpp)
|
||||
target_link_libraries(discovery_only PRIVATE Void::Discovery)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME discovery_only COMMAND discovery_only)
|
||||
@@ -0,0 +1,24 @@
|
||||
#include <Void/Discovery/Catalog.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Discovery::Catalog catalog{};
|
||||
Void::Discovery::EndpointRecord rec{};
|
||||
rec.service = "svc";
|
||||
rec.instance = "i-1";
|
||||
rec.endpoint.scheme = "http";
|
||||
rec.endpoint.host = "127.0.0.1";
|
||||
rec.endpoint.port = 8080;
|
||||
|
||||
auto rev = catalog.replace_static({rec});
|
||||
if (!rev.has_value() || *rev != 1U) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
auto snap = catalog.resolve("svc");
|
||||
if (!snap.has_value() || snap->records.size() != 1U) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -318,6 +318,21 @@ if(_has_rpc)
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
has_modules(_has_discovery Discovery Core Functional Time Async)
|
||||
if(_has_discovery)
|
||||
run_consumer(DiscoveryOnly "${install_prefix}" "DiscoveryOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_scheduler Scheduler Core Functional Time Async)
|
||||
if(_has_scheduler)
|
||||
run_consumer(SchedulerOnly "${install_prefix}" "SchedulerOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_messaging Messaging Core Functional Binary Time Async)
|
||||
if(_has_messaging)
|
||||
run_consumer(MessagingOnly "${install_prefix}" "MessagingOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidMessagingOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void REQUIRED CONFIG COMPONENTS Messaging)
|
||||
|
||||
add_executable(messaging_only main.cpp)
|
||||
target_link_libraries(messaging_only PRIVATE Void::Messaging)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME messaging_only COMMAND messaging_only)
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue q{};
|
||||
if (!q.create_queue(Void::Messaging::QueueConfig{.name = "q"}).has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!q.create_group("q", Void::Messaging::GroupConfig{.name = "g"})
|
||||
.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
Void::Messaging::Message m{};
|
||||
m.id = "m1";
|
||||
m.payload = {std::byte{0x41}};
|
||||
auto pub = q.publish("q", m, Void::Messaging::PublishDurability::Memory);
|
||||
if (!pub.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
auto del = q.try_receive("q", "g");
|
||||
if (!del.has_value() || !del->has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!q.ack((*del)->receipt).has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!q.close_and_join().has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidSchedulerOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void REQUIRED CONFIG COMPONENTS Scheduler)
|
||||
|
||||
add_executable(scheduler_only main.cpp)
|
||||
target_link_libraries(scheduler_only PRIVATE Void::Scheduler)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME scheduler_only COMMAND scheduler_only)
|
||||
@@ -0,0 +1,41 @@
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Time::ManualClock mono{};
|
||||
auto sched = Void::Scheduler::Scheduler::create(
|
||||
Void::Scheduler::SchedulerOptions{.monotonic_clock = &mono});
|
||||
if (!sched.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
int ran = 0;
|
||||
if (!sched->register_handler(
|
||||
"ping",
|
||||
[&](const Void::Scheduler::OccurrenceContext&,
|
||||
std::span<const std::byte>,
|
||||
Void::Async::OperationOptions)
|
||||
-> Void::Scheduler::Result<void> {
|
||||
++ran;
|
||||
return {};
|
||||
})
|
||||
.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
Void::Scheduler::JobSpec spec{};
|
||||
spec.id = "j1";
|
||||
spec.handler_id = "ping";
|
||||
spec.schedule = Void::Scheduler::Schedule::one_shot_monotonic(mono.now());
|
||||
if (!sched->add_job(spec).has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
auto count = sched->tick();
|
||||
if (!count.has_value() || *count != 1U || ran != 1) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!sched->close_and_join().has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Discovery/Catalog.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::Discovery::EndpointRecord make_record(std::string svc,
|
||||
std::string inst,
|
||||
std::string host = "127.0.0.1",
|
||||
std::uint16_t port = 8080,
|
||||
std::uint32_t weight = 1)
|
||||
{
|
||||
Void::Discovery::EndpointRecord r{};
|
||||
r.service = std::move(svc);
|
||||
r.instance = std::move(inst);
|
||||
r.endpoint.scheme = "http";
|
||||
r.endpoint.host = std::move(host);
|
||||
r.endpoint.port = port;
|
||||
r.weight = weight;
|
||||
r.ready = true;
|
||||
return r;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test discovery_atomic_static_replacement_and_validation()
|
||||
{
|
||||
using namespace Void::Discovery;
|
||||
|
||||
Catalog catalog{};
|
||||
|
||||
auto good = catalog.replace_static({
|
||||
make_record("orders", "inst-b", "10.0.0.2", 8080, 2),
|
||||
make_record("orders", "inst-a", "10.0.0.1", 8080, 1),
|
||||
});
|
||||
Void::Testing::require(good.has_value());
|
||||
Void::Testing::expect_eq(*good, 1ULL);
|
||||
|
||||
auto snap = catalog.resolve("orders");
|
||||
Void::Testing::require(snap.has_value());
|
||||
Void::Testing::expect_eq(snap->revision, 1ULL);
|
||||
Void::Testing::expect_eq(snap->provider_generation, 1ULL);
|
||||
Void::Testing::require(snap->records.size() == 2U);
|
||||
// Deterministic sorted order by instance identity.
|
||||
Void::Testing::expect_eq(snap->records[0].instance, std::string{"inst-a"});
|
||||
Void::Testing::expect_eq(snap->records[1].instance, std::string{"inst-b"});
|
||||
|
||||
// Duplicate service+instance in candidate must reject atomically and keep
|
||||
// active revision unchanged.
|
||||
auto dup = catalog.replace_static({
|
||||
make_record("orders", "inst-x", "10.0.0.9", 8080),
|
||||
make_record("orders", "inst-x", "10.0.0.10", 8080),
|
||||
});
|
||||
Void::Testing::expect(!dup.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
dup.error().code().value,
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::Conflict));
|
||||
Void::Testing::expect_eq(catalog.revision(), 1ULL);
|
||||
|
||||
// Invalid metadata / zero port rejected atomically.
|
||||
auto bad_port = make_record("orders", "inst-c", "10.0.0.3", 0);
|
||||
auto bad_res = catalog.replace_static({bad_port});
|
||||
Void::Testing::expect(!bad_res.has_value());
|
||||
Void::Testing::expect_eq(catalog.revision(), 1ULL);
|
||||
|
||||
auto bad_meta = make_record("orders", "inst-c", "10.0.0.3", 8080);
|
||||
bad_meta.attributes["k"] = std::string(5000, 'x');
|
||||
auto bad_meta_res = catalog.replace_static({bad_meta});
|
||||
Void::Testing::expect(!bad_meta_res.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
bad_meta_res.error().code().value,
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::LimitExceeded));
|
||||
Void::Testing::expect_eq(catalog.revision(), 1ULL);
|
||||
|
||||
// Active snapshot completely preserved.
|
||||
auto after = catalog.resolve("orders");
|
||||
Void::Testing::require(after.has_value());
|
||||
Void::Testing::expect_eq(after->records.size(), 2ULL);
|
||||
Void::Testing::expect_eq(after->records[0].instance, std::string{"inst-a"});
|
||||
}
|
||||
|
||||
Void::Testing::Test discovery_local_registration_leases_conflict_and_expiry()
|
||||
{
|
||||
using namespace Void::Discovery;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::Time::ManualClock clock{};
|
||||
Catalog catalog{CatalogOptions{.clock = &clock}};
|
||||
|
||||
// Zero TTL is invalid, never an undocumented permanent registration.
|
||||
auto zero_ttl = catalog.register_local(
|
||||
make_record("auth", "node-1"), LeasePolicy::with_ttl(0ms));
|
||||
Void::Testing::expect(!zero_ttl.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
zero_ttl.error().code().value,
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::InvalidArgument));
|
||||
|
||||
auto reg1 = catalog.register_local(
|
||||
make_record("auth", "node-1", "10.0.1.1", 9000),
|
||||
LeasePolicy::with_ttl(30s, 10s));
|
||||
Void::Testing::require(reg1.has_value());
|
||||
Void::Testing::expect(reg1->active());
|
||||
|
||||
// Duplicate registration conflicts without stealing the first handle.
|
||||
auto dup = catalog.register_local(
|
||||
make_record("auth", "node-1", "10.0.1.2", 9001),
|
||||
LeasePolicy::unleased());
|
||||
Void::Testing::expect(!dup.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
dup.error().code().value,
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::Conflict));
|
||||
|
||||
ManagedLeaseRenewer renewer{*reg1, 10s, &clock};
|
||||
Void::Testing::expect(!renewer.due());
|
||||
Void::Testing::require(clock.advance(10s).has_value());
|
||||
Void::Testing::expect(renewer.due());
|
||||
auto ticked = renewer.tick();
|
||||
Void::Testing::require(ticked.has_value());
|
||||
Void::Testing::expect(*ticked);
|
||||
|
||||
// Advance past renewed 30s TTL. Resolve must logically filter expired
|
||||
// record even before reap_expired() runs.
|
||||
Void::Testing::require(clock.advance(30s).has_value());
|
||||
auto snap_expired = catalog.resolve("auth");
|
||||
Void::Testing::require(snap_expired.has_value());
|
||||
Void::Testing::expect(snap_expired->records.empty());
|
||||
|
||||
// Renewal after expiry fails with Expired.
|
||||
auto late_renew = reg1->renew();
|
||||
Void::Testing::expect(!late_renew.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
late_renew.error().code().value,
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::Expired));
|
||||
|
||||
Void::Testing::expect_eq(catalog.reap_expired(), 1ULL);
|
||||
|
||||
// Unleased registration stays alive indefinitely until RAII release.
|
||||
{
|
||||
auto unleased = catalog.register_local(
|
||||
make_record("auth", "node-perm", "10.0.1.9", 9009),
|
||||
LeasePolicy::unleased());
|
||||
Void::Testing::require(unleased.has_value());
|
||||
Void::Testing::require(clock.advance(std::chrono::hours{24}).has_value());
|
||||
auto s = catalog.resolve("auth");
|
||||
Void::Testing::require(s.has_value());
|
||||
Void::Testing::require(s->records.size() == 1U);
|
||||
Void::Testing::expect_eq(s->records[0].instance,
|
||||
std::string{"node-perm"});
|
||||
}
|
||||
auto after_release = catalog.resolve("auth");
|
||||
Void::Testing::require(after_release.has_value());
|
||||
Void::Testing::expect(after_release->records.empty());
|
||||
}
|
||||
|
||||
Void::Testing::Test discovery_watch_overflow_resync_self_cancel_and_self_join()
|
||||
{
|
||||
using namespace Void::Discovery;
|
||||
|
||||
CatalogLimits limits{};
|
||||
limits.max_events_per_watch = 2;
|
||||
Catalog catalog{CatalogOptions{.limits = limits}};
|
||||
|
||||
std::vector<WatchEvent> events;
|
||||
auto wh = catalog.watch(
|
||||
"billing", 0,
|
||||
[&](WatchEvent ev) { events.push_back(std::move(ev)); },
|
||||
WatchOptions{.dispatch_mode = WatchDispatchMode::Manual});
|
||||
Void::Testing::require(wh.has_value());
|
||||
// Initial snapshot queued (1 event).
|
||||
Void::Testing::expect_eq(wh->pending_events(), 1ULL);
|
||||
|
||||
// Push 3 rapid updates without delivering -> queue cap 2 overflows and
|
||||
// coalesces into an explicit ResyncRequired event carrying latest snapshot.
|
||||
auto r1 = catalog.register_local(make_record("billing", "b-1"));
|
||||
auto r2 = catalog.register_local(make_record("billing", "b-2"));
|
||||
auto r3 = catalog.register_local(make_record("billing", "b-3"));
|
||||
Void::Testing::require(r1.has_value());
|
||||
Void::Testing::require(r2.has_value());
|
||||
Void::Testing::require(r3.has_value());
|
||||
|
||||
Void::Testing::expect_eq(wh->pending_events(), 1ULL);
|
||||
Void::Testing::expect_eq(wh->deliver_all(), 1ULL);
|
||||
Void::Testing::require(events.size() == 1U);
|
||||
Void::Testing::expect(events[0].kind == WatchEventKind::ResyncRequired);
|
||||
Void::Testing::require(events[0].snapshot.has_value());
|
||||
Void::Testing::expect_eq(events[0].snapshot->records.size(), 3ULL);
|
||||
|
||||
// Provider generation reset emits explicit ResyncRequired.
|
||||
auto reset = catalog.replace_static(
|
||||
{make_record("billing", "b-static")}, true);
|
||||
Void::Testing::require(reset.has_value());
|
||||
Void::Testing::expect_eq(catalog.provider_generation(), 2ULL);
|
||||
Void::Testing::expect_eq(wh->deliver_all(), 1ULL);
|
||||
Void::Testing::require(events.size() == 2U);
|
||||
Void::Testing::expect(events[1].kind == WatchEventKind::ResyncRequired);
|
||||
Void::Testing::expect_eq(events[1].provider_generation, 2ULL);
|
||||
|
||||
// Self-cancel and self-join diagnosis inside a callback (on Executor mode).
|
||||
Void::Async::ManualExecutor exec{};
|
||||
WatchHandle* self_ptr = nullptr;
|
||||
bool self_join_diagnosed = false;
|
||||
auto self_watch = catalog.watch(
|
||||
"billing", 0,
|
||||
[&](WatchEvent) {
|
||||
if (self_ptr != nullptr) {
|
||||
auto jr = self_ptr->join();
|
||||
self_join_diagnosed =
|
||||
!jr.has_value() &&
|
||||
jr.error().code().value ==
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::SelfJoin);
|
||||
self_ptr->cancel();
|
||||
}
|
||||
},
|
||||
WatchOptions{
|
||||
.dispatch_mode = WatchDispatchMode::Executor,
|
||||
.executor = &exec,
|
||||
});
|
||||
Void::Testing::require(self_watch.has_value());
|
||||
self_ptr = &(*self_watch);
|
||||
Void::Testing::expect(exec.drain() >= 1U);
|
||||
Void::Testing::expect(self_join_diagnosed);
|
||||
Void::Testing::expect(!self_watch->active());
|
||||
Void::Testing::expect(self_watch->join().has_value());
|
||||
|
||||
Void::Testing::expect(catalog.shutdown_and_join().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test discovery_freshness_policy_and_selectors()
|
||||
{
|
||||
using namespace Void::Discovery;
|
||||
|
||||
Catalog catalog{};
|
||||
auto pub = catalog.replace_static({
|
||||
make_record("search", "s-1", "10.0.2.1", 8080, 3),
|
||||
make_record("search", "s-2", "10.0.2.2", 8080, 1),
|
||||
});
|
||||
Void::Testing::require(pub.has_value());
|
||||
|
||||
catalog.set_provider_health(
|
||||
Freshness::Stale,
|
||||
make_discovery_error(DiscoveryErrorCode::Stale, "quorum lost"));
|
||||
auto strict = catalog.resolve("search", ResolvePolicy{.allow_stale = false});
|
||||
Void::Testing::expect(!strict.has_value());
|
||||
auto stale_ok =
|
||||
catalog.resolve("search", ResolvePolicy{.allow_stale = true});
|
||||
Void::Testing::require(stale_ok.has_value());
|
||||
Void::Testing::expect(stale_ok->freshness == Freshness::Stale);
|
||||
Void::Testing::expect(stale_ok->provider_error.has_value());
|
||||
|
||||
// Weighted round-robin delivers 3:1 ratio deterministically.
|
||||
WeightedRoundRobinSelector rr{};
|
||||
std::size_t s1_count = 0;
|
||||
std::size_t s2_count = 0;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
auto picked = rr.select(*stale_ok);
|
||||
Void::Testing::require(picked.has_value());
|
||||
if (picked->instance == "s-1") {
|
||||
++s1_count;
|
||||
} else {
|
||||
++s2_count;
|
||||
}
|
||||
}
|
||||
Void::Testing::expect_eq(s1_count, 6ULL);
|
||||
Void::Testing::expect_eq(s2_count, 2ULL);
|
||||
|
||||
// Affinity selector is deterministic across repeated queries.
|
||||
auto a1 = AffinitySelector::select(*stale_ok, "tenant-42");
|
||||
auto a2 = AffinitySelector::select(*stale_ok, "tenant-42");
|
||||
Void::Testing::require(a1.has_value());
|
||||
Void::Testing::require(a2.has_value());
|
||||
Void::Testing::expect_eq(a1->instance, a2->instance);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#include <Void/DiscoveryRpc/EndpointAdapter.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
Void::Testing::Test discovery_rpc_identity_preserving_refresh_and_roundtrip()
|
||||
{
|
||||
using namespace Void::Discovery;
|
||||
using namespace Void::DiscoveryRpc;
|
||||
|
||||
Void::RPC::Server server{};
|
||||
static constexpr Void::RPC::MethodId kEchoMethod{100U, 1U};
|
||||
auto reg = server.bind(
|
||||
Void::RPC::MethodDescriptor{
|
||||
.id = kEchoMethod,
|
||||
.service_name = "echo",
|
||||
.method_name = "ping",
|
||||
.schema_version = 1,
|
||||
},
|
||||
[](const Void::RPC::CallContext& ctx, Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
std::string auth_seen;
|
||||
for (const auto& m : ctx.metadata) {
|
||||
if (m.key == "void-expected-authority") {
|
||||
auth_seen = m.value;
|
||||
}
|
||||
}
|
||||
Void::RPC::OwnedBytes out = std::move(req);
|
||||
for (char c : auth_seen) {
|
||||
out.push_back(static_cast<std::byte>(c));
|
||||
}
|
||||
return out;
|
||||
});
|
||||
Void::Testing::require(reg.has_value());
|
||||
Void::Testing::require(server.start().has_value());
|
||||
|
||||
Catalog catalog{};
|
||||
EndpointRecord rec{};
|
||||
rec.service = "echo";
|
||||
rec.instance = "echo-1";
|
||||
rec.endpoint.scheme = "http";
|
||||
rec.endpoint.host = "127.0.0.1";
|
||||
rec.endpoint.port = server.bound_port();
|
||||
rec.endpoint.expected_tls_name = "echo.internal";
|
||||
rec.weight = 1;
|
||||
Void::Testing::require(catalog.replace_static({rec}).has_value());
|
||||
|
||||
EndpointResolverClient client{
|
||||
catalog,
|
||||
EndpointResolverOptions{
|
||||
.service = "echo",
|
||||
.expected_tls_name = "echo.internal",
|
||||
.require_tls = false,
|
||||
},
|
||||
};
|
||||
|
||||
Void::RPC::OwnedBytes payload{std::byte{'o'}, std::byte{'k'},
|
||||
std::byte{':'}};
|
||||
auto resp = client.call(kEchoMethod, std::move(payload));
|
||||
Void::Testing::require(resp.has_value());
|
||||
const std::string reply{
|
||||
reinterpret_cast<const char*>(resp->data()), resp->size()};
|
||||
Void::Testing::expect_eq(reply, std::string{"ok:echo.internal"});
|
||||
|
||||
// TLS enforcement rejects non-HTTPS downgrade and mismatched identity.
|
||||
EndpointResolverClient tls_client{
|
||||
catalog,
|
||||
EndpointResolverOptions{
|
||||
.service = "echo",
|
||||
.expected_tls_name = "echo.internal",
|
||||
.require_tls = true,
|
||||
},
|
||||
};
|
||||
auto downgrade = tls_client.select_endpoint();
|
||||
Void::Testing::expect(!downgrade.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
downgrade.error().code().value,
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::TlsIdentityMismatch));
|
||||
|
||||
// Identity mismatch on HTTPS refresh also fails closed.
|
||||
rec.endpoint.scheme = "https";
|
||||
rec.endpoint.expected_tls_name = "spoofed.evil";
|
||||
Void::Testing::require(catalog.replace_static({rec}).has_value());
|
||||
auto mismatch = tls_client.select_endpoint();
|
||||
Void::Testing::expect(!mismatch.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
mismatch.error().code().value,
|
||||
static_cast<std::int32_t>(DiscoveryErrorCode::TlsIdentityMismatch));
|
||||
|
||||
server.shutdown();
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::Messaging::Message make_msg(std::string id, std::string body)
|
||||
{
|
||||
Void::Messaging::Message m{};
|
||||
m.id = std::move(id);
|
||||
m.payload.reserve(body.size());
|
||||
for (char c : body) {
|
||||
m.payload.push_back(static_cast<std::byte>(c));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test messaging_ephemeral_durability_visibility_fencing_and_dlq()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
InMemoryQueue q{InMemoryQueueOptions{
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = []() -> std::uint64_t { return 0ULL; }, // zero retry delay
|
||||
}};
|
||||
|
||||
QueueConfig qcfg{};
|
||||
qcfg.name = "jobs";
|
||||
qcfg.retry.max_attempts = 2;
|
||||
qcfg.retry.base_delay = 1s;
|
||||
qcfg.retry.max_delay = 5s;
|
||||
Void::Testing::require(q.create_queue(qcfg).has_value());
|
||||
Void::Testing::require(
|
||||
q.create_group("jobs", GroupConfig{
|
||||
.name = "workers",
|
||||
.mode = ConsumerMode::Competing,
|
||||
.visibility_timeout = 30s,
|
||||
})
|
||||
.has_value());
|
||||
|
||||
// Explicitly nondurable queue MUST reject PublishDurability::Durable!
|
||||
auto bad_dur =
|
||||
q.publish("jobs", make_msg("m1", "hello"), PublishDurability::Durable);
|
||||
Void::Testing::expect(!bad_dur.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
bad_dur.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::UnsupportedDurability));
|
||||
|
||||
auto pub =
|
||||
q.publish("jobs", make_msg("m1", "hello"), PublishDurability::Memory);
|
||||
Void::Testing::require(pub.has_value());
|
||||
Void::Testing::expect(pub->durability == PublishDurability::Memory);
|
||||
Void::Testing::expect(!pub->deduplicated);
|
||||
|
||||
// Idempotent duplicate publish within 24h returns same sequence.
|
||||
auto dup =
|
||||
q.publish("jobs", make_msg("m1", "hello"), PublishDurability::Memory);
|
||||
Void::Testing::require(dup.has_value());
|
||||
Void::Testing::expect(dup->deduplicated);
|
||||
Void::Testing::expect_eq(dup->sequence, pub->sequence);
|
||||
|
||||
// Receive generation 1, then advance past 30s visibility timeout.
|
||||
auto d1 = q.try_receive("jobs", "workers");
|
||||
Void::Testing::require(d1.has_value() && d1->has_value());
|
||||
Void::Testing::expect_eq((*d1)->receipt.generation, 1ULL);
|
||||
Void::Testing::expect_eq((*d1)->attempt, 1U);
|
||||
|
||||
// Extend visibility works within 5m limit, rejects >5m.
|
||||
Void::Testing::expect(
|
||||
!q.extend_visibility((*d1)->receipt, std::chrono::minutes{6})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
q.extend_visibility((*d1)->receipt, 20s).has_value());
|
||||
|
||||
// Advance past extended 20s visibility -> redelivery generation 2!
|
||||
Void::Testing::require(mono.advance(25s).has_value());
|
||||
auto d2 = q.try_receive("jobs", "workers");
|
||||
Void::Testing::require(d2.has_value() && d2->has_value());
|
||||
Void::Testing::expect_eq((*d2)->receipt.generation, 2ULL);
|
||||
Void::Testing::expect_eq((*d2)->attempt, 2U);
|
||||
|
||||
// Stale receipt from generation 1 MUST fail with StaleReceipt!
|
||||
auto stale_ack = q.ack((*d1)->receipt);
|
||||
Void::Testing::expect(!stale_ack.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
stale_ack.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::StaleReceipt));
|
||||
|
||||
// Exhausting attempt 2 via nack moves atomically to DLQ.
|
||||
Void::Testing::require(q.nack((*d2)->receipt).has_value());
|
||||
auto dlq = q.list_dead_letters("jobs", "workers");
|
||||
Void::Testing::require(dlq.has_value());
|
||||
Void::Testing::require(dlq->size() == 1U);
|
||||
Void::Testing::expect_eq(dlq->front().message.id, std::string{"m1"});
|
||||
Void::Testing::expect_eq(dlq->front().attempts, 2U);
|
||||
|
||||
// Test idempotent repeat ack + SingleActive head-of-line blocking!
|
||||
Void::Testing::require(
|
||||
q.create_group("jobs", GroupConfig{
|
||||
.name = "ordered",
|
||||
.mode = ConsumerMode::SingleActive,
|
||||
.visibility_timeout = 30s,
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
q.publish("jobs", make_msg("m2", "a"), PublishDurability::Memory)
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
q.publish("jobs", make_msg("m3", "b"), PublishDurability::Memory)
|
||||
.has_value());
|
||||
|
||||
auto s1 = q.try_receive("jobs", "ordered");
|
||||
Void::Testing::require(s1.has_value() && s1->has_value());
|
||||
Void::Testing::expect_eq((*s1)->message.id, std::string{"m1"});
|
||||
// While head is InFlight, SingleActive blocks delivery of m2!
|
||||
auto s_blocked = q.try_receive("jobs", "ordered");
|
||||
Void::Testing::require(s_blocked.has_value());
|
||||
Void::Testing::expect(!s_blocked->has_value());
|
||||
|
||||
// Ack and repeat ack of same receipt -> idempotent OK!
|
||||
Void::Testing::require(q.ack((*s1)->receipt).has_value());
|
||||
Void::Testing::require(q.ack((*s1)->receipt).has_value());
|
||||
auto st = q.query_receipt((*s1)->receipt);
|
||||
Void::Testing::require(st.has_value());
|
||||
Void::Testing::expect(*st == DeliveryState::Acked);
|
||||
|
||||
// Next delivery is strictly m2.
|
||||
auto s2 = q.try_receive("jobs", "ordered");
|
||||
Void::Testing::require(s2.has_value() && s2->has_value());
|
||||
Void::Testing::expect_eq((*s2)->message.id, std::string{"m2"});
|
||||
Void::Testing::require(q.ack((*s2)->receipt).has_value());
|
||||
|
||||
auto report = q.close_and_join();
|
||||
Void::Testing::require(report.has_value());
|
||||
Void::Testing::expect(report->complete);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/MessagingRpc/RpcAdapter.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
Void::Testing::Test messaging_rpc_remote_publish_receive_ack_and_query()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace Void::MessagingRpc;
|
||||
|
||||
InMemoryQueue queue{};
|
||||
Void::Testing::require(
|
||||
queue.create_queue(QueueConfig{.name = "remote-q"}).has_value());
|
||||
Void::Testing::require(
|
||||
queue.create_group("remote-q", GroupConfig{.name = "g1"}).has_value());
|
||||
|
||||
Void::RPC::Server rpc_server{};
|
||||
RpcQueueServer adapter{};
|
||||
Void::Testing::require(adapter.mount(rpc_server, queue).has_value());
|
||||
Void::Testing::require(rpc_server.start().has_value());
|
||||
|
||||
RpcQueueClient client{Void::RPC::ClientOptions{
|
||||
.endpoint_base_url = rpc_server.base_url(),
|
||||
}};
|
||||
|
||||
Message msg{};
|
||||
msg.id = "rpc-msg-1";
|
||||
msg.payload = {std::byte{'h'}, std::byte{'i'}};
|
||||
msg.headers["trace"] = "abc";
|
||||
|
||||
auto pub = client.publish("remote-q", msg, PublishDurability::Memory);
|
||||
Void::Testing::require(pub.has_value());
|
||||
Void::Testing::expect_eq(pub->sequence, 1ULL);
|
||||
|
||||
auto del = client.try_receive("remote-q", "g1");
|
||||
Void::Testing::require(del.has_value() && del->has_value());
|
||||
Void::Testing::expect_eq((*del)->message.id, std::string{"rpc-msg-1"});
|
||||
Void::Testing::expect_eq((*del)->message.headers.at("trace"),
|
||||
std::string{"abc"});
|
||||
|
||||
auto st_inflight = client.query_receipt((*del)->receipt);
|
||||
Void::Testing::require(st_inflight.has_value());
|
||||
Void::Testing::expect(*st_inflight == DeliveryState::InFlight);
|
||||
|
||||
Void::Testing::require(client.ack((*del)->receipt).has_value());
|
||||
|
||||
auto st_acked = client.query_receipt((*del)->receipt);
|
||||
Void::Testing::require(st_acked.has_value());
|
||||
Void::Testing::expect(*st_acked == DeliveryState::Acked);
|
||||
|
||||
adapter.unmount_and_drain();
|
||||
rpc_server.shutdown();
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
#include <Void/MessagingStorage/OutboxInbox.hpp>
|
||||
#include <Void/MessagingStorage/StorageQueue.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::Messaging::Message make_msg(std::string id, std::string body)
|
||||
{
|
||||
Void::Messaging::Message m{};
|
||||
m.id = std::move(id);
|
||||
m.payload.reserve(body.size());
|
||||
for (char c : body) {
|
||||
m.payload.push_back(static_cast<std::byte>(c));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test messaging_storage_restart_fencing_poison_dlq_and_caps()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace Void::MessagingStorage;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_msg_store_"};
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
Receipt pre_crash_receipt{};
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto sq = StorageQueue::open(*eng, StorageQueueOptions{
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = []() { return 0ULL; },
|
||||
});
|
||||
Void::Testing::require(sq.has_value());
|
||||
|
||||
QueueConfig qcfg{};
|
||||
qcfg.name = "events";
|
||||
qcfg.retry.max_attempts = 2;
|
||||
Void::Testing::require(sq->create_queue(qcfg).has_value());
|
||||
Void::Testing::require(
|
||||
sq->create_group("events", GroupConfig{.name = "g1"}).has_value());
|
||||
|
||||
auto pub = sq->publish("events", make_msg("poison-1", "bad-data"),
|
||||
PublishDurability::Durable);
|
||||
Void::Testing::require(pub.has_value());
|
||||
Void::Testing::expect(pub->durability == PublishDurability::Durable);
|
||||
|
||||
auto d1 = sq->try_receive("events", "g1");
|
||||
Void::Testing::require(d1.has_value() && d1->has_value());
|
||||
Void::Testing::expect_eq((*d1)->attempt, 1U);
|
||||
pre_crash_receipt = (*d1)->receipt;
|
||||
|
||||
// Crash before ack!
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
|
||||
// Reopen: prior InFlight must be redelivered with bumped generation and
|
||||
// preserved attempt count (1 -> 2)! Old receipt must fail StaleReceipt!
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
QueueLimits lim{};
|
||||
lim.max_dlq_messages = 1;
|
||||
lim.max_idempotency_entries = 2;
|
||||
auto sq = StorageQueue::open(*eng, StorageQueueOptions{
|
||||
.limits = lim,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = []() { return 0ULL; },
|
||||
});
|
||||
Void::Testing::require(sq.has_value());
|
||||
|
||||
// Old worker receipt from before crash is fenced!
|
||||
auto stale = sq->ack(pre_crash_receipt);
|
||||
Void::Testing::expect(!stale.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
stale.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::StaleReceipt));
|
||||
|
||||
auto d2 = sq->try_receive("events", "g1");
|
||||
Void::Testing::require(d2.has_value() && d2->has_value());
|
||||
Void::Testing::expect((*d2)->receipt.generation >
|
||||
pre_crash_receipt.generation);
|
||||
// Attempt counter survived restart!
|
||||
Void::Testing::expect_eq((*d2)->attempt, 2U);
|
||||
|
||||
// Attempt 2 nack exhausts max_attempts=2 -> atomic DLQ move!
|
||||
Void::Testing::require(sq->nack((*d2)->receipt).has_value());
|
||||
auto dlq = sq->list_dead_letters("events", "g1");
|
||||
Void::Testing::require(dlq.has_value());
|
||||
Void::Testing::require(dlq->size() == 1U);
|
||||
Void::Testing::expect_eq(dlq->front().message.id,
|
||||
std::string{"poison-1"});
|
||||
|
||||
// Second poison message hits DLQ cap (max_dlq_messages = 1) -> keeps
|
||||
// message durable and increments stuck_dlq_count without dropping data!
|
||||
Void::Testing::require(
|
||||
sq->publish("events", make_msg("poison-2", "bad2"),
|
||||
PublishDurability::Durable)
|
||||
.has_value());
|
||||
auto p2a = sq->try_receive("events", "g1");
|
||||
Void::Testing::require(p2a.has_value() && p2a->has_value());
|
||||
auto q_full = sq->quarantine_corrupt((*p2a)->receipt, "unknown schema");
|
||||
Void::Testing::expect(!q_full.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
q_full.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::DlqFull));
|
||||
Void::Testing::expect_eq(sq->stuck_dlq_count("events", "g1"), 1ULL);
|
||||
|
||||
// Idempotency table is now at capacity (2/2 live within 24h) -> third
|
||||
// distinct publish MUST fail with IdempotencyCapacityExceeded rather
|
||||
// than silently evicting live contracts!
|
||||
auto idem_cap = sq->publish("events", make_msg("msg-3", "data"),
|
||||
PublishDurability::Durable);
|
||||
Void::Testing::expect(!idem_cap.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
idem_cap.error().code().value,
|
||||
static_cast<std::int32_t>(
|
||||
MessagingErrorCode::IdempotencyCapacityExceeded));
|
||||
|
||||
// Unhealthy civil clock pauses retention expiry even after 30 days!
|
||||
sq->set_clock_healthy(false);
|
||||
Void::Testing::require(
|
||||
civil.advance(std::chrono::hours{24 * 30}).has_value());
|
||||
auto exp_paused = sq->expire_retention();
|
||||
Void::Testing::require(exp_paused.has_value());
|
||||
Void::Testing::expect_eq(*exp_paused, 0ULL);
|
||||
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test messaging_storage_outbox_inbox_single_batch_atomicity()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace Void::MessagingStorage;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_msg_outbox_"};
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto sq = StorageQueue::open(*eng);
|
||||
Void::Testing::require(sq.has_value());
|
||||
Void::Testing::require(
|
||||
sq->create_queue(QueueConfig{.name = "orders"}).has_value());
|
||||
Void::Testing::require(
|
||||
sq->create_group("orders", GroupConfig{.name = "ledger"}).has_value());
|
||||
|
||||
// 1. Atomic business mutation + outbox append in ONE Storage::Batch!
|
||||
{
|
||||
Void::Storage::Batch b{};
|
||||
b.put("biz:order:100", "created");
|
||||
OutboxInbox::append_outbox_in_batch(
|
||||
b, OutboxRecord{
|
||||
.outbox_id = "ob-100",
|
||||
.target_queue = "orders",
|
||||
.message = make_msg("order-100", "amount=42"),
|
||||
});
|
||||
Void::Testing::require(
|
||||
eng->write(std::move(b), Void::Storage::Durability::Sync)
|
||||
.has_value());
|
||||
}
|
||||
|
||||
// 2. Relay outbox into durable queue (idempotent publish).
|
||||
auto relayed = OutboxInbox::relay_outbox(*eng, *sq);
|
||||
Void::Testing::require(relayed.has_value());
|
||||
Void::Testing::expect_eq(*relayed, 1ULL);
|
||||
|
||||
// 3. Consumer receives message and atomically applies local effect + inbox
|
||||
// dedup key in ONE Storage::Batch!
|
||||
auto del = sq->try_receive("orders", "ledger");
|
||||
Void::Testing::require(del.has_value() && del->has_value());
|
||||
|
||||
{
|
||||
Void::Storage::Batch apply_b{};
|
||||
OutboxInbox::apply_inbox_in_batch(apply_b, "ledger-worker",
|
||||
(*del)->message.id);
|
||||
apply_b.put("biz:ledger:100", "credited");
|
||||
Void::Testing::require(
|
||||
eng->write(std::move(apply_b), Void::Storage::Durability::Sync)
|
||||
.has_value());
|
||||
}
|
||||
|
||||
// Simulate duplicate delivery (e.g. crash before ack): second apply of
|
||||
// identical inbox key in local batch fails cleanly with Conflict!
|
||||
{
|
||||
Void::Storage::Batch dup_b{};
|
||||
OutboxInbox::apply_inbox_in_batch(dup_b, "ledger-worker",
|
||||
(*del)->message.id);
|
||||
dup_b.put("biz:ledger:100", "double-credited");
|
||||
auto wr = eng->write(std::move(dup_b), Void::Storage::Durability::Sync);
|
||||
Void::Testing::expect(!wr.has_value());
|
||||
Void::Testing::expect(wr.error().cause.code ==
|
||||
Void::Storage::StorageErrorCode::conflict);
|
||||
}
|
||||
|
||||
Void::Testing::require(sq->ack((*del)->receipt).has_value());
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
#include <Void/Scheduler/Calendar.hpp>
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
Void::Testing::Test scheduler_fake_clock_ordering_retries_and_dead_letter()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
// Deterministic RNG yielding 500ms full-jitter delay (500 % (1000+1) = 500).
|
||||
std::uint64_t rng_val = 500ULL;
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "unit-1",
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = [&]() { return rng_val; },
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
std::vector<std::string> order;
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"record",
|
||||
[&](const OccurrenceContext& ctx, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
order.push_back(ctx.id.job_id);
|
||||
return {};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
int fail_calls = 0;
|
||||
OccurrenceId failed_id{};
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"always_fail",
|
||||
[&](const OccurrenceContext& ctx, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
++fail_calls;
|
||||
failed_id = ctx.id;
|
||||
return Void::Result::fail(make_scheduler_error(
|
||||
SchedulerErrorCode::HandlerFailed, "boom"));
|
||||
})
|
||||
.has_value());
|
||||
|
||||
// Add later job first, earlier job second -> heap must order by due_time.
|
||||
JobSpec late{};
|
||||
late.id = "job-late";
|
||||
late.handler_id = "record";
|
||||
late.schedule = Schedule::one_shot_monotonic(mono.now() + 5s);
|
||||
Void::Testing::require(sched->add_job(late).has_value());
|
||||
|
||||
JobSpec early{};
|
||||
early.id = "job-early";
|
||||
early.handler_id = "record";
|
||||
early.schedule = Schedule::one_shot_monotonic(mono.now() + 2s);
|
||||
Void::Testing::require(sched->add_job(early).has_value());
|
||||
|
||||
// Clock jumps past both -> must run early before late!
|
||||
Void::Testing::require(mono.advance(10s).has_value());
|
||||
auto ran = sched->tick();
|
||||
Void::Testing::require(ran.has_value());
|
||||
Void::Testing::expect_eq(*ran, 2ULL);
|
||||
Void::Testing::require(order.size() == 2U);
|
||||
Void::Testing::expect_eq(order[0], std::string{"job-early"});
|
||||
Void::Testing::expect_eq(order[1], std::string{"job-late"});
|
||||
|
||||
// Retry exhaustion -> Dead status keeping same OccurrenceId!
|
||||
JobSpec flaky{};
|
||||
flaky.id = "job-flaky";
|
||||
flaky.handler_id = "always_fail";
|
||||
flaky.schedule = Schedule::one_shot_monotonic(mono.now());
|
||||
flaky.retry.max_attempts = 3;
|
||||
flaky.retry.base_delay = 1s;
|
||||
flaky.retry.max_delay = 10s;
|
||||
flaky.retry.multiplier = 2;
|
||||
Void::Testing::require(sched->add_job(flaky).has_value());
|
||||
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
auto r = sched->tick();
|
||||
Void::Testing::require(r.has_value());
|
||||
Void::Testing::expect_eq(*r, 1ULL);
|
||||
Void::Testing::require(mono.advance(10s).has_value());
|
||||
}
|
||||
Void::Testing::expect_eq(fail_calls, 3);
|
||||
auto st = sched->stats();
|
||||
Void::Testing::require(st.has_value());
|
||||
Void::Testing::expect_eq(st->dead, 1ULL);
|
||||
|
||||
// Dead records cannot be pruned until explicitly acknowledged.
|
||||
auto prune0 = sched->prune_completed();
|
||||
Void::Testing::require(prune0.has_value());
|
||||
Void::Testing::expect_eq(*prune0, 0ULL);
|
||||
Void::Testing::require(sched->acknowledge_dead(failed_id).has_value());
|
||||
auto prune1 = sched->prune_completed();
|
||||
Void::Testing::require(prune1.has_value());
|
||||
Void::Testing::expect_eq(*prune1, 1ULL);
|
||||
|
||||
auto report = sched->close_and_join();
|
||||
Void::Testing::require(report.has_value());
|
||||
Void::Testing::expect(report->complete);
|
||||
}
|
||||
|
||||
Void::Testing::Test scheduler_calendar_dst_misfire_and_unknown_tz()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
|
||||
TimezoneRegistry tz{};
|
||||
// Reject unknown timezone without silent UTC fallback.
|
||||
auto bad_tz = tz.validate_timezone("Mars/Olympus_Mons");
|
||||
Void::Testing::expect(!bad_tz.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
bad_tz.error().code().value,
|
||||
static_cast<std::int32_t>(SchedulerErrorCode::UnsupportedTimezone));
|
||||
|
||||
// Fixed offset +02:00 works cleanly.
|
||||
Void::Testing::expect(tz.validate_timezone("UTC+02:00").has_value());
|
||||
|
||||
// Register deterministic DST zone:
|
||||
// Gap: 2026-03-08 02:00..03:00 local (spring forward -05:00 -> -04:00)
|
||||
// Fold: 2026-11-01 01:00..02:00 local (fall back -04:00 -> -05:00)
|
||||
DstTransitionRule rule{};
|
||||
rule.name = "Test/DST";
|
||||
rule.standard_offset_minutes = -300;
|
||||
rule.dst_offset_minutes = -240;
|
||||
rule.gap_start_local_min = civil_to_epoch_minute(2026, 3, 8, 2, 0);
|
||||
rule.gap_end_local_min = civil_to_epoch_minute(2026, 3, 8, 3, 0);
|
||||
rule.fold_start_local_min = civil_to_epoch_minute(2026, 11, 1, 1, 0);
|
||||
rule.fold_end_local_min = civil_to_epoch_minute(2026, 11, 1, 2, 0);
|
||||
tz.register_dst_zone(rule);
|
||||
|
||||
// Gap policy Skip omits 02:30 on 2026-03-08.
|
||||
const std::int64_t gap_min = civil_to_epoch_minute(2026, 3, 8, 2, 30);
|
||||
auto skipped = tz.resolve_local_minute("Test/DST", gap_min,
|
||||
DstGapPolicy::Skip,
|
||||
DstFoldPolicy::First);
|
||||
Void::Testing::require(skipped.has_value());
|
||||
Void::Testing::expect(skipped->empty());
|
||||
|
||||
// Fold policy First yields fold_index=0; Twice yields both fold 0 and 1!
|
||||
const std::int64_t fold_min = civil_to_epoch_minute(2026, 11, 1, 1, 30);
|
||||
auto first_only = tz.resolve_local_minute("Test/DST", fold_min,
|
||||
DstGapPolicy::Skip,
|
||||
DstFoldPolicy::First);
|
||||
Void::Testing::require(first_only.has_value());
|
||||
Void::Testing::require(first_only->size() == 1U);
|
||||
Void::Testing::expect_eq(first_only->front().fold_index,
|
||||
static_cast<std::uint8_t>(0));
|
||||
|
||||
auto twice = tz.resolve_local_minute("Test/DST", fold_min,
|
||||
DstGapPolicy::Skip,
|
||||
DstFoldPolicy::Twice);
|
||||
Void::Testing::require(twice.has_value());
|
||||
Void::Testing::require(twice->size() == 2U);
|
||||
Void::Testing::expect_eq((*twice)[0].fold_index,
|
||||
static_cast<std::uint8_t>(0));
|
||||
Void::Testing::expect_eq((*twice)[1].fold_index,
|
||||
static_cast<std::uint8_t>(1));
|
||||
Void::Testing::expect_eq((*twice)[1].utc_ms - (*twice)[0].utc_ms,
|
||||
3600LL * 1000LL);
|
||||
|
||||
// CoalesceLatest over >2,000,000 missed minutes executes immediately in
|
||||
// bounded time and returns the single latest slot!
|
||||
auto every_min = CalendarExpression::parse("* * * * *");
|
||||
Void::Testing::require(every_min.has_value());
|
||||
const std::int64_t t0 =
|
||||
civil_to_epoch_minute(2020, 1, 1, 0, 0) * 60000LL;
|
||||
const std::int64_t t1 =
|
||||
civil_to_epoch_minute(2025, 1, 1, 0, 0) * 60000LL; // ~2.63M minutes!
|
||||
CalendarSpec cspec{.expression = "* * * * *", .timezone = "UTC"};
|
||||
auto coalesced = every_min->materialize_range(
|
||||
cspec, tz, t0, t1, MisfirePolicy::CoalesceLatest, 100);
|
||||
Void::Testing::require(coalesced.has_value());
|
||||
Void::Testing::require(coalesced->slots.size() == 1U);
|
||||
Void::Testing::expect_eq(coalesced->slots[0].utc_ms, t1);
|
||||
|
||||
// CatchUpBounded caps strictly at 100 slots/pass preserving cursor state!
|
||||
auto bounded = every_min->materialize_range(
|
||||
cspec, tz, t0, t1, MisfirePolicy::CatchUpBounded, 100);
|
||||
Void::Testing::require(bounded.has_value());
|
||||
Void::Testing::expect_eq(bounded->slots.size(), 100ULL);
|
||||
Void::Testing::expect(bounded->more_pending);
|
||||
Void::Testing::expect_eq(bounded->next_cursor_utc_ms,
|
||||
t0 + 100LL * 60000LL);
|
||||
}
|
||||
|
||||
Void::Testing::Test scheduler_overlap_revision_edit_and_shutdown_timeout()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "unit-overlap",
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
std::mutex gate_mu;
|
||||
std::condition_variable gate_cv;
|
||||
bool entered = false;
|
||||
bool release = false;
|
||||
std::atomic<int> concurrent_now{0};
|
||||
std::atomic<int> max_concurrent_seen{0};
|
||||
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"slow",
|
||||
[&](const OccurrenceContext&, std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
const int c = ++concurrent_now;
|
||||
int prev = max_concurrent_seen.load();
|
||||
while (c > prev &&
|
||||
!max_concurrent_seen.compare_exchange_weak(prev, c)) {
|
||||
}
|
||||
{
|
||||
std::lock_guard lk{gate_mu};
|
||||
entered = true;
|
||||
}
|
||||
gate_cv.notify_all();
|
||||
{
|
||||
std::unique_lock lk{gate_mu};
|
||||
gate_cv.wait(lk, [&] { return release; });
|
||||
}
|
||||
--concurrent_now;
|
||||
return {};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
JobSpec job{};
|
||||
job.id = "j-forbid";
|
||||
job.handler_id = "slow";
|
||||
job.schedule = Schedule::fixed_rate(1s, mono.now());
|
||||
job.misfire = MisfirePolicy::CatchUpBounded;
|
||||
job.overlap = OverlapPolicy::Forbid;
|
||||
Void::Testing::require(sched->add_job(job).has_value());
|
||||
|
||||
// Advance 3s -> materializes multiple due slots, but Overlap::Forbid must
|
||||
// never allow 2 concurrent executions of the same job.
|
||||
Void::Testing::require(mono.advance(2s).has_value());
|
||||
|
||||
std::thread worker([&] { (void)sched->tick(); });
|
||||
|
||||
{
|
||||
std::unique_lock lk{gate_mu};
|
||||
gate_cv.wait(lk, [&] { return entered; });
|
||||
}
|
||||
|
||||
// Second concurrent dispatch_one must be blocked by Overlap::Forbid!
|
||||
auto blocked = sched->dispatch_one();
|
||||
Void::Testing::require(blocked.has_value());
|
||||
Void::Testing::expect(!*blocked);
|
||||
Void::Testing::expect_eq(max_concurrent_seen.load(), 1);
|
||||
|
||||
// Invalid update_job must fail without mutating active policy.
|
||||
JobSpec bad_update = job;
|
||||
bad_update.schedule = Schedule::calendar_schedule(
|
||||
CalendarSpec{.expression = "bad cron", .timezone = "UTC"});
|
||||
Void::Testing::expect(!sched->update_job(bad_update).has_value());
|
||||
|
||||
// Valid update_job bumps revision to 2 and invalidates unstarted rev-1
|
||||
// pending occurrences!
|
||||
JobSpec good_update = job;
|
||||
good_update.payload = {std::byte{0x42}};
|
||||
auto rev2 = sched->update_job(good_update);
|
||||
Void::Testing::require(rev2.has_value());
|
||||
Void::Testing::expect_eq(*rev2, 2ULL);
|
||||
|
||||
// close_and_join with already-expired deadline returns incomplete report
|
||||
// listing the live occurrence instead of erasing running state!
|
||||
auto inc = sched->close_and_join(
|
||||
Void::Async::OperationOptions{.deadline = mono.now()});
|
||||
Void::Testing::require(inc.has_value());
|
||||
Void::Testing::expect(!inc->complete);
|
||||
Void::Testing::expect_eq(inc->live_occurrences.size(), 1ULL);
|
||||
|
||||
// Unblock active handler and join cleanly.
|
||||
{
|
||||
std::lock_guard lk{gate_mu};
|
||||
release = true;
|
||||
}
|
||||
gate_cv.notify_all();
|
||||
worker.join();
|
||||
|
||||
auto done = sched->close_and_join();
|
||||
Void::Testing::require(done.has_value());
|
||||
Void::Testing::expect(done->complete);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
#include <Void/Scheduler/Scheduler.hpp>
|
||||
#include <Void/SchedulerStorage/StorageJobStore.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
Void::Testing::Test scheduler_storage_durable_recovery_ownership_and_retention()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace Void::SchedulerStorage;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_sched_store_"};
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
OccurrenceId first_id{};
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto store1 = std::make_shared<StorageJobStore>(*eng);
|
||||
auto store2 = std::make_shared<StorageJobStore>(*eng);
|
||||
|
||||
// Exclusive ownership lock rejects second owner!
|
||||
Void::Testing::require(store1->acquire_ownership("owner-A").has_value());
|
||||
auto second = store2->acquire_ownership("owner-B");
|
||||
Void::Testing::expect(!second.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
second.error().code().value,
|
||||
static_cast<std::int32_t>(SchedulerErrorCode::OwnershipLocked));
|
||||
Void::Testing::require(store1->release_ownership().has_value());
|
||||
|
||||
// Manually create a job & claim one occurrence (Pending -> Running),
|
||||
// then close engine WITHOUT completing to simulate a crash!
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "owner-A",
|
||||
.store = store1,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
JobSpec j{};
|
||||
j.id = "durable-job";
|
||||
j.handler_id = "h1";
|
||||
j.schedule = Schedule::one_shot_utc(to_utc_ms(civil.now()));
|
||||
Void::Testing::require(sched->add_job(j).has_value());
|
||||
|
||||
// Materialize without handler registered (stays Pending), then claim
|
||||
// directly through store to leave it durably Running across crash.
|
||||
auto ran = sched->tick();
|
||||
Void::Testing::require(ran.has_value());
|
||||
Void::Testing::expect_eq(*ran, 0ULL);
|
||||
|
||||
auto occs = store1->load_occurrences();
|
||||
Void::Testing::require(occs.has_value());
|
||||
Void::Testing::require(occs->size() == 1U);
|
||||
first_id = occs->front().id;
|
||||
|
||||
auto claimed = store1->claim_occurrence(first_id, 0);
|
||||
Void::Testing::require(claimed.has_value());
|
||||
Void::Testing::expect(claimed->status == OccurrenceStatus::Running);
|
||||
Void::Testing::expect_eq(claimed->attempt, 1U);
|
||||
|
||||
// Simulate crash: do NOT call complete_occurrence or
|
||||
// release_ownership; close engine cleanly for reopen.
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
|
||||
// Reopen after crash: recovery must return Running -> Pending preserving
|
||||
// the exact same OccurrenceId and execute at-least-once!
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto store = std::make_shared<StorageJobStore>(
|
||||
*eng, StorageJobStoreOptions{.recover_stale_owner = true});
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "owner-A-restarted",
|
||||
.store = store,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
OccurrenceId executed_id{};
|
||||
std::uint32_t executed_attempt = 0;
|
||||
Void::Testing::require(
|
||||
sched
|
||||
->register_handler(
|
||||
"h1",
|
||||
[&](const OccurrenceContext& ctx,
|
||||
std::span<const std::byte>,
|
||||
Void::Async::OperationOptions) -> Result<void> {
|
||||
executed_id = ctx.id;
|
||||
executed_attempt = ctx.attempt;
|
||||
return {};
|
||||
})
|
||||
.has_value());
|
||||
|
||||
auto ran = sched->tick();
|
||||
Void::Testing::require(ran.has_value());
|
||||
Void::Testing::expect_eq(*ran, 1ULL);
|
||||
Void::Testing::expect(executed_id == first_id);
|
||||
// Attempt incremented from 1 (pre-crash) -> 2 (post-crash redelivery)!
|
||||
Void::Testing::expect_eq(executed_attempt, 2U);
|
||||
|
||||
Void::Testing::require(sched->close_and_join().has_value());
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test scheduler_storage_retention_cap_pauses_without_cursor_loss()
|
||||
{
|
||||
using namespace Void::Scheduler;
|
||||
using namespace Void::SchedulerStorage;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_sched_ret_"};
|
||||
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
SchedulerLimits limits{};
|
||||
limits.max_retained_occurrences = 2;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
auto store = std::make_shared<StorageJobStore>(
|
||||
*eng, StorageJobStoreOptions{.limits = limits});
|
||||
auto sched = Scheduler::create(SchedulerOptions{
|
||||
.owner_id = "ret-owner",
|
||||
.store = store,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.limits = limits,
|
||||
});
|
||||
Void::Testing::require(sched.has_value());
|
||||
|
||||
JobSpec j{};
|
||||
j.id = "rate-job";
|
||||
j.handler_id = "h";
|
||||
j.schedule = Schedule::fixed_rate(1s, mono.now());
|
||||
j.misfire = MisfirePolicy::CatchUpBounded;
|
||||
Void::Testing::require(sched->add_job(j).has_value());
|
||||
|
||||
// Advance 3s -> 4 due slots exist, but retention cap is 2, so
|
||||
// materialization of all 4 is rejected WITHOUT advancing cursor!
|
||||
Void::Testing::require(mono.advance(3s).has_value());
|
||||
auto r = sched->tick();
|
||||
Void::Testing::require(r.has_value());
|
||||
auto jobs = sched->list_jobs();
|
||||
Void::Testing::require(jobs.has_value());
|
||||
Void::Testing::require(jobs->size() == 1U);
|
||||
Void::Testing::expect(!jobs->front().cursor_initialized);
|
||||
|
||||
Void::Testing::require(sched->close_and_join().has_value());
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
Reference in new issue
Block a user