From 0cf187d664c8d10e3b634bc00e6e091e80fff1da Mon Sep 17 00:00:00 2001 From: faumaray Date: Fri, 27 Nov 2026 05:14:52 +0300 Subject: [PATCH 1/5] docs(wave10): add P3 Discovery, Scheduler, and Messaging specs and error domains --- .../agent-workflow/tasks/S-DISCOVERY-01-04.md | 39 ++++++++++++++++++ .../agent-workflow/tasks/S-MESSAGING-01-04.md | 41 +++++++++++++++++++ .../agent-workflow/tasks/S-SCHEDULER-01-04.md | 40 ++++++++++++++++++ include/Void/Functional/Error.hpp | 2 + 4 files changed, 122 insertions(+) create mode 100644 docs/agent-workflow/tasks/S-DISCOVERY-01-04.md create mode 100644 docs/agent-workflow/tasks/S-MESSAGING-01-04.md create mode 100644 docs/agent-workflow/tasks/S-SCHEDULER-01-04.md diff --git a/docs/agent-workflow/tasks/S-DISCOVERY-01-04.md b/docs/agent-workflow/tasks/S-DISCOVERY-01-04.md new file mode 100644 index 0000000..c4a80b5 --- /dev/null +++ b/docs/agent-workflow/tasks/S-DISCOVERY-01-04.md @@ -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. diff --git a/docs/agent-workflow/tasks/S-MESSAGING-01-04.md b/docs/agent-workflow/tasks/S-MESSAGING-01-04.md new file mode 100644 index 0000000..cb085b1 --- /dev/null +++ b/docs/agent-workflow/tasks/S-MESSAGING-01-04.md @@ -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. diff --git a/docs/agent-workflow/tasks/S-SCHEDULER-01-04.md b/docs/agent-workflow/tasks/S-SCHEDULER-01-04.md new file mode 100644 index 0000000..4c9be19 --- /dev/null +++ b/docs/agent-workflow/tasks/S-SCHEDULER-01-04.md @@ -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. diff --git a/include/Void/Functional/Error.hpp b/include/Void/Functional/Error.hpp index 14fc5ab..b54b475 100644 --- a/include/Void/Functional/Error.hpp +++ b/include/Void/Functional/Error.hpp @@ -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}; From ec8c0bd40ad2f982712c2b06110b5ebe46c48efb Mon Sep 17 00:00:00 2001 From: faumaray Date: Fri, 27 Nov 2026 05:25:43 +0300 Subject: [PATCH 2/5] feat(discovery): implement P3 S-DISCOVERY-01..04 Discovery catalog and optional DiscoveryRpc adapter --- include/Void/Discovery/Catalog.hpp | 216 +++ include/Void/Discovery/Types.hpp | 245 +++ include/Void/DiscoveryRpc/EndpointAdapter.hpp | 73 + src/Discovery/Catalog.cpp | 1588 +++++++++++++++++ src/Discovery/module.cmake | 3 + src/DiscoveryRpc/EndpointAdapter.cpp | 144 ++ src/DiscoveryRpc/module.cmake | 3 + tests/package/DiscoveryOnly/CMakeLists.txt | 14 + tests/package/DiscoveryOnly/main.cpp | 24 + tests/package/InstalledComponents.cmake | 5 + tests/standalone/Discovery/Catalog.cpp | 278 +++ .../DiscoveryRpc/EndpointAdapter.cpp | 93 + 12 files changed, 2686 insertions(+) create mode 100644 include/Void/Discovery/Catalog.hpp create mode 100644 include/Void/Discovery/Types.hpp create mode 100644 include/Void/DiscoveryRpc/EndpointAdapter.hpp create mode 100644 src/Discovery/Catalog.cpp create mode 100644 src/Discovery/module.cmake create mode 100644 src/DiscoveryRpc/EndpointAdapter.cpp create mode 100644 src/DiscoveryRpc/module.cmake create mode 100644 tests/package/DiscoveryOnly/CMakeLists.txt create mode 100644 tests/package/DiscoveryOnly/main.cpp create mode 100644 tests/standalone/Discovery/Catalog.cpp create mode 100644 tests/standalone/DiscoveryRpc/EndpointAdapter.cpp diff --git a/include/Void/Discovery/Catalog.hpp b/include/Void/Discovery/Catalog.hpp new file mode 100644 index 0000000..770e673 --- /dev/null +++ b/include/Void/Discovery/Catalog.hpp @@ -0,0 +1,216 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 + expires_at() const noexcept; + + [[nodiscard]] Result renew(); + void release() noexcept; + + private: + + friend class Catalog; + struct State; + std::shared_ptr 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 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 m_catalog_state{}; + std::shared_ptr 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 + replace_static(std::vector 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 provider_error = + std::nullopt); + + [[nodiscard]] Result + resolve(std::string_view service, + ResolvePolicy policy = {}) const; + + [[nodiscard]] Result + register_local(EndpointRecord record, + LeasePolicy lease = LeasePolicy::unleased()); + + [[nodiscard]] Result + 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 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 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 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 + select(const Snapshot& snapshot); + + void reset() noexcept; + + private: + + mutable std::mutex m_mu{}; + std::map> m_current_weights{}; + }; + + /// Deterministic client-side affinity selector using weighted Rendezvous + /// (HRW) hashing over `Void::Hash::fnv1a64`. + class AffinitySelector final + { + public: + + [[nodiscard]] static Result + select(const Snapshot& snapshot, std::string_view affinity_key); + }; + +} // namespace Void::Discovery diff --git a/include/Void/Discovery/Types.hpp b/include/Void/Discovery/Types.hpp new file mode 100644 index 0000000..8691ccf --- /dev/null +++ b/include/Void/Discovery/Types.hpp @@ -0,0 +1,245 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Discovery +{ + using Void::Result::Error; + template using Result = Void::Result::Result; + + 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(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> attributes{}; + + [[nodiscard]] bool + operator==(const EndpointRecord&) const noexcept = default; + }; + + struct Snapshot { + std::uint64_t provider_generation{1}; + std::uint64_t revision{0}; + std::vector records{}; + Freshness freshness{Freshness::Fresh}; + std::optional 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{}; + std::vector added{}; + std::vector updated{}; + std::vector removed_instances{}; + }; + + using WatchCallback = std::function; + + 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; + + struct CatalogOptions { + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + CatalogLimits limits{}; + ObservationHook observer{}; + }; + + [[nodiscard]] Result + 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 diff --git a/include/Void/DiscoveryRpc/EndpointAdapter.hpp b/include/Void/DiscoveryRpc/EndpointAdapter.hpp new file mode 100644 index 0000000..51ef9b5 --- /dev/null +++ b/include/Void/DiscoveryRpc/EndpointAdapter.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +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 + select_endpoint( + std::optional affinity_key = std::nullopt); + + [[nodiscard]] Void::Result::Result + call(Void::RPC::MethodId method, + Void::RPC::OwnedBytes payload, + Void::RPC::CallOptions options = {}, + std::optional 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 m_outstanding{0}; + }; + +} // namespace Void::DiscoveryRpc diff --git a/src/Discovery/Catalog.cpp b/src/Discovery/Catalog.cpp new file mode 100644 index 0000000..bf099a9 --- /dev/null +++ b/src/Discovery/Catalog.cpp @@ -0,0 +1,1588 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Discovery +{ + namespace + { + [[nodiscard]] bool is_valid_identifier(std::string_view s, + std::size_t max_len = 256) noexcept + { + if (s.empty() || s.size() > max_len) { + return false; + } + for (unsigned char c : s) { + if (c < 0x21U || c > 0x7EU) { + return false; + } + } + return true; + } + + [[nodiscard]] bool is_valid_scheme(std::string_view s) noexcept + { + if (s.empty() || s.size() > 32U) { + return false; + } + const auto first = static_cast(s.front()); + const bool is_alpha = (first >= 'a' && first <= 'z') || + (first >= 'A' && first <= 'Z'); + if (!is_alpha) { + return false; + } + for (unsigned char c : s) { + const bool ok = (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '+' || + c == '-' || c == '.'; + if (!ok) { + return false; + } + } + return true; + } + + [[nodiscard]] bool is_valid_host(std::string_view s) noexcept + { + if (s.empty() || s.size() > 255U) { + return false; + } + for (unsigned char c : s) { + if (c < 0x21U || c > 0x7EU || c == '/' || c == '@' || + c == '?' || c == '#' || c == '\\') { + return false; + } + } + return true; + } + + [[nodiscard]] bool is_valid_printable_ascii(std::string_view s) noexcept + { + for (unsigned char c : s) { + if (c < 0x20U || c > 0x7EU) { + return false; + } + } + return true; + } + + struct StoredRecord { + EndpointRecord record{}; + bool is_static{true}; + std::uint64_t token{0}; + bool leased{false}; + Void::Time::MonotonicClock::time_point expires_at{}; + }; + + [[nodiscard]] bool + is_expired(const StoredRecord& rec, + Void::Time::MonotonicClock::time_point now) noexcept + { + return !rec.is_static && rec.leased && now >= rec.expires_at; + } + + struct WatchNode { + std::uint64_t id{0}; + std::string service{}; + WatchCallback callback{}; + WatchDispatchMode mode{WatchDispatchMode::Inline}; + Void::Async::Executor* executor{nullptr}; + std::size_t max_events{64}; + std::atomic* shared_event_bytes{nullptr}; + std::size_t max_shared_event_bytes{16ULL * 1024 * 1024}; + ObservationHook observer{}; + + mutable std::mutex mu{}; + std::condition_variable cv{}; + std::deque> queue{}; + bool cancelled{false}; + bool running{false}; + bool pump_scheduled{false}; + std::thread::id callback_thread{}; + + void release_all_queued_locked() noexcept + { + std::size_t total = 0; + for (const auto& [ev, bytes] : queue) { + (void)ev; + total += bytes; + } + queue.clear(); + if (shared_event_bytes != nullptr && total > 0) { + shared_event_bytes->fetch_sub( + total, std::memory_order_acq_rel); + } + } + + [[nodiscard]] bool enqueue(WatchEvent event, + const Snapshot& full_snapshot) + { + bool resynced = false; + { + std::lock_guard lk{mu}; + if (cancelled) { + return false; + } + const std::size_t ev_bytes = + estimate_watch_event_bytes(event); + const bool force_resync = + event.kind == WatchEventKind::ResyncRequired; + const bool already_resyncing = + !queue.empty() && + queue.back().first.kind == + WatchEventKind::ResyncRequired; + const bool queue_full = queue.size() >= max_events; + const std::size_t cur_shared = + shared_event_bytes != nullptr + ? shared_event_bytes->load( + std::memory_order_acquire) + : 0; + const bool budget_exceeded = + cur_shared + ev_bytes > max_shared_event_bytes; + + if (force_resync || already_resyncing || queue_full || + budget_exceeded) { + release_all_queued_locked(); + WatchEvent resync{}; + resync.kind = WatchEventKind::ResyncRequired; + resync.service = service; + resync.provider_generation = + full_snapshot.provider_generation; + resync.revision = full_snapshot.revision; + resync.snapshot = full_snapshot; + const std::size_t rb = + estimate_watch_event_bytes(resync); + if (shared_event_bytes != nullptr) { + shared_event_bytes->fetch_add( + rb, std::memory_order_acq_rel); + } + queue.emplace_back(std::move(resync), rb); + resynced = true; + } else { + if (shared_event_bytes != nullptr) { + shared_event_bytes->fetch_add( + ev_bytes, std::memory_order_acq_rel); + } + queue.emplace_back(std::move(event), ev_bytes); + } + } + if (resynced && observer) { + observer(ObservationEvent{ + .kind = ObservationKind::WatchResync, + .ok = true, + .count = 1, + }); + } + return true; + } + + bool deliver_one() + { + WatchEvent event{}; + { + std::unique_lock lk{mu}; + if (cancelled || queue.empty()) { + return false; + } + // Serialize per watch: if another thread is currently + // delivering, wait unless this is the callback thread. + if (running) { + if (callback_thread == std::this_thread::get_id()) { + return false; + } + cv.wait(lk, [this] { + return !running || cancelled || queue.empty(); + }); + if (cancelled || queue.empty()) { + return false; + } + } + auto [ev, bytes] = std::move(queue.front()); + queue.pop_front(); + if (shared_event_bytes != nullptr && bytes > 0) { + shared_event_bytes->fetch_sub( + bytes, std::memory_order_acq_rel); + } + event = std::move(ev); + running = true; + callback_thread = std::this_thread::get_id(); + } + + try { + if (callback) { + callback(std::move(event)); + } + } catch (...) { + // Never let user callback exceptions corrupt watch + // serialization or leave `running == true`. + } + + { + std::lock_guard lk{mu}; + running = false; + callback_thread = std::thread::id{}; + } + cv.notify_all(); + return true; + } + + std::size_t deliver_all() + { + std::size_t delivered = 0; + while (deliver_one()) { + ++delivered; + } + return delivered; + } + + void cancel() noexcept + { + { + std::lock_guard lk{mu}; + cancelled = true; + release_all_queued_locked(); + } + cv.notify_all(); + } + + [[nodiscard]] Result join() noexcept + { + std::unique_lock lk{mu}; + if (running && + callback_thread == std::this_thread::get_id()) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::SelfJoin, + "Discovery::WatchHandle::join cannot be called " + "synchronously from inside its own callback")); + } + if (pump_scheduled && executor != nullptr && + executor->is_executor_thread()) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::SelfJoin, + "Discovery::WatchHandle::join cannot block inside " + "its active executor thread")); + } + cv.wait(lk, + [this] { return !running && !pump_scheduled; }); + return {}; + } + }; + + struct DetachedWatchPump { + struct promise_type { + DetachedWatchPump get_return_object() noexcept + { + return DetachedWatchPump{ + std::coroutine_handle::from_promise( + *this)}; + } + std::suspend_always initial_suspend() noexcept + { + return {}; + } + std::suspend_never final_suspend() noexcept + { + return {}; + } + void return_void() noexcept {} + void unhandled_exception() noexcept {} + }; + + std::coroutine_handle handle{}; + }; + + DetachedWatchPump run_watch_pump(std::shared_ptr node) + { + node->deliver_all(); + { + std::lock_guard lk{node->mu}; + node->pump_scheduled = false; + } + node->cv.notify_all(); + co_return; + } + + void trigger_watch_delivery(const std::shared_ptr& node) + { + if (!node) { + return; + } + if (node->mode == WatchDispatchMode::Manual) { + return; + } + if (node->mode == WatchDispatchMode::Inline) { + node->deliver_all(); + return; + } + if (node->mode == WatchDispatchMode::Executor && + node->executor != nullptr) { + { + std::lock_guard lk{node->mu}; + if (node->cancelled || node->pump_scheduled || + node->queue.empty()) { + return; + } + node->pump_scheduled = true; + } + auto coro = run_watch_pump(node); + auto posted = node->executor->try_post(coro.handle); + if (!posted.has_value()) { + coro.handle.destroy(); + { + std::lock_guard lk{node->mu}; + node->pump_scheduled = false; + } + node->cv.notify_all(); + } + } + } + + void emit_obs(const ObservationHook& hook, ObservationKind kind, + bool ok, std::size_t count = 1) + { + if (hook) { + hook(ObservationEvent{ + .kind = kind, + .ok = ok, + .count = count, + }); + } + } + } // namespace + + Result validate_endpoint_record(const EndpointRecord& record, + const CatalogLimits& limits) + { + if (!is_valid_identifier(record.service)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: invalid service identifier")); + } + if (!is_valid_identifier(record.instance)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: invalid instance identifier")); + } + if (!is_valid_scheme(record.endpoint.scheme)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: invalid endpoint scheme")); + } + if (!is_valid_host(record.endpoint.host)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: invalid endpoint host")); + } + if (record.endpoint.port == 0U) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: endpoint port must be non-zero")); + } + if (!record.endpoint.expected_tls_name.empty() && + !is_valid_host(record.endpoint.expected_tls_name)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: invalid expected_tls_name")); + } + if (record.weight == 0U) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: endpoint weight must be positive")); + } + if (record.attributes.size() > limits.max_attributes_per_record) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery: endpoint attribute count exceeds limit")); + } + std::size_t meta_bytes = 0; + for (const auto& [k, v] : record.attributes) { + if (k.empty() || !is_valid_printable_ascii(k) || + !is_valid_printable_ascii(v)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery: invalid endpoint attribute key or value")); + } + meta_bytes += k.size() + v.size(); + if (meta_bytes > limits.max_metadata_bytes_per_record) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery: endpoint attribute bytes exceed limit")); + } + } + return {}; + } + + std::size_t estimate_record_bytes(const EndpointRecord& record) noexcept + { + std::size_t bytes = sizeof(EndpointRecord) + record.instance.size() + + record.service.size() + + record.endpoint.scheme.size() + + record.endpoint.host.size() + + record.endpoint.expected_tls_name.size(); + for (const auto& [k, v] : record.attributes) { + bytes += k.size() + v.size() + 32U; + } + return bytes; + } + + std::size_t estimate_watch_event_bytes(const WatchEvent& event) noexcept + { + std::size_t bytes = sizeof(WatchEvent) + event.service.size(); + if (event.snapshot.has_value()) { + for (const auto& r : event.snapshot->records) { + bytes += estimate_record_bytes(r); + } + } + for (const auto& r : event.added) { + bytes += estimate_record_bytes(r); + } + for (const auto& r : event.updated) { + bytes += estimate_record_bytes(r); + } + for (const auto& id : event.removed_instances) { + bytes += id.size() + sizeof(std::string); + } + return bytes; + } + + struct Catalog::State { + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + CatalogLimits limits{}; + ObservationHook observer{}; + + mutable std::mutex mu{}; + std::map>, + std::less<>> + services{}; + std::uint64_t provider_generation{1}; + std::uint64_t revision{0}; + std::uint64_t next_token{1}; + std::uint64_t next_watch_id{1}; + Freshness freshness{Freshness::Fresh}; + std::optional provider_error{}; + bool closed{false}; + + std::map> watches{}; + std::atomic shared_event_bytes{0}; + + [[nodiscard]] Snapshot build_snapshot_locked( + std::string_view service, ResolvePolicy policy, + Void::Time::MonotonicClock::time_point now) const + { + Snapshot snap{}; + snap.provider_generation = provider_generation; + snap.revision = revision; + snap.freshness = freshness; + snap.provider_error = provider_error; + + auto it = services.find(service); + if (it != services.end()) { + snap.records.reserve(it->second.size()); + for (const auto& [inst, stored] : it->second) { + (void)inst; + if (is_expired(stored, now)) { + continue; + } + if (!policy.include_unready && !stored.record.ready) { + continue; + } + snap.records.push_back(stored.record); + } + } + // std::map keys by `instance`, guaranteeing deterministic + // ascending instance-identity ordering. + return snap; + } + + [[nodiscard]] std::size_t count_total_records_locked() const noexcept + { + std::size_t total = 0; + for (const auto& [svc, map] : services) { + (void)svc; + total += map.size(); + } + return total; + } + + [[nodiscard]] std::vector> + matching_watches_locked(std::string_view service) const + { + std::vector> out; + for (const auto& [id, node] : watches) { + (void)id; + if (node && node->service == service) { + out.push_back(node); + } + } + return out; + } + }; + + // ── Registration ────────────────────────────────────────────────────────── + + Registration::~Registration() noexcept { release(); } + + Registration::Registration(Registration&& other) noexcept + : m_catalog_state(std::move(other.m_catalog_state)), + m_service(std::move(other.m_service)), + m_instance(std::move(other.m_instance)), m_token(other.m_token), + m_leased(other.m_leased), m_ttl(other.m_ttl), + m_active(std::exchange(other.m_active, false)) + { + } + + Registration& Registration::operator=(Registration&& other) noexcept + { + if (this != &other) { + release(); + m_catalog_state = std::move(other.m_catalog_state); + m_service = std::move(other.m_service); + m_instance = std::move(other.m_instance); + m_token = other.m_token; + m_leased = other.m_leased; + m_ttl = other.m_ttl; + m_active = std::exchange(other.m_active, false); + } + return *this; + } + + bool Registration::active() const noexcept + { + if (!m_active || !m_catalog_state) { + return false; + } + auto state = std::static_pointer_cast(m_catalog_state); + std::lock_guard lk{state->mu}; + if (state->closed) { + return false; + } + auto sit = state->services.find(m_service); + if (sit == state->services.end()) { + return false; + } + auto iit = sit->second.find(m_instance); + if (iit == sit->second.end() || iit->second.token != m_token) { + return false; + } + return !is_expired(iit->second, state->clock->now()); + } + + std::optional + Registration::expires_at() const noexcept + { + if (!m_active || !m_leased || !m_catalog_state) { + return std::nullopt; + } + auto state = std::static_pointer_cast(m_catalog_state); + std::lock_guard lk{state->mu}; + auto sit = state->services.find(m_service); + if (sit == state->services.end()) { + return std::nullopt; + } + auto iit = sit->second.find(m_instance); + if (iit == sit->second.end() || iit->second.token != m_token) { + return std::nullopt; + } + return iit->second.expires_at; + } + + Result Registration::renew() + { + if (!m_active || !m_catalog_state) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Expired, + "Discovery::Registration is not active")); + } + if (!m_leased) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery::Registration is unleased and does not require " + "renewal")); + } + + auto state = std::static_pointer_cast(m_catalog_state); + Void::Time::MonotonicClock::time_point next_expiry{}; + ObservationHook obs{}; + { + std::lock_guard lk{state->mu}; + obs = state->observer; + if (state->closed) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, + "Discovery::Catalog is closed")); + } + const auto now = state->clock->now(); + auto sit = state->services.find(m_service); + if (sit == state->services.end()) { + m_active = false; + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Expired, + "Discovery::Registration lease expired")); + } + auto iit = sit->second.find(m_instance); + if (iit == sit->second.end() || iit->second.token != m_token) { + m_active = false; + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Expired, + "Discovery::Registration no longer owned")); + } + if (is_expired(iit->second, now)) { + m_active = false; + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Expired, + "Discovery::Registration lease already expired")); + } + next_expiry = now + m_ttl; + iit->second.expires_at = next_expiry; + } + emit_obs(obs, ObservationKind::Renew, true); + return next_expiry; + } + + void Registration::release() noexcept + { + if (!m_active || !m_catalog_state) { + m_active = false; + return; + } + m_active = false; + auto state = std::static_pointer_cast(m_catalog_state); + m_catalog_state.reset(); + + std::vector> targets; + WatchEvent delta{}; + Snapshot full_snap{}; + ObservationHook obs{}; + bool removed = false; + { + std::lock_guard lk{state->mu}; + obs = state->observer; + auto sit = state->services.find(m_service); + if (sit != state->services.end()) { + auto iit = sit->second.find(m_instance); + if (iit != sit->second.end() && iit->second.token == m_token) { + sit->second.erase(iit); + if (sit->second.empty()) { + state->services.erase(sit); + } + ++state->revision; + removed = true; + targets = state->matching_watches_locked(m_service); + if (!targets.empty()) { + const auto now = state->clock->now(); + full_snap = state->build_snapshot_locked( + m_service, ResolvePolicy{}, now); + delta.kind = WatchEventKind::Delta; + delta.service = m_service; + delta.provider_generation = state->provider_generation; + delta.revision = state->revision; + delta.removed_instances.push_back(m_instance); + } + } + } + } + + if (removed) { + for (const auto& w : targets) { + if (w->enqueue(delta, full_snap)) { + trigger_watch_delivery(w); + } + } + emit_obs(obs, ObservationKind::Release, true); + } + } + + // ── WatchHandle ─────────────────────────────────────────────────────────── + + WatchHandle::~WatchHandle() noexcept { cancel(); } + + WatchHandle::WatchHandle(WatchHandle&& other) noexcept + : m_catalog_state(std::move(other.m_catalog_state)), + m_watch_node(std::move(other.m_watch_node)), + m_watch_id(std::exchange(other.m_watch_id, 0)) + { + } + + WatchHandle& WatchHandle::operator=(WatchHandle&& other) noexcept + { + if (this != &other) { + cancel(); + m_catalog_state = std::move(other.m_catalog_state); + m_watch_node = std::move(other.m_watch_node); + m_watch_id = std::exchange(other.m_watch_id, 0); + } + return *this; + } + + bool WatchHandle::active() const noexcept + { + if (!m_watch_node) { + return false; + } + auto node = std::static_pointer_cast(m_watch_node); + std::lock_guard lk{node->mu}; + return !node->cancelled; + } + + std::size_t WatchHandle::pending_events() const noexcept + { + if (!m_watch_node) { + return 0; + } + auto node = std::static_pointer_cast(m_watch_node); + std::lock_guard lk{node->mu}; + return node->queue.size(); + } + + void WatchHandle::cancel() noexcept + { + if (m_watch_node) { + auto node = std::static_pointer_cast(m_watch_node); + node->cancel(); + } + if (m_catalog_state && m_watch_id != 0) { + auto state = + std::static_pointer_cast(m_catalog_state); + std::lock_guard lk{state->mu}; + state->watches.erase(m_watch_id); + } + m_watch_id = 0; + } + + Result WatchHandle::join() noexcept + { + if (!m_watch_node) { + return {}; + } + auto node = std::static_pointer_cast(m_watch_node); + return node->join(); + } + + bool WatchHandle::deliver_one() + { + if (!m_watch_node) { + return false; + } + auto node = std::static_pointer_cast(m_watch_node); + return node->deliver_one(); + } + + std::size_t WatchHandle::deliver_all() + { + if (!m_watch_node) { + return 0; + } + auto node = std::static_pointer_cast(m_watch_node); + return node->deliver_all(); + } + + // ── Catalog ─────────────────────────────────────────────────────────────── + + Catalog::Catalog(CatalogOptions options) + : m_state(std::make_shared()) + { + m_state->clock = + options.clock != nullptr + ? options.clock + : &Void::Time::SystemMonotonicClock::instance(); + m_state->limits = options.limits; + m_state->observer = std::move(options.observer); + } + + Catalog::~Catalog() noexcept + { + if (!m_state) { + return; + } + // Destruction alone only requests stop without blocking on callbacks. + std::vector> active_watches; + { + std::lock_guard lk{m_state->mu}; + m_state->closed = true; + for (auto& [id, node] : m_state->watches) { + (void)id; + active_watches.push_back(std::move(node)); + } + m_state->watches.clear(); + } + for (const auto& w : active_watches) { + if (w) { + w->cancel(); + } + } + } + + Catalog::Catalog(Catalog&&) noexcept = default; + Catalog& Catalog::operator=(Catalog&&) noexcept = default; + + Result + Catalog::replace_static(std::vector candidate, + bool bump_provider_generation) + { + if (!m_state) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, "Discovery::Catalog moved-from")); + } + + // Phase 1: Validate every record and detect candidate-internal + // duplicates completely before taking locks or publishing anything. + std::map>, + std::less<>> + staged; + for (auto& rec : candidate) { + if (auto vr = validate_endpoint_record(rec, m_state->limits); + !vr.has_value()) { + emit_obs(m_state->observer, ObservationKind::ReplaceStatic, + false); + return Void::Result::fail(vr.error()); + } + auto& inst_map = staged[rec.service]; + if (inst_map.contains(rec.instance)) { + emit_obs(m_state->observer, ObservationKind::ReplaceStatic, + false); + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Conflict, + "Discovery::replace_static duplicate service+instance: " + + rec.service + "/" + rec.instance)); + } + inst_map.emplace(rec.instance, std::move(rec)); + } + + struct WatchDelivery { + std::shared_ptr node{}; + WatchEvent event{}; + Snapshot full_snap{}; + }; + std::vector deliveries; + std::uint64_t published_rev = 0; + ObservationHook obs{}; + + { + std::lock_guard lk{m_state->mu}; + obs = m_state->observer; + if (m_state->closed) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, + "Discovery::Catalog is closed")); + } + const auto now = m_state->clock->now(); + + // Merge active local registrations with staged static records to + // verify conflicts & caps atomically before swapping. + std::map>, + std::less<>> + next_services; + for (const auto& [svc, imap] : m_state->services) { + for (const auto& [inst, stored] : imap) { + if (!stored.is_static && !is_expired(stored, now)) { + next_services[svc].emplace(inst, stored); + } + } + } + + for (const auto& [svc, imap] : staged) { + auto& dst = next_services[svc]; + for (const auto& [inst, rec] : imap) { + if (dst.contains(inst)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Conflict, + "Discovery::replace_static conflicts with active " + "local registration: " + + svc + "/" + inst)); + } + dst.emplace(inst, StoredRecord{ + .record = rec, + .is_static = true, + .token = 0, + .leased = false, + .expires_at = {}, + }); + } + } + + if (next_services.size() > m_state->limits.max_services) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery::replace_static exceeds max_services")); + } + std::size_t total_records = 0; + for (const auto& [svc, imap] : next_services) { + if (imap.size() > m_state->limits.max_endpoints_per_service) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery::replace_static exceeds " + "max_endpoints_per_service for service: " + + svc)); + } + total_records += imap.size(); + } + if (total_records > m_state->limits.max_total_records) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery::replace_static exceeds max_total_records")); + } + + // Compute affected services & diffs before swap. + std::set> affected_services; + for (const auto& [svc, _] : m_state->services) { + affected_services.insert(svc); + } + for (const auto& [svc, _] : next_services) { + affected_services.insert(svc); + } + + auto old_services = std::move(m_state->services); + m_state->services = std::move(next_services); + if (bump_provider_generation) { + ++m_state->provider_generation; + m_state->revision = 1; + } else { + ++m_state->revision; + } + published_rev = m_state->revision; + + for (const auto& [wid, node] : m_state->watches) { + (void)wid; + if (!node) { + continue; + } + const bool touched = affected_services.contains(node->service); + if (!bump_provider_generation && !touched) { + continue; + } + Snapshot full_snap = m_state->build_snapshot_locked( + node->service, ResolvePolicy{}, now); + if (bump_provider_generation) { + WatchEvent ev{}; + ev.kind = WatchEventKind::ResyncRequired; + ev.service = node->service; + ev.provider_generation = m_state->provider_generation; + ev.revision = m_state->revision; + ev.snapshot = full_snap; + deliveries.push_back( + WatchDelivery{node, std::move(ev), full_snap}); + continue; + } + + WatchEvent delta{}; + delta.kind = WatchEventKind::Delta; + delta.service = node->service; + delta.provider_generation = m_state->provider_generation; + delta.revision = m_state->revision; + + const auto old_it = old_services.find(node->service); + const auto new_it = m_state->services.find(node->service); + + if (new_it != m_state->services.end()) { + for (const auto& [inst, stored] : new_it->second) { + if (is_expired(stored, now)) { + continue; + } + if (old_it == old_services.end() || + !old_it->second.contains(inst)) { + delta.added.push_back(stored.record); + } else if (old_it->second.at(inst).record != + stored.record) { + delta.updated.push_back(stored.record); + } + } + } + if (old_it != old_services.end()) { + for (const auto& [inst, stored] : old_it->second) { + if (is_expired(stored, now)) { + continue; + } + if (new_it == m_state->services.end() || + !new_it->second.contains(inst)) { + delta.removed_instances.push_back(inst); + } + } + } + + if (!delta.added.empty() || !delta.updated.empty() || + !delta.removed_instances.empty()) { + deliveries.push_back( + WatchDelivery{node, std::move(delta), full_snap}); + } + } + } + + for (auto& d : deliveries) { + if (d.node->enqueue(std::move(d.event), d.full_snap)) { + trigger_watch_delivery(d.node); + } + } + emit_obs(obs, ObservationKind::ReplaceStatic, true, published_rev); + return published_rev; + } + + void Catalog::set_provider_health(Freshness freshness, + std::optional provider_error) + { + if (!m_state) { + return; + } + std::lock_guard lk{m_state->mu}; + m_state->freshness = freshness; + m_state->provider_error = std::move(provider_error); + } + + Result Catalog::resolve(std::string_view service, + ResolvePolicy policy) const + { + if (!m_state) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, "Discovery::Catalog moved-from")); + } + if (!is_valid_identifier(service)) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery::resolve invalid service name")); + } + + ObservationHook obs{}; + Snapshot snap{}; + { + std::lock_guard lk{m_state->mu}; + obs = m_state->observer; + if (m_state->closed) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, + "Discovery::Catalog is closed")); + } + if (m_state->freshness == Freshness::Unavailable && + !policy.allow_stale) { + emit_obs(obs, ObservationKind::Resolve, false); + if (m_state->provider_error.has_value()) { + return Void::Result::fail(*m_state->provider_error); + } + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Unavailable, + "Discovery provider is unavailable")); + } + if (m_state->freshness == Freshness::Stale && !policy.allow_stale) { + emit_obs(obs, ObservationKind::Resolve, false); + if (m_state->provider_error.has_value()) { + return Void::Result::fail(*m_state->provider_error); + } + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Stale, + "Discovery snapshot is stale and allow_stale is false")); + } + snap = m_state->build_snapshot_locked(service, policy, + m_state->clock->now()); + } + + emit_obs(obs, ObservationKind::Resolve, true, snap.records.size()); + return snap; + } + + Result Catalog::register_local(EndpointRecord record, + LeasePolicy lease) + { + if (!m_state) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, "Discovery::Catalog moved-from")); + } + if (auto vr = validate_endpoint_record(record, m_state->limits); + !vr.has_value()) { + emit_obs(m_state->observer, ObservationKind::Register, false); + return Void::Result::fail(vr.error()); + } + if (lease.leased && lease.ttl <= std::chrono::milliseconds{0}) { + emit_obs(m_state->observer, ObservationKind::Register, false); + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery::register_local leased TTL must be positive (zero " + "TTL is invalid; use LeasePolicy::unleased())")); + } + + Registration reg{}; + std::vector> targets; + WatchEvent delta{}; + Snapshot full_snap{}; + ObservationHook obs{}; + + { + std::lock_guard lk{m_state->mu}; + obs = m_state->observer; + if (m_state->closed) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, + "Discovery::Catalog is closed")); + } + const auto now = m_state->clock->now(); + + auto sit = m_state->services.find(record.service); + if (sit != m_state->services.end()) { + auto iit = sit->second.find(record.instance); + if (iit != sit->second.end()) { + if (!is_expired(iit->second, now)) { + emit_obs(obs, ObservationKind::Register, false); + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Conflict, + "Discovery::register_local duplicate " + "service+instance: " + + record.service + "/" + record.instance)); + } + // Logically expired entry can be replaced cleanly. + sit->second.erase(iit); + } + if (sit->second.size() >= + m_state->limits.max_endpoints_per_service) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery::register_local exceeds " + "max_endpoints_per_service")); + } + } else { + if (m_state->services.size() >= m_state->limits.max_services) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery::register_local exceeds max_services")); + } + } + + if (m_state->count_total_records_locked() >= + m_state->limits.max_total_records) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery::register_local exceeds max_total_records")); + } + + const std::uint64_t token = m_state->next_token++; + StoredRecord stored{}; + stored.record = record; + stored.is_static = false; + stored.token = token; + stored.leased = lease.leased; + stored.expires_at = lease.leased ? (now + lease.ttl) + : Void::Time::MonotonicClock::time_point{}; + + m_state->services[record.service].emplace(record.instance, + std::move(stored)); + ++m_state->revision; + + reg.m_catalog_state = m_state; + reg.m_service = record.service; + reg.m_instance = record.instance; + reg.m_token = token; + reg.m_leased = lease.leased; + reg.m_ttl = lease.ttl; + reg.m_active = true; + + targets = m_state->matching_watches_locked(record.service); + if (!targets.empty()) { + full_snap = m_state->build_snapshot_locked( + record.service, ResolvePolicy{}, now); + delta.kind = WatchEventKind::Delta; + delta.service = record.service; + delta.provider_generation = m_state->provider_generation; + delta.revision = m_state->revision; + delta.added.push_back(std::move(record)); + } + } + + for (const auto& w : targets) { + if (w->enqueue(delta, full_snap)) { + trigger_watch_delivery(w); + } + } + emit_obs(obs, ObservationKind::Register, true); + return reg; + } + + Result Catalog::watch(std::string service, + std::uint64_t after_revision, + WatchCallback callback, + WatchOptions options) + { + (void)after_revision; + if (!m_state) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, "Discovery::Catalog moved-from")); + } + if (!is_valid_identifier(service) || !callback) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery::watch requires valid service name and callback")); + } + if (options.dispatch_mode == WatchDispatchMode::Executor && + options.executor == nullptr) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "Discovery::watch Executor mode requires non-null executor")); + } + + auto node = std::make_shared(); + node->service = std::move(service); + node->callback = std::move(callback); + node->mode = options.dispatch_mode; + node->executor = options.executor; + node->max_events = options.max_queued_events > 0 + ? options.max_queued_events + : m_state->limits.max_events_per_watch; + node->shared_event_bytes = &m_state->shared_event_bytes; + node->max_shared_event_bytes = m_state->limits.max_shared_event_bytes; + + Snapshot initial_snap{}; + std::uint64_t wid = 0; + { + std::lock_guard lk{m_state->mu}; + if (m_state->closed) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::Closed, + "Discovery::Catalog is closed")); + } + if (m_state->watches.size() >= m_state->limits.max_watches) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::LimitExceeded, + "Discovery::watch exceeds max_watches")); + } + node->observer = m_state->observer; + wid = m_state->next_watch_id++; + node->id = wid; + initial_snap = m_state->build_snapshot_locked( + node->service, ResolvePolicy{}, m_state->clock->now()); + m_state->watches.emplace(wid, node); + } + + WatchEvent initial_ev{}; + initial_ev.kind = WatchEventKind::InitialSnapshot; + initial_ev.service = node->service; + initial_ev.provider_generation = initial_snap.provider_generation; + initial_ev.revision = initial_snap.revision; + initial_ev.snapshot = initial_snap; + (void)node->enqueue(std::move(initial_ev), initial_snap); + + WatchHandle handle{}; + handle.m_catalog_state = m_state; + handle.m_watch_node = node; + handle.m_watch_id = wid; + + trigger_watch_delivery(node); + return handle; + } + + std::size_t Catalog::reap_expired() + { + if (!m_state) { + return 0; + } + struct WatchDelivery { + std::shared_ptr node{}; + WatchEvent event{}; + Snapshot full_snap{}; + }; + std::vector deliveries; + std::size_t reaped = 0; + ObservationHook obs{}; + + { + std::lock_guard lk{m_state->mu}; + obs = m_state->observer; + if (m_state->closed) { + return 0; + } + const auto now = m_state->clock->now(); + const std::size_t max_reap = + m_state->limits.max_expirations_per_turn; + std::map, std::less<>> + removed_by_service; + + for (auto sit = m_state->services.begin(); + sit != m_state->services.end() && reaped < max_reap;) { + for (auto iit = sit->second.begin(); + iit != sit->second.end() && reaped < max_reap;) { + if (is_expired(iit->second, now)) { + removed_by_service[sit->first].push_back(iit->first); + iit = sit->second.erase(iit); + ++reaped; + } else { + ++iit; + } + } + if (sit->second.empty()) { + sit = m_state->services.erase(sit); + } else { + ++sit; + } + } + + if (reaped > 0) { + ++m_state->revision; + for (auto& [svc, removed] : removed_by_service) { + auto targets = m_state->matching_watches_locked(svc); + if (targets.empty()) { + continue; + } + Snapshot full_snap = m_state->build_snapshot_locked( + svc, ResolvePolicy{}, now); + WatchEvent delta{}; + delta.kind = WatchEventKind::Delta; + delta.service = svc; + delta.provider_generation = m_state->provider_generation; + delta.revision = m_state->revision; + delta.removed_instances = std::move(removed); + for (const auto& w : targets) { + deliveries.push_back( + WatchDelivery{w, delta, full_snap}); + } + } + } + } + + for (auto& d : deliveries) { + if (d.node->enqueue(std::move(d.event), d.full_snap)) { + trigger_watch_delivery(d.node); + } + } + if (reaped > 0) { + emit_obs(obs, ObservationKind::Expire, true, reaped); + } + return reaped; + } + + Result Catalog::shutdown_and_join() noexcept + { + if (!m_state) { + return {}; + } + std::vector> active_watches; + { + std::lock_guard lk{m_state->mu}; + m_state->closed = true; + // Remove all local registrations during explicit shutdown. + for (auto sit = m_state->services.begin(); + sit != m_state->services.end();) { + for (auto iit = sit->second.begin(); + iit != sit->second.end();) { + if (!iit->second.is_static) { + iit = sit->second.erase(iit); + } else { + ++iit; + } + } + if (sit->second.empty()) { + sit = m_state->services.erase(sit); + } else { + ++sit; + } + } + for (auto& [id, node] : m_state->watches) { + (void)id; + active_watches.push_back(std::move(node)); + } + m_state->watches.clear(); + } + + for (const auto& w : active_watches) { + if (w) { + w->cancel(); + } + } + for (const auto& w : active_watches) { + if (w) { + if (auto jr = w->join(); !jr.has_value()) { + return jr; + } + } + } + return {}; + } + + std::uint64_t Catalog::revision() const noexcept + { + if (!m_state) { + return 0; + } + std::lock_guard lk{m_state->mu}; + return m_state->revision; + } + + std::uint64_t Catalog::provider_generation() const noexcept + { + if (!m_state) { + return 0; + } + std::lock_guard lk{m_state->mu}; + return m_state->provider_generation; + } + + std::size_t Catalog::active_record_count() const noexcept + { + if (!m_state) { + return 0; + } + std::lock_guard lk{m_state->mu}; + const auto now = m_state->clock->now(); + std::size_t total = 0; + for (const auto& [svc, imap] : m_state->services) { + (void)svc; + for (const auto& [inst, stored] : imap) { + (void)inst; + if (!is_expired(stored, now)) { + ++total; + } + } + } + return total; + } + + std::size_t Catalog::active_watch_count() const noexcept + { + if (!m_state) { + return 0; + } + std::lock_guard lk{m_state->mu}; + return m_state->watches.size(); + } + + std::size_t Catalog::shared_watch_event_bytes() const noexcept + { + if (!m_state) { + return 0; + } + return m_state->shared_event_bytes.load(std::memory_order_acquire); + } + + // ── ManagedLeaseRenewer ─────────────────────────────────────────────────── + + ManagedLeaseRenewer::ManagedLeaseRenewer( + Registration& registration, std::chrono::milliseconds renew_interval, + const Void::Time::MonotonicClock* clock) noexcept + : m_registration(®istration), + m_interval(renew_interval > std::chrono::milliseconds{0} + ? renew_interval + : std::chrono::seconds{10}), + m_clock(clock != nullptr + ? clock + : &Void::Time::SystemMonotonicClock::instance()), + m_next_renew(m_clock->now() + m_interval) + { + } + + bool ManagedLeaseRenewer::due() const noexcept + { + return m_clock->now() >= m_next_renew; + } + + Result ManagedLeaseRenewer::tick() + { + if (m_registration == nullptr) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::InvalidArgument, + "ManagedLeaseRenewer has no registration")); + } + if (!due()) { + return false; + } + auto r = m_registration->renew(); + if (!r.has_value()) { + ++m_consecutive_failures; + return Void::Result::fail(r.error()); + } + m_consecutive_failures = 0; + m_next_renew = m_clock->now() + m_interval; + return true; + } + + // ── WeightedRoundRobinSelector ──────────────────────────────────────────── + + Result + WeightedRoundRobinSelector::select(const Snapshot& snapshot) + { + if (snapshot.records.empty()) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::NotFound, + "WeightedRoundRobinSelector: snapshot has no endpoints")); + } + + std::lock_guard lk{m_mu}; + std::int64_t total_weight = 0; + std::size_t best_idx = 0; + std::int64_t best_weight = std::numeric_limits::min(); + + for (std::size_t i = 0; i < snapshot.records.size(); ++i) { + const auto& rec = snapshot.records[i]; + const auto w = static_cast( + rec.weight > 0U ? rec.weight : 1U); + total_weight += w; + auto& cw = m_current_weights[rec.instance]; + cw += w; + if (cw > best_weight) { + best_weight = cw; + best_idx = i; + } + } + + const auto& chosen = snapshot.records[best_idx]; + m_current_weights[chosen.instance] -= total_weight; + return chosen; + } + + void WeightedRoundRobinSelector::reset() noexcept + { + std::lock_guard lk{m_mu}; + m_current_weights.clear(); + } + + // ── AffinitySelector ────────────────────────────────────────────────────── + + Result + AffinitySelector::select(const Snapshot& snapshot, + std::string_view affinity_key) + { + if (snapshot.records.empty()) { + return Void::Result::fail(make_discovery_error( + DiscoveryErrorCode::NotFound, + "AffinitySelector: snapshot has no endpoints")); + } + + std::size_t best_idx = 0; + double best_score = -1.0; + + for (std::size_t i = 0; i < snapshot.records.size(); ++i) { + const auto& rec = snapshot.records[i]; + std::uint64_t h = Void::Hash::fnv1a64(affinity_key); + h = Void::Hash::fnv1a64_update(h, std::string_view{"\x1F"}); + h = Void::Hash::fnv1a64_update(h, rec.instance); + // Map non-zero uniform hash into (0, 1] and apply weighted HRW + // score: -weight / ln(u) -> equivalent maximize weight / -ln(u). + const double u = + (static_cast((h >> 11U) + 1ULL)) / + static_cast((1ULL << 53U) + 1ULL); + const double neg_log = -std::log(u); + const double weight = + static_cast(rec.weight > 0U ? rec.weight : 1U); + const double score = + neg_log > 0.0 ? (weight / neg_log) + : std::numeric_limits::max(); + if (score > best_score) { + best_score = score; + best_idx = i; + } + } + + return snapshot.records[best_idx]; + } + +} // namespace Void::Discovery diff --git a/src/Discovery/module.cmake b/src/Discovery/module.cmake new file mode 100644 index 0000000..6dbbd34 --- /dev/null +++ b/src/Discovery/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Discovery + INTERNAL_DEPS Core Functional Time Async +) diff --git a/src/DiscoveryRpc/EndpointAdapter.cpp b/src/DiscoveryRpc/EndpointAdapter.cpp new file mode 100644 index 0000000..9e27c2e --- /dev/null +++ b/src/DiscoveryRpc/EndpointAdapter.cpp @@ -0,0 +1,144 @@ +#include + +#include +#include + +namespace Void::DiscoveryRpc +{ + namespace + { + struct OutstandingGuard { + std::atomic& 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 + EndpointResolverClient::select_endpoint( + std::optional 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 + EndpointResolverClient::call( + Void::RPC::MethodId method, Void::RPC::OwnedBytes payload, + Void::RPC::CallOptions options, + std::optional 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 diff --git a/src/DiscoveryRpc/module.cmake b/src/DiscoveryRpc/module.cmake new file mode 100644 index 0000000..be99729 --- /dev/null +++ b/src/DiscoveryRpc/module.cmake @@ -0,0 +1,3 @@ +void_add_module(DiscoveryRpc + INTERNAL_DEPS Discovery RPC +) diff --git a/tests/package/DiscoveryOnly/CMakeLists.txt b/tests/package/DiscoveryOnly/CMakeLists.txt new file mode 100644 index 0000000..8324b7c --- /dev/null +++ b/tests/package/DiscoveryOnly/CMakeLists.txt @@ -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) diff --git a/tests/package/DiscoveryOnly/main.cpp b/tests/package/DiscoveryOnly/main.cpp new file mode 100644 index 0000000..5356f38 --- /dev/null +++ b/tests/package/DiscoveryOnly/main.cpp @@ -0,0 +1,24 @@ +#include + +#include + +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; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index cf69b36..eeb75eb 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -318,6 +318,11 @@ 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() + # 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) diff --git a/tests/standalone/Discovery/Catalog.cpp b/tests/standalone/Discovery/Catalog.cpp new file mode 100644 index 0000000..391462e --- /dev/null +++ b/tests/standalone/Discovery/Catalog.cpp @@ -0,0 +1,278 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +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(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(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(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(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(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 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(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); +} diff --git a/tests/standalone/DiscoveryRpc/EndpointAdapter.cpp b/tests/standalone/DiscoveryRpc/EndpointAdapter.cpp new file mode 100644 index 0000000..ef0e2f0 --- /dev/null +++ b/tests/standalone/DiscoveryRpc/EndpointAdapter.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include + +#include + +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 { + 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(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(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(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(DiscoveryErrorCode::TlsIdentityMismatch)); + + server.shutdown(); +} From aaeab50758ecd1b1ab9e30683194c34f73da4aa4 Mon Sep 17 00:00:00 2001 From: faumaray Date: Fri, 27 Nov 2026 05:38:06 +0300 Subject: [PATCH 3/5] feat(scheduler): implement P3 S-SCHEDULER-01..04 Scheduler engine, calendar/DST, and SchedulerStorage durable store --- include/Void/Scheduler/Calendar.hpp | 135 ++ include/Void/Scheduler/Scheduler.hpp | 100 + include/Void/Scheduler/Store.hpp | 105 ++ include/Void/Scheduler/Types.hpp | 339 ++++ .../Void/SchedulerStorage/StorageJobStore.hpp | 111 ++ src/Scheduler/Calendar.cpp | 632 +++++++ src/Scheduler/Scheduler.cpp | 1649 +++++++++++++++++ src/Scheduler/module.cmake | 3 + src/SchedulerStorage/StorageJobStore.cpp | 1078 +++++++++++ src/SchedulerStorage/module.cmake | 3 + tests/package/InstalledComponents.cmake | 5 + tests/package/SchedulerOnly/CMakeLists.txt | 14 + tests/package/SchedulerOnly/main.cpp | 41 + tests/standalone/Scheduler/Scheduler.cpp | 307 +++ .../SchedulerStorage/StorageJobStore.cpp | 172 ++ 15 files changed, 4694 insertions(+) create mode 100644 include/Void/Scheduler/Calendar.hpp create mode 100644 include/Void/Scheduler/Scheduler.hpp create mode 100644 include/Void/Scheduler/Store.hpp create mode 100644 include/Void/Scheduler/Types.hpp create mode 100644 include/Void/SchedulerStorage/StorageJobStore.hpp create mode 100644 src/Scheduler/Calendar.cpp create mode 100644 src/Scheduler/Scheduler.cpp create mode 100644 src/Scheduler/module.cmake create mode 100644 src/SchedulerStorage/StorageJobStore.cpp create mode 100644 src/SchedulerStorage/module.cmake create mode 100644 tests/package/SchedulerOnly/CMakeLists.txt create mode 100644 tests/package/SchedulerOnly/main.cpp create mode 100644 tests/standalone/Scheduler/Scheduler.cpp create mode 100644 tests/standalone/SchedulerStorage/StorageJobStore.cpp diff --git a/include/Void/Scheduler/Calendar.hpp b/include/Void/Scheduler/Calendar.hpp new file mode 100644 index 0000000..8c1bf02 --- /dev/null +++ b/include/Void/Scheduler/Calendar.hpp @@ -0,0 +1,135 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +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 gap_start_local_min{}; + std::optional 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 fold_start_local_min{}; + std::optional 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 + validate_timezone(std::string_view tz) const; + + [[nodiscard]] Result> + 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> + local_minute_bounds(std::string_view tz, + std::int64_t utc_min_lo, + std::int64_t utc_min_hi) const; + + private: + + std::map> m_dst_zones{}; + }; + + struct MaterializedSlots { + std::vector 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 + 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 + 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 + prev_matching_minute(std::int64_t from_local_min, + std::int64_t min_local_min) const noexcept; + + [[nodiscard]] Result + 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 diff --git a/include/Void/Scheduler/Scheduler.hpp b/include/Void/Scheduler/Scheduler.hpp new file mode 100644 index 0000000..a8de73c --- /dev/null +++ b/include/Void/Scheduler/Scheduler.hpp @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Scheduler +{ + struct SchedulerOptions { + std::string owner_id{"scheduler-default"}; + std::shared_ptr 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 + create(SchedulerOptions options = {}); + + Scheduler(Scheduler&&) noexcept; + Scheduler& operator=(Scheduler&&) noexcept; + Scheduler(const Scheduler&) = delete; + Scheduler& operator=(const Scheduler&) = delete; + ~Scheduler() noexcept; + + [[nodiscard]] Result register_handler(std::string handler_id, + HandlerFn handler); + + [[nodiscard]] Result + 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 + 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 + 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 + tick(Void::Async::OperationOptions options = {}); + + /// Execute at most one ready occurrence from the monotonic min-heap + /// outside scheduler/store locks. + [[nodiscard]] Result + 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 + close_and_join(Void::Async::OperationOptions options = {}); + + [[nodiscard]] Result> list_jobs() const; + [[nodiscard]] Result> + list_occurrences() const; + [[nodiscard]] Result + acknowledge_dead(const OccurrenceId& id); + [[nodiscard]] Result + prune_completed(std::size_t max_count = 256); + [[nodiscard]] Result + reclaim_invalidated(std::size_t max_count = 256); + [[nodiscard]] Result stats() const; + + private: + + struct State; + explicit Scheduler(std::shared_ptr state) noexcept; + std::shared_ptr m_state; + }; + +} // namespace Void::Scheduler diff --git a/include/Void/Scheduler/Store.hpp b/include/Void/Scheduler/Store.hpp new file mode 100644 index 0000000..593e72a --- /dev/null +++ b/include/Void/Scheduler/Store.hpp @@ -0,0 +1,105 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +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 + acquire_ownership(std::string_view owner_id) = 0; + + [[nodiscard]] virtual Result release_ownership() = 0; + + [[nodiscard]] virtual Result put_job(const JobRecord& job) = 0; + + [[nodiscard]] virtual Result + update_job(const JobRecord& updated, + std::uint64_t expected_revision) = 0; + + [[nodiscard]] virtual Result + tombstone_job(std::string_view job_id) = 0; + + [[nodiscard]] virtual Result> + load_jobs() const = 0; + + [[nodiscard]] virtual Result> + 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 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& records) = 0; + + /// Atomically verify job is not tombstoned, check old-revision + /// invalidation watermark, and transition `Pending -> Running` + /// bumping `attempt`. + [[nodiscard]] virtual Result + 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 complete_occurrence( + const OccurrenceId& id, std::uint32_t attempt, + std::int64_t completed_utc_ms, + std::optional fixed_delay_next_monotonic_ns = + std::nullopt) = 0; + + /// Atomically transition `Running -> Pending` (retry) or + /// `Running -> Dead` (exhausted). + [[nodiscard]] virtual Result 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 + 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 + recover_running_occurrences() = 0; + + [[nodiscard]] virtual Result + acknowledge_dead(const OccurrenceId& id) = 0; + + [[nodiscard]] virtual Result + prune_completed(std::int64_t before_utc_ms, + std::size_t max_count) = 0; + + [[nodiscard]] virtual Result + reclaim_invalidated(std::size_t max_count) = 0; + + [[nodiscard]] virtual Result stats() const = 0; + }; + + /// Default in-memory `JobStore` implementation requiring zero `Storage` + /// dependency. + [[nodiscard]] std::shared_ptr + make_in_memory_job_store(SchedulerLimits limits = {}); + +} // namespace Void::Scheduler diff --git a/include/Void/Scheduler/Types.hpp b/include/Void/Scheduler/Types.hpp new file mode 100644 index 0000000..2e6d4fa --- /dev/null +++ b/include/Void/Scheduler/Types.hpp @@ -0,0 +1,339 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Scheduler +{ + using Void::Result::Error; + template using Result = Void::Result::Result; + + 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(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 + 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 + 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 + 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 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 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 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; + using RandomU64Fn = std::function; + + 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( + const OccurrenceContext&, std::span, + Void::Async::OperationOptions)>; + + [[nodiscard]] inline std::int64_t + to_ns(Void::Time::MonotonicClock::time_point tp) noexcept + { + return std::chrono::duration_cast( + 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( + tp.time_since_epoch()) + .count(); + } + +} // namespace Void::Scheduler diff --git a/include/Void/SchedulerStorage/StorageJobStore.hpp b/include/Void/SchedulerStorage/StorageJobStore.hpp new file mode 100644 index 0000000..8b4f919 --- /dev/null +++ b/include/Void/SchedulerStorage/StorageJobStore.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include +#include + +#include +#include + +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 + acquire_ownership(std::string_view owner_id) override; + + [[nodiscard]] Void::Scheduler::Result + release_ownership() override; + + [[nodiscard]] Void::Scheduler::Result + put_job(const Void::Scheduler::JobRecord& job) override; + + [[nodiscard]] Void::Scheduler::Result + update_job(const Void::Scheduler::JobRecord& updated, + std::uint64_t expected_revision) override; + + [[nodiscard]] Void::Scheduler::Result + tombstone_job(std::string_view job_id) override; + + [[nodiscard]] Void::Scheduler::Result< + std::vector> + load_jobs() const override; + + [[nodiscard]] Void::Scheduler::Result< + std::vector> + load_occurrences() const override; + + [[nodiscard]] Void::Scheduler::Result + 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& + 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 complete_occurrence( + const Void::Scheduler::OccurrenceId& id, std::uint32_t attempt, + std::int64_t completed_utc_ms, + std::optional fixed_delay_next_monotonic_ns = + std::nullopt) override; + + [[nodiscard]] Void::Scheduler::Result 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 + requeue_on_shutdown(const Void::Scheduler::OccurrenceId& id, + std::uint32_t attempt) override; + + [[nodiscard]] Void::Scheduler::Result + recover_running_occurrences() override; + + [[nodiscard]] Void::Scheduler::Result + acknowledge_dead(const Void::Scheduler::OccurrenceId& id) override; + + [[nodiscard]] Void::Scheduler::Result + prune_completed(std::int64_t before_utc_ms, + std::size_t max_count) override; + + [[nodiscard]] Void::Scheduler::Result + reclaim_invalidated(std::size_t max_count) override; + + [[nodiscard]] Void::Scheduler::Result + stats() const override; + + private: + + Void::Storage::Engine* m_engine{nullptr}; + StorageJobStoreOptions m_options{}; + std::string m_owner_id{}; + }; + +} // namespace Void::SchedulerStorage diff --git a/src/Scheduler/Calendar.cpp b/src/Scheduler/Calendar.cpp new file mode 100644 index 0000000..238e72e --- /dev/null +++ b/src/Scheduler/Calendar.cpp @@ -0,0 +1,632 @@ +#include + +#include +#include +#include +#include +#include +#include + +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(y) - (m <= 2); + const std::int64_t era = + (y_adj >= 0 ? y_adj : y_adj - 399) / 400; + const auto yoe = + static_cast(y_adj - era * 400); // [0, 399] + const std::uint64_t doy = + (153U * (m + (m > 2 ? static_cast(-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(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 + 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(hh * 60U + mm); + } + + [[nodiscard]] Result 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(hour) * 60LL + + static_cast(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(rem / 60LL); + const auto minute = static_cast(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(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(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( + doy - (153U * mp + 2U) / 5U + 1U); // [1, 31] + const auto m = + static_cast(mp < 10U ? mp + 3U : mp - 9U); // [1, 12] + const auto year = static_cast(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(wd), + }; + } + + // ── TimezoneRegistry ────────────────────────────────────────────────────── + + void TimezoneRegistry::register_dst_zone(DstTransitionRule rule) + { + if (!rule.name.empty()) { + m_dst_zones[rule.name] = std::move(rule); + } + } + + Result 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> 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(*fixed); + return std::vector{ + 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{}; + } + const std::int64_t shifted_utc_min = + *rule.gap_end_local_min - + static_cast(rule.dst_offset_minutes); + return std::vector{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(rule.dst_offset_minutes); + const std::int64_t second_utc_min = + local_epoch_minute - + static_cast(rule.standard_offset_minutes); + switch (fold_policy) { + case DstFoldPolicy::First: + return std::vector{ResolvedSlot{ + .utc_ms = first_utc_min * 60000LL, .fold_index = 0}}; + case DstFoldPolicy::Second: + return std::vector{ResolvedSlot{ + .utc_ms = second_utc_min * 60000LL, .fold_index = 1}}; + case DstFoldPolicy::Twice: + return std::vector{ + 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(off); + return std::vector{ + ResolvedSlot{.utc_ms = utc_min * 60000LL, .fold_index = 0}}; + } + + Result> + 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::parse(std::string_view expression) + { + std::vector 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(*hr_m); + expr.m_days = static_cast(*day_m); + expr.m_months = static_cast(*mon_m); + expr.m_weekdays = static_cast(*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 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 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 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 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 diff --git a/src/Scheduler/Scheduler.cpp b/src/Scheduler/Scheduler.cpp new file mode 100644 index 0000000..399e572 --- /dev/null +++ b/src/Scheduler/Scheduler.cpp @@ -0,0 +1,1649 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Scheduler +{ + namespace + { + [[nodiscard]] bool is_valid_id(std::string_view s) noexcept + { + if (s.empty() || s.size() > 256U) { + return false; + } + for (unsigned char c : s) { + if (c < 0x21U || c > 0x7EU) { + return false; + } + } + return true; + } + + struct SlotDedupKey { + std::string job_id{}; + std::uint64_t revision{0}; + std::int64_t intended_utc_ms{0}; + std::uint8_t fold_index{0}; + + [[nodiscard]] auto + operator<=>(const SlotDedupKey&) const noexcept = default; + }; + + [[nodiscard]] std::size_t + count_retained_map(const std::map& occs) noexcept + { + return occs.size(); + } + + class InMemoryJobStore final : public JobStore + { + public: + + explicit InMemoryJobStore(SchedulerLimits limits) + : m_limits(limits) + { + } + + Result acquire_ownership(std::string_view owner_id) override + { + std::lock_guard lk{m_mu}; + if (m_owner.has_value() && *m_owner != owner_id) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::OwnershipLocked, + "InMemoryJobStore already owned by '" + *m_owner + + "'")); + } + m_owner = std::string{owner_id}; + return {}; + } + + Result release_ownership() override + { + std::lock_guard lk{m_mu}; + m_owner.reset(); + return {}; + } + + Result put_job(const JobRecord& job) override + { + std::lock_guard lk{m_mu}; + if (m_jobs.contains(job.spec.id)) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "Scheduler: job already exists: " + job.spec.id)); + } + if (m_jobs.size() >= m_limits.max_jobs) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Overloaded, + "Scheduler: max_jobs limit reached")); + } + if (count_retained_map(m_occurrences) >= + m_limits.max_retained_occurrences) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::RetentionFull, + "Scheduler: occurrence retention cap saturated")); + } + m_jobs.emplace(job.spec.id, job); + return {}; + } + + Result update_job(const JobRecord& updated, + std::uint64_t expected_revision) override + { + std::lock_guard lk{m_mu}; + auto it = m_jobs.find(updated.spec.id); + if (it == m_jobs.end() || it->second.tombstoned) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: job not found: " + updated.spec.id)); + } + if (it->second.revision != expected_revision) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "Scheduler: concurrent revision conflict on update")); + } + it->second = updated; + return {}; + } + + Result tombstone_job(std::string_view job_id) override + { + std::lock_guard lk{m_mu}; + auto it = m_jobs.find(job_id); + if (it == m_jobs.end()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: job not found")); + } + it->second.tombstoned = true; + return {}; + } + + Result> load_jobs() const override + { + std::lock_guard lk{m_mu}; + std::vector out; + out.reserve(m_jobs.size()); + for (const auto& [k, v] : m_jobs) { + (void)k; + out.push_back(v); + } + return out; + } + + Result> + load_occurrences() const override + { + std::lock_guard lk{m_mu}; + std::vector out; + out.reserve(m_occurrences.size()); + for (const auto& [k, v] : m_occurrences) { + (void)k; + out.push_back(v); + } + return out; + } + + Result 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& records) override + { + std::lock_guard lk{m_mu}; + auto jit = m_jobs.find(job_id); + if (jit == m_jobs.end() || jit->second.tombstoned) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: job missing or tombstoned")); + } + if (jit->second.revision != expected_revision) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "Scheduler: job revision mismatch during " + "materialization")); + } + + // Filter out duplicates via unique slot index first, then + // reserve retention capacity before advancing cursor. + std::vector to_insert; + to_insert.reserve(records.size()); + for (const auto& rec : records) { + SlotDedupKey dk{rec.id.job_id, rec.id.revision, + rec.intended_utc_ms, rec.fold_index}; + if (jit->second.spec.schedule.kind == + ScheduleKind::Calendar && + m_slot_index.contains(dk)) { + continue; + } + if (m_occurrences.contains(rec.id)) { + continue; + } + to_insert.push_back(rec); + } + + if (m_occurrences.size() + to_insert.size() > + m_limits.max_retained_occurrences) { + // Never advance cursor when retention is saturated! + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::RetentionFull, + "Scheduler: occurrence retention cap reached; " + "pausing materialization without advancing cursor")); + } + + for (const auto& rec : to_insert) { + if (jit->second.spec.schedule.kind == + ScheduleKind::Calendar) { + m_slot_index.insert(SlotDedupKey{ + rec.id.job_id, rec.id.revision, + rec.intended_utc_ms, rec.fold_index}); + } + m_occurrences.emplace(rec.id, rec); + } + + jit->second.cursor_utc_ms = new_cursor_utc_ms; + jit->second.cursor_monotonic_ns = new_cursor_monotonic_ns; + jit->second.cursor_initialized = cursor_initialized; + jit->second.one_shot_materialized = one_shot_materialized; + jit->second.next_sequence = next_sequence; + return to_insert.size(); + } + + Result + claim_occurrence(const OccurrenceId& id, + std::uint32_t expected_attempt) override + { + std::lock_guard lk{m_mu}; + auto jit = m_jobs.find(id.job_id); + if (jit == m_jobs.end() || jit->second.tombstoned) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, + "Scheduler: job tombstoned before claim")); + } + if (id.revision < jit->second.invalidated_before_revision) { + auto oit = m_occurrences.find(id); + if (oit != m_occurrences.end() && + oit->second.status == OccurrenceStatus::Pending) { + oit->second.status = OccurrenceStatus::Cancelled; + } + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, + "Scheduler: occurrence invalidated by newer job " + "revision")); + } + auto oit = m_occurrences.find(id); + if (oit == m_occurrences.end()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: occurrence not found")); + } + if (oit->second.status != OccurrenceStatus::Pending || + oit->second.attempt != expected_attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "Scheduler: occurrence state changed before claim")); + } + oit->second.status = OccurrenceStatus::Running; + oit->second.attempt += 1U; + return oit->second; + } + + Result complete_occurrence( + const OccurrenceId& id, std::uint32_t attempt, + std::int64_t completed_utc_ms, + std::optional fixed_delay_next_monotonic_ns) + override + { + std::lock_guard lk{m_mu}; + auto oit = m_occurrences.find(id); + if (oit == m_occurrences.end()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: occurrence not found on complete")); + } + if (oit->second.status != OccurrenceStatus::Running || + oit->second.attempt != attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "Scheduler: stale attempt on complete")); + } + oit->second.status = OccurrenceStatus::Completed; + oit->second.completed_utc_ms = completed_utc_ms; + if (fixed_delay_next_monotonic_ns.has_value()) { + auto jit = m_jobs.find(id.job_id); + if (jit != m_jobs.end() && !jit->second.tombstoned && + jit->second.revision == id.revision) { + jit->second.cursor_monotonic_ns = + *fixed_delay_next_monotonic_ns; + jit->second.cursor_initialized = true; + } + } + return {}; + } + + Result 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) override + { + std::lock_guard lk{m_mu}; + auto oit = m_occurrences.find(id); + if (oit == m_occurrences.end()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: occurrence not found on fail")); + } + if (oit->second.status != OccurrenceStatus::Running || + oit->second.attempt != attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "Scheduler: stale attempt on fail")); + } + oit->second.diagnostic_category = + std::move(diagnostic_category); + if (mark_dead) { + oit->second.status = OccurrenceStatus::Dead; + } else { + oit->second.status = OccurrenceStatus::Pending; + oit->second.due_monotonic_ns = next_due_monotonic_ns; + oit->second.intended_utc_ms = next_due_utc_ms; + } + return {}; + } + + Result requeue_on_shutdown(const OccurrenceId& id, + std::uint32_t attempt) override + { + std::lock_guard lk{m_mu}; + auto oit = m_occurrences.find(id); + if (oit == m_occurrences.end()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: occurrence not found on shutdown " + "requeue")); + } + if (oit->second.status != OccurrenceStatus::Running || + oit->second.attempt != attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "Scheduler: stale attempt on shutdown requeue")); + } + oit->second.status = OccurrenceStatus::Pending; + if (oit->second.attempt > 0U) { + oit->second.attempt -= 1U; + } + return {}; + } + + Result recover_running_occurrences() override + { + std::lock_guard lk{m_mu}; + std::size_t recovered = 0; + for (auto& [id, rec] : m_occurrences) { + (void)id; + if (rec.status == OccurrenceStatus::Running) { + rec.status = OccurrenceStatus::Pending; + ++recovered; + } + } + return recovered; + } + + Result acknowledge_dead(const OccurrenceId& id) override + { + std::lock_guard lk{m_mu}; + auto oit = m_occurrences.find(id); + if (oit == m_occurrences.end()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler: occurrence not found")); + } + if (oit->second.status != OccurrenceStatus::Dead) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "Scheduler: occurrence is not in Dead status")); + } + oit->second.dead_acknowledged = true; + return {}; + } + + Result + prune_completed(std::int64_t before_utc_ms, + std::size_t max_count) override + { + std::lock_guard lk{m_mu}; + std::size_t pruned = 0; + for (auto it = m_occurrences.begin(); + it != m_occurrences.end() && pruned < max_count;) { + const bool prunable_completed = + it->second.status == OccurrenceStatus::Completed && + it->second.completed_utc_ms <= before_utc_ms; + const bool prunable_dead = + it->second.status == OccurrenceStatus::Dead && + it->second.dead_acknowledged; + if (prunable_completed || prunable_dead) { + it = m_occurrences.erase(it); + ++pruned; + } else { + ++it; + } + } + return pruned; + } + + Result + reclaim_invalidated(std::size_t max_count) override + { + std::lock_guard lk{m_mu}; + std::size_t reclaimed = 0; + for (auto it = m_occurrences.begin(); + it != m_occurrences.end() && reclaimed < max_count;) { + bool invalid = + it->second.status == OccurrenceStatus::Cancelled; + if (!invalid && + it->second.status == OccurrenceStatus::Pending) { + auto jit = m_jobs.find(it->first.job_id); + if (jit != m_jobs.end() && + (jit->second.tombstoned || + it->first.revision < + jit->second.invalidated_before_revision)) { + invalid = true; + } + } + if (invalid) { + it = m_occurrences.erase(it); + ++reclaimed; + } else { + ++it; + } + } + return reclaimed; + } + + Result stats() const override + { + std::lock_guard lk{m_mu}; + StoreStats s{}; + s.jobs = m_jobs.size(); + for (const auto& [id, rec] : m_occurrences) { + (void)id; + switch (rec.status) { + case OccurrenceStatus::Pending: ++s.pending; break; + case OccurrenceStatus::Running: ++s.running; break; + case OccurrenceStatus::Completed: + ++s.completed; + break; + case OccurrenceStatus::Dead: ++s.dead; break; + case OccurrenceStatus::Cancelled: + ++s.cancelled; + break; + } + } + s.total_retained = m_occurrences.size(); + s.retention_saturated = + s.total_retained >= m_limits.max_retained_occurrences; + return s; + } + + private: + + SchedulerLimits m_limits{}; + mutable std::mutex m_mu{}; + std::optional m_owner{}; + std::map> m_jobs{}; + std::map m_occurrences{}; + std::set m_slot_index{}; + }; + + struct HeapEntry { + std::int64_t due_monotonic_ns{0}; + std::uint64_t sequence{0}; + OccurrenceId id{}; + + // Min-heap comparator (priority_queue pops largest, so invert). + [[nodiscard]] bool operator>(const HeapEntry& o) const noexcept + { + if (due_monotonic_ns != o.due_monotonic_ns) { + return due_monotonic_ns > o.due_monotonic_ns; + } + if (sequence != o.sequence) { + return sequence > o.sequence; + } + return id > o.id; + } + }; + + struct ActiveExecution { + OccurrenceId id{}; + std::stop_source stop_source{}; + std::thread::id worker_thread{}; + }; + + [[nodiscard]] std::int64_t compute_retry_delay_ms( + const RetryPolicy& policy, std::uint32_t attempt, + const RandomU64Fn& rng) + { + const std::int64_t base_ms = std::max( + 0LL, policy.base_delay.count()); + const std::int64_t max_ms = std::max( + base_ms, policy.max_delay.count()); + if (max_ms == 0LL) { + return 0LL; + } + std::int64_t cap_ms = base_ms; + const std::uint32_t mult = std::max(1U, policy.multiplier); + for (std::uint32_t i = 1U; i < attempt; ++i) { + if (cap_ms > max_ms / static_cast(mult)) { + cap_ms = max_ms; + break; + } + cap_ms *= static_cast(mult); + } + cap_ms = std::min(cap_ms, max_ms); + if (cap_ms <= 0LL) { + return 0LL; + } + const std::uint64_t r = rng ? rng() : 0ULL; + return static_cast( + r % (static_cast(cap_ms) + 1ULL)); + } + } // namespace + + std::shared_ptr make_in_memory_job_store(SchedulerLimits limits) + { + return std::make_shared(limits); + } + + struct Scheduler::State { + std::string owner_id{}; + std::shared_ptr 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{}; + + mutable std::mutex mu{}; + std::condition_variable active_cv{}; + bool closing{false}; + bool closed_cleanly{false}; + + std::map> handlers{}; + std::map> jobs{}; + std::map> + parsed_calendars{}; + std::map pending_cache{}; + std::priority_queue, + std::greater> + heap{}; + std::map> active{}; + std::map> active_per_job{}; + + void emit(ObservationKind kind, std::size_t count = 1, + std::int64_t lag_ms = 0) const + { + if (observer) { + observer(ObservationEvent{ + .kind = kind, + .count = count, + .lag_ms = lag_ms, + }); + } + } + + [[nodiscard]] Result> + validate_job_spec(const JobSpec& spec) const + { + if (!is_valid_id(spec.id)) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "Scheduler: invalid job id")); + } + if (!is_valid_id(spec.handler_id)) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "Scheduler: invalid handler_id")); + } + if (spec.payload.size() > limits.max_payload_bytes) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "Scheduler: job payload exceeds max_payload_bytes")); + } + if (spec.retry.max_attempts == 0U || + spec.retry.base_delay < std::chrono::milliseconds{0} || + spec.retry.max_delay < spec.retry.base_delay || + spec.retry.multiplier == 0U) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "Scheduler: invalid RetryPolicy")); + } + if (spec.overlap == OverlapPolicy::AllowBounded && + spec.max_concurrent == 0U) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "Scheduler: AllowBounded overlap requires " + "max_concurrent >= 1")); + } + + switch (spec.schedule.kind) { + case ScheduleKind::OneShot: + return std::optional{std::nullopt}; + case ScheduleKind::FixedDelay: + case ScheduleKind::FixedRate: + if (spec.schedule.interval <= + std::chrono::milliseconds{0}) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidRule, + "Scheduler: fixed interval must be positive")); + } + return std::optional{std::nullopt}; + case ScheduleKind::Calendar: { + if (auto tz_ok = timezones.validate_timezone( + spec.schedule.calendar.timezone); + !tz_ok.has_value()) { + return Void::Result::fail(tz_ok.error()); + } + auto expr = CalendarExpression::parse( + spec.schedule.calendar.expression); + if (!expr.has_value()) { + return Void::Result::fail(expr.error()); + } + return std::optional{ + std::move(*expr)}; + } + } + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidRule, + "Scheduler: unknown schedule kind")); + } + + [[nodiscard]] std::size_t + pending_for_job_locked(std::string_view job_id, + std::uint64_t rev) const noexcept + { + std::size_t n = 0; + for (const auto& [oid, rec] : pending_cache) { + if (oid.job_id == job_id && oid.revision == rev && + rec.status == OccurrenceStatus::Pending) { + ++n; + } + } + return n; + } + + [[nodiscard]] std::size_t + active_for_job_locked(std::string_view job_id) const noexcept + { + auto it = active_per_job.find(job_id); + return it == active_per_job.end() ? 0U : it->second; + } + + [[nodiscard]] std::size_t + allowed_concurrency_for_job(const JobSpec& spec) const noexcept + { + switch (spec.overlap) { + case OverlapPolicy::Forbid: + case OverlapPolicy::QueueOne: + return 1U; + case OverlapPolicy::AllowBounded: + return std::max(1U, spec.max_concurrent); + } + return 1U; + } + + void push_pending_locked(const OccurrenceRecord& rec) + { + pending_cache[rec.id] = rec; + heap.push(HeapEntry{ + .due_monotonic_ns = rec.due_monotonic_ns, + .sequence = rec.id.sequence, + .id = rec.id, + }); + } + + Result materialize_all_due() + { + std::vector snapshot_jobs; + { + std::lock_guard lk{mu}; + if (closing) { + return 0U; + } + snapshot_jobs.reserve(jobs.size()); + for (const auto& [k, j] : jobs) { + (void)k; + if (!j.tombstoned) { + snapshot_jobs.push_back(j); + } + } + } + + const auto now_mono = monotonic_clock->now(); + const std::int64_t now_mono_ns = to_ns(now_mono); + const std::int64_t now_utc_ms = to_utc_ms(civil_clock->now()); + + std::size_t total_created = 0; + + for (auto& job : snapshot_jobs) { + std::vector batch_records; + std::int64_t next_cursor_utc = job.cursor_utc_ms; + std::int64_t next_cursor_mono = job.cursor_monotonic_ns; + bool next_cursor_init = job.cursor_initialized; + bool next_one_shot_done = job.one_shot_materialized; + std::uint64_t next_seq = job.next_sequence; + bool should_commit = false; + + auto make_occ = [&](std::int64_t due_ns, + std::int64_t intended_utc, + std::uint8_t fold) { + OccurrenceRecord rec{}; + rec.id = OccurrenceId{job.spec.id, job.revision, + next_seq++}; + rec.intended_utc_ms = intended_utc; + rec.due_monotonic_ns = due_ns; + rec.fold_index = fold; + rec.status = OccurrenceStatus::Pending; + rec.attempt = 0; + rec.handler_id = job.spec.handler_id; + rec.payload_schema = job.spec.payload_schema; + rec.payload = job.spec.payload; + return rec; + }; + + switch (job.spec.schedule.kind) { + case ScheduleKind::OneShot: { + if (job.one_shot_materialized) { + break; + } + std::int64_t due_ns = now_mono_ns; + std::int64_t intended_utc = now_utc_ms; + if (job.spec.schedule.due_monotonic.has_value()) { + due_ns = to_ns(*job.spec.schedule.due_monotonic); + intended_utc = + now_utc_ms + (due_ns - now_mono_ns) / 1000000LL; + } else { + intended_utc = job.spec.schedule.start_utc_ms; + due_ns = now_mono_ns + + (intended_utc - now_utc_ms) * 1000000LL; + } + if (due_ns <= now_mono_ns) { + batch_records.push_back( + make_occ(due_ns, intended_utc, 0)); + next_one_shot_done = true; + next_cursor_mono = due_ns; + next_cursor_utc = intended_utc; + next_cursor_init = true; + should_commit = true; + } + break; + } + + case ScheduleKind::FixedDelay: { + std::size_t live_for_job = 0; + { + std::lock_guard lk{mu}; + live_for_job = + pending_for_job_locked(job.spec.id, + job.revision) + + active_for_job_locked(job.spec.id); + } + if (live_for_job > 0U) { + break; + } + std::int64_t due_ns = now_mono_ns; + if (job.cursor_initialized) { + due_ns = job.cursor_monotonic_ns; + } else if (job.spec.schedule.due_monotonic + .has_value()) { + due_ns = to_ns(*job.spec.schedule.due_monotonic); + } + if (due_ns <= now_mono_ns) { + const std::int64_t intended_utc = + now_utc_ms + (due_ns - now_mono_ns) / 1000000LL; + batch_records.push_back( + make_occ(due_ns, intended_utc, 0)); + next_cursor_mono = due_ns; + next_cursor_utc = intended_utc; + next_cursor_init = true; + should_commit = true; + } + break; + } + + case ScheduleKind::FixedRate: { + const std::int64_t interval_ns = + std::chrono::duration_cast< + std::chrono::nanoseconds>( + job.spec.schedule.interval) + .count(); + std::int64_t first_due = now_mono_ns; + if (job.cursor_initialized) { + first_due = job.cursor_monotonic_ns + interval_ns; + } else if (job.spec.schedule.due_monotonic + .has_value()) { + first_due = + to_ns(*job.spec.schedule.due_monotonic); + } + if (first_due > now_mono_ns) { + break; + } + const std::int64_t missed = + (now_mono_ns - first_due) / interval_ns + 1LL; + if (job.spec.misfire == MisfirePolicy::Skip) { + next_cursor_mono = + first_due + (missed - 1LL) * interval_ns; + next_cursor_init = true; + should_commit = true; + } else if (job.spec.misfire == + MisfirePolicy::CoalesceLatest) { + const std::int64_t latest = + first_due + (missed - 1LL) * interval_ns; + const std::int64_t intended_utc = + now_utc_ms + + (latest - now_mono_ns) / 1000000LL; + batch_records.push_back( + make_occ(latest, intended_utc, 0)); + next_cursor_mono = latest; + next_cursor_utc = intended_utc; + next_cursor_init = true; + should_commit = true; + } else { + const std::size_t cap = std::min( + static_cast(missed), + limits.max_catch_up_per_job_per_pass); + for (std::size_t k = 0; k < cap; ++k) { + const std::int64_t due = + first_due + + static_cast(k) * + interval_ns; + const std::int64_t intended_utc = + now_utc_ms + + (due - now_mono_ns) / 1000000LL; + batch_records.push_back( + make_occ(due, intended_utc, 0)); + next_cursor_mono = due; + next_cursor_utc = intended_utc; + } + next_cursor_init = true; + should_commit = true; + } + break; + } + + case ScheduleKind::Calendar: { + std::optional expr{}; + { + std::lock_guard lk{mu}; + auto cit = parsed_calendars.find(job.spec.id); + if (cit != parsed_calendars.end()) { + expr = cit->second; + } + } + if (!expr.has_value()) { + auto parsed = CalendarExpression::parse( + job.spec.schedule.calendar.expression); + if (!parsed.has_value()) { + return Void::Result::fail(parsed.error()); + } + expr = *parsed; + } + const std::int64_t after_utc = + job.cursor_initialized ? job.cursor_utc_ms + : (now_utc_ms - 60000LL); + auto mat = expr->materialize_range( + job.spec.schedule.calendar, timezones, + after_utc, now_utc_ms, job.spec.misfire, + limits.max_catch_up_per_job_per_pass); + if (!mat.has_value()) { + return Void::Result::fail(mat.error()); + } + if (!mat->slots.empty() || + mat->next_cursor_utc_ms != job.cursor_utc_ms) { + for (const auto& s : mat->slots) { + const std::int64_t due_ns = + now_mono_ns + + (s.utc_ms - now_utc_ms) * 1000000LL; + batch_records.push_back( + make_occ(due_ns, s.utc_ms, s.fold_index)); + } + next_cursor_utc = mat->next_cursor_utc_ms; + next_cursor_init = true; + should_commit = true; + } + break; + } + } + + if (!should_commit) { + continue; + } + + // QueueOne overlap: if a job is currently running and + // already has a queued pending slot, retain only the latest + // slot (do not pile up unbounded pending records). + if (job.spec.overlap == OverlapPolicy::QueueOne && + batch_records.size() > 1U) { + OccurrenceRecord latest = + std::move(batch_records.back()); + batch_records.clear(); + batch_records.push_back(std::move(latest)); + } + if (job.spec.overlap == OverlapPolicy::QueueOne) { + std::lock_guard lk{mu}; + if (active_for_job_locked(job.spec.id) > 0U && + pending_for_job_locked(job.spec.id, job.revision) >= + 1U) { + batch_records.clear(); + } + } + + auto res = store->materialize_occurrences( + job.spec.id, job.revision, next_cursor_utc, + next_cursor_mono, next_cursor_init, next_one_shot_done, + next_seq, batch_records); + if (!res.has_value()) { + if (res.error().code().value == + static_cast( + SchedulerErrorCode::RetentionFull)) { + emit(ObservationKind::RetentionPause, 1); + // Pause materialization cleanly without advancing + // cursor or failing the entire tick. + continue; + } + if (res.error().code().value == + static_cast( + SchedulerErrorCode::Conflict)) { + continue; + } + return Void::Result::fail(res.error()); + } + + total_created += *res; + { + std::lock_guard lk{mu}; + auto jit = jobs.find(job.spec.id); + if (jit != jobs.end() && + jit->second.revision == job.revision) { + jit->second.cursor_utc_ms = next_cursor_utc; + jit->second.cursor_monotonic_ns = next_cursor_mono; + jit->second.cursor_initialized = next_cursor_init; + jit->second.one_shot_materialized = + next_one_shot_done; + jit->second.next_sequence = next_seq; + } + for (const auto& rec : batch_records) { + push_pending_locked(rec); + } + } + if (*res > 0U) { + emit(ObservationKind::Materialize, *res); + } + } + + return total_created; + } + + Result dispatch_one(Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, + "Scheduler::dispatch_one cancelled")); + } + if (Void::Async::is_deadline_expired(options, *monotonic_clock)) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, + "Scheduler::dispatch_one deadline expired")); + } + + const std::int64_t now_mono_ns = to_ns(monotonic_clock->now()); + + OccurrenceRecord candidate{}; + JobSpec job_spec{}; + HandlerFn handler{}; + std::shared_ptr exec_slot{}; + bool found = false; + + { + std::lock_guard lk{mu}; + if (closing) { + return false; + } + if (active.size() >= limits.max_active_handlers) { + return false; + } + + std::vector deferred; + while (!heap.empty()) { + HeapEntry top = heap.top(); + if (top.due_monotonic_ns > now_mono_ns) { + break; + } + heap.pop(); + + auto pit = pending_cache.find(top.id); + if (pit == pending_cache.end() || + pit->second.status != OccurrenceStatus::Pending) { + continue; + } + // Ignore stale heap entry superseded by retry re-push. + if (pit->second.due_monotonic_ns > now_mono_ns) { + deferred.push_back(HeapEntry{ + .due_monotonic_ns = + pit->second.due_monotonic_ns, + .sequence = top.sequence, + .id = top.id, + }); + continue; + } + + auto jit = jobs.find(top.id.job_id); + if (jit == jobs.end() || jit->second.tombstoned || + top.id.revision < + jit->second.invalidated_before_revision) { + pending_cache.erase(pit); + continue; + } + + const std::size_t running_for_job = + active_for_job_locked(top.id.job_id); + if (running_for_job >= + allowed_concurrency_for_job(jit->second.spec)) { + deferred.push_back(top); + continue; + } + + auto hit = handlers.find(pit->second.handler_id); + if (hit == handlers.end()) { + // Keep pending until handler is registered or + // explicitly fail? Defer so caller can register + // handler before running. + deferred.push_back(top); + continue; + } + + candidate = pit->second; + job_spec = jit->second.spec; + handler = hit->second; + pending_cache.erase(pit); + + exec_slot = std::make_shared(); + exec_slot->id = candidate.id; + exec_slot->worker_thread = std::this_thread::get_id(); + active.emplace(candidate.id, exec_slot); + active_per_job[candidate.id.job_id] += 1U; + found = true; + break; + } + for (auto& d : deferred) { + heap.push(std::move(d)); + } + } + + if (!found) { + return false; + } + + auto release_active = [&]() { + std::lock_guard lk{mu}; + active.erase(candidate.id); + auto it = active_per_job.find(candidate.id.job_id); + if (it != active_per_job.end()) { + if (it->second <= 1U) { + active_per_job.erase(it); + } else { + it->second -= 1U; + } + } + active_cv.notify_all(); + }; + + // Atomically claim Pending -> Running in store before running + // handler! + auto claimed = + store->claim_occurrence(candidate.id, candidate.attempt); + if (!claimed.has_value()) { + release_active(); + if (claimed.error().code().value == + static_cast( + SchedulerErrorCode::Cancelled) || + claimed.error().code().value == + static_cast( + SchedulerErrorCode::Conflict)) { + return false; + } + return Void::Result::fail(claimed.error()); + } + + const std::int64_t lag_ms = + std::max(0LL, (now_mono_ns - + claimed->due_monotonic_ns) / + 1000000LL); + emit(ObservationKind::Dispatch, 1, lag_ms); + + // Build merged stop token linking caller stop + execution stop. + std::stop_callback caller_fwd( + options.stop, [&] { exec_slot->stop_source.request_stop(); }); + Void::Async::OperationOptions handler_opts{}; + handler_opts.stop = exec_slot->stop_source.get_token(); + handler_opts.deadline = options.deadline; + + OccurrenceContext ctx{}; + ctx.id = claimed->id; + ctx.attempt = claimed->attempt; + ctx.payload_schema = claimed->payload_schema; + ctx.intended_utc_ms = claimed->intended_utc_ms; + ctx.fold_index = claimed->fold_index; + + // Invoke handler strictly OUTSIDE scheduler and store locks! + Result handler_res{}; + try { + handler_res = handler(ctx, claimed->payload, handler_opts); + } catch (...) { + handler_res = Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::HandlerFailed, + "Scheduler: handler threw an exception")); + } + + bool is_closing = false; + { + std::lock_guard lk{mu}; + is_closing = closing; + } + + if (handler_res.has_value()) { + const std::int64_t done_utc_ms = + to_utc_ms(civil_clock->now()); + std::optional fixed_delay_next{}; + if (job_spec.schedule.kind == ScheduleKind::FixedDelay) { + fixed_delay_next = + to_ns(monotonic_clock->now()) + + std::chrono::duration_cast< + std::chrono::nanoseconds>( + job_spec.schedule.interval) + .count(); + } + auto cr = store->complete_occurrence( + claimed->id, claimed->attempt, done_utc_ms, + fixed_delay_next); + if (cr.has_value() && fixed_delay_next.has_value()) { + std::lock_guard lk{mu}; + auto jit = jobs.find(claimed->id.job_id); + if (jit != jobs.end() && + jit->second.revision == claimed->id.revision) { + jit->second.cursor_monotonic_ns = *fixed_delay_next; + jit->second.cursor_initialized = true; + } + } + release_active(); + if (!cr.has_value()) { + return Void::Result::fail(cr.error()); + } + emit(ObservationKind::Complete, 1); + return true; + } + + // Handler failed or stopped. + if (is_closing && + (exec_slot->stop_source.stop_requested() || + handler_res.error().kind() == + Void::Result::ErrorKind::cancelled)) { + // Host shutdown: preserve Pending intent without consuming + // a retry attempt! + auto rq = + store->requeue_on_shutdown(claimed->id, claimed->attempt); + release_active(); + if (!rq.has_value()) { + return Void::Result::fail(rq.error()); + } + return true; + } + + const bool exhausted = + claimed->attempt >= job_spec.retry.max_attempts; + const std::int64_t retry_delay_ms = + exhausted ? 0LL + : compute_retry_delay_ms( + job_spec.retry, claimed->attempt, rng); + const std::int64_t next_mono_ns = + to_ns(monotonic_clock->now()) + retry_delay_ms * 1000000LL; + const std::int64_t next_utc_ms = + to_utc_ms(civil_clock->now()) + retry_delay_ms; + + auto fr = store->fail_occurrence( + claimed->id, claimed->attempt, next_mono_ns, next_utc_ms, + exhausted, + std::string{ + Void::Result::to_string(handler_res.error().kind())}); + if (fr.has_value() && !exhausted) { + OccurrenceRecord retry_rec = *claimed; + retry_rec.status = OccurrenceStatus::Pending; + retry_rec.due_monotonic_ns = next_mono_ns; + retry_rec.intended_utc_ms = next_utc_ms; + std::lock_guard lk{mu}; + push_pending_locked(retry_rec); + } + release_active(); + if (!fr.has_value()) { + return Void::Result::fail(fr.error()); + } + emit(exhausted ? ObservationKind::DeadLetter + : ObservationKind::Retry, + 1); + return true; + } + }; + + Scheduler::Scheduler(std::shared_ptr state) noexcept + : m_state(std::move(state)) + { + } + + Scheduler::Scheduler(Scheduler&&) noexcept = default; + Scheduler& Scheduler::operator=(Scheduler&&) noexcept = default; + + Scheduler::~Scheduler() noexcept + { + if (!m_state) { + return; + } + bool release = false; + { + std::lock_guard lk{m_state->mu}; + m_state->closing = true; + for (auto& [id, exec] : m_state->active) { + (void)id; + if (exec) { + exec->stop_source.request_stop(); + } + } + release = !m_state->closed_cleanly && m_state->active.empty(); + if (release) { + m_state->closed_cleanly = true; + } + } + if (release && m_state->store) { + (void)m_state->store->release_ownership(); + } + } + + Result Scheduler::create(SchedulerOptions options) + { + auto st = std::make_shared(); + st->owner_id = + options.owner_id.empty() ? "scheduler-default" : options.owner_id; + st->limits = options.limits; + st->store = options.store ? std::move(options.store) + : make_in_memory_job_store(st->limits); + st->monotonic_clock = + options.monotonic_clock != nullptr + ? options.monotonic_clock + : &Void::Time::SystemMonotonicClock::instance(); + st->civil_clock = options.civil_clock != nullptr + ? options.civil_clock + : &Void::Time::SystemCivilClock::instance(); + st->timezones = std::move(options.timezones); + st->observer = std::move(options.observer); + if (options.rng) { + st->rng = std::move(options.rng); + } else { + auto prng = std::make_shared(0x9E3779B97F4A7C15ULL); + auto prng_mu = std::make_shared(); + st->rng = [prng, prng_mu]() -> std::uint64_t { + std::lock_guard lk{*prng_mu}; + return (*prng)(); + }; + } + + if (auto own = st->store->acquire_ownership(st->owner_id); + !own.has_value()) { + return Void::Result::fail(own.error()); + } + + auto rec_count = st->store->recover_running_occurrences(); + if (!rec_count.has_value()) { + (void)st->store->release_ownership(); + return Void::Result::fail(rec_count.error()); + } + if (*rec_count > 0U) { + st->emit(ObservationKind::Recover, *rec_count); + } + + auto jobs = st->store->load_jobs(); + if (!jobs.has_value()) { + (void)st->store->release_ownership(); + return Void::Result::fail(jobs.error()); + } + for (auto& j : *jobs) { + if (j.spec.schedule.kind == ScheduleKind::Calendar) { + if (auto expr = CalendarExpression::parse( + j.spec.schedule.calendar.expression); + expr.has_value()) { + st->parsed_calendars.emplace(j.spec.id, std::move(*expr)); + } + } + st->jobs.emplace(j.spec.id, std::move(j)); + } + + auto occs = st->store->load_occurrences(); + if (!occs.has_value()) { + (void)st->store->release_ownership(); + return Void::Result::fail(occs.error()); + } + const std::int64_t now_mono_ns = to_ns(st->monotonic_clock->now()); + const std::int64_t now_utc_ms = to_utc_ms(st->civil_clock->now()); + for (auto& o : *occs) { + if (o.status == OccurrenceStatus::Pending) { + // Re-anchor recovered occurrences into current monotonic domain + // based on their persisted intended UTC instant. + o.due_monotonic_ns = + now_mono_ns + (o.intended_utc_ms - now_utc_ms) * 1000000LL; + st->push_pending_locked(o); + } + } + + return Scheduler{std::move(st)}; + } + + Result Scheduler::register_handler(std::string handler_id, + HandlerFn handler) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + if (!is_valid_id(handler_id) || !handler) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "Scheduler::register_handler requires valid id and function")); + } + std::lock_guard lk{m_state->mu}; + m_state->handlers[std::move(handler_id)] = std::move(handler); + return {}; + } + + Result + Scheduler::add_job(JobSpec spec, Void::Async::OperationOptions options) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + if (options.stop.stop_requested()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, "Scheduler::add_job cancelled")); + } + auto parsed_cal = m_state->validate_job_spec(spec); + if (!parsed_cal.has_value()) { + return Void::Result::fail(parsed_cal.error()); + } + + JobRecord rec{}; + rec.spec = std::move(spec); + rec.revision = 1; + rec.invalidated_before_revision = 1; + rec.tombstoned = false; + rec.next_sequence = 1; + if (rec.spec.schedule.kind == ScheduleKind::Calendar) { + rec.cursor_utc_ms = rec.spec.schedule.start_utc_ms != 0 + ? rec.spec.schedule.start_utc_ms + : to_utc_ms(m_state->civil_clock->now()); + rec.cursor_initialized = true; + } + + { + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler is closing")); + } + } + + if (auto pr = m_state->store->put_job(rec); !pr.has_value()) { + return Void::Result::fail(pr.error()); + } + + { + std::lock_guard lk{m_state->mu}; + if (parsed_cal->has_value()) { + m_state->parsed_calendars[rec.spec.id] = **parsed_cal; + } + m_state->jobs[rec.spec.id] = rec; + } + return rec.revision; + } + + Result + Scheduler::update_job(JobSpec spec, + Void::Async::OperationOptions options) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + if (options.stop.stop_requested()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, + "Scheduler::update_job cancelled")); + } + // Validate completely BEFORE touching existing policy! + auto parsed_cal = m_state->validate_job_spec(spec); + if (!parsed_cal.has_value()) { + return Void::Result::fail(parsed_cal.error()); + } + + JobRecord next{}; + std::uint64_t expected_rev = 0; + { + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler is closing")); + } + auto it = m_state->jobs.find(spec.id); + if (it == m_state->jobs.end() || it->second.tombstoned) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "Scheduler::update_job job not found: " + spec.id)); + } + expected_rev = it->second.revision; + next = it->second; + next.spec = std::move(spec); + next.revision = expected_rev + 1U; + // Atomically invalidate unstarted occurrences from older revisions. + next.invalidated_before_revision = next.revision; + next.one_shot_materialized = false; + if (next.spec.schedule.kind == ScheduleKind::Calendar && + !next.cursor_initialized) { + next.cursor_utc_ms = + next.spec.schedule.start_utc_ms != 0 + ? next.spec.schedule.start_utc_ms + : to_utc_ms(m_state->civil_clock->now()); + next.cursor_initialized = true; + } + } + + if (auto ur = m_state->store->update_job(next, expected_rev); + !ur.has_value()) { + return Void::Result::fail(ur.error()); + } + + { + std::lock_guard lk{m_state->mu}; + if (parsed_cal->has_value()) { + m_state->parsed_calendars[next.spec.id] = **parsed_cal; + } else { + m_state->parsed_calendars.erase(next.spec.id); + } + m_state->jobs[next.spec.id] = next; + } + return next.revision; + } + + Result Scheduler::remove_job(std::string_view job_id, + Void::Async::OperationOptions options) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + if (options.stop.stop_requested()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, + "Scheduler::remove_job cancelled")); + } + + if (auto tr = m_state->store->tombstone_job(job_id); !tr.has_value()) { + return tr; + } + + std::lock_guard lk{m_state->mu}; + auto jit = m_state->jobs.find(job_id); + if (jit != m_state->jobs.end()) { + jit->second.tombstoned = true; + } + for (auto& [oid, exec] : m_state->active) { + if (oid.job_id == job_id && exec) { + exec->stop_source.request_stop(); + } + } + return {}; + } + + Result + Scheduler::tick(Void::Async::OperationOptions options) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + if (auto mr = m_state->materialize_all_due(); !mr.has_value()) { + return Void::Result::fail(mr.error()); + } + + std::size_t executed = 0; + const std::size_t max_dispatches = m_state->limits.max_ready_dispatches; + while (executed < max_dispatches) { + auto d = m_state->dispatch_one(options); + if (!d.has_value()) { + return Void::Result::fail(d.error()); + } + if (!*d) { + break; + } + ++executed; + } + return executed; + } + + Result Scheduler::dispatch_one(Void::Async::OperationOptions options) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + return m_state->dispatch_one(options); + } + + Result + Scheduler::close_and_join(Void::Async::OperationOptions options) + { + if (!m_state) { + return ShutdownReport{.complete = true}; + } + + { + std::lock_guard lk{m_state->mu}; + for (const auto& [oid, exec] : m_state->active) { + (void)oid; + if (exec && + exec->worker_thread == std::this_thread::get_id()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::SelfJoin, + "Scheduler::close_and_join cannot be called from an " + "active handler thread")); + } + } + m_state->closing = true; + for (auto& [oid, exec] : m_state->active) { + (void)oid; + if (exec) { + exec->stop_source.request_stop(); + } + } + } + + std::unique_lock lk{m_state->mu}; + while (!m_state->active.empty()) { + if (options.deadline.has_value()) { + const auto rem = Void::Time::remaining_until( + *m_state->monotonic_clock, *options.deadline); + if (rem <= std::chrono::nanoseconds{0}) { + ShutdownReport report{}; + report.complete = false; + for (const auto& [oid, _] : m_state->active) { + report.live_occurrences.push_back(oid); + } + return report; + } + const auto slice = + std::min(rem, std::chrono::duration_cast< + std::chrono::nanoseconds>( + std::chrono::milliseconds{5})); + m_state->active_cv.wait_for(lk, slice, [this] { + return m_state->active.empty(); + }); + } else { + m_state->active_cv.wait( + lk, [this] { return m_state->active.empty(); }); + } + } + + if (!m_state->closed_cleanly) { + m_state->closed_cleanly = true; + lk.unlock(); + if (auto rel = m_state->store->release_ownership(); + !rel.has_value()) { + return Void::Result::fail(rel.error()); + } + } + return ShutdownReport{.complete = true}; + } + + Result> Scheduler::list_jobs() const + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + return m_state->store->load_jobs(); + } + + Result> Scheduler::list_occurrences() const + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + return m_state->store->load_occurrences(); + } + + Result Scheduler::acknowledge_dead(const OccurrenceId& id) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + return m_state->store->acknowledge_dead(id); + } + + Result Scheduler::prune_completed(std::size_t max_count) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + const std::int64_t cutoff = + to_utc_ms(m_state->civil_clock->now()) - + m_state->limits.completed_retention.count(); + return m_state->store->prune_completed(cutoff, max_count); + } + + Result Scheduler::reclaim_invalidated(std::size_t max_count) + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + return m_state->store->reclaim_invalidated(max_count); + } + + Result Scheduler::stats() const + { + if (!m_state) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Closed, "Scheduler moved-from")); + } + return m_state->store->stats(); + } + +} // namespace Void::Scheduler diff --git a/src/Scheduler/module.cmake b/src/Scheduler/module.cmake new file mode 100644 index 0000000..1caadd5 --- /dev/null +++ b/src/Scheduler/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Scheduler + INTERNAL_DEPS Core Functional Time Async +) diff --git a/src/SchedulerStorage/StorageJobStore.cpp b/src/SchedulerStorage/StorageJobStore.cpp new file mode 100644 index 0000000..0d4cafb --- /dev/null +++ b/src/SchedulerStorage/StorageJobStore.cpp @@ -0,0 +1,1078 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::SchedulerStorage +{ + using namespace Void::Scheduler; + using Void::Scheduler::Result; + + namespace + { + constexpr std::uint32_t kSchemaVersion = 1U; + + void append_u8(std::string& out, std::uint8_t v) + { + out.push_back(static_cast(v)); + } + + void append_u32(std::string& out, std::uint32_t v) + { + out.push_back(static_cast((v >> 24U) & 0xFFU)); + out.push_back(static_cast((v >> 16U) & 0xFFU)); + out.push_back(static_cast((v >> 8U) & 0xFFU)); + out.push_back(static_cast(v & 0xFFU)); + } + + void append_u64(std::string& out, std::uint64_t v) + { + for (int shift = 56; shift >= 0; shift -= 8) { + out.push_back(static_cast((v >> shift) & 0xFFU)); + } + } + + void append_i64(std::string& out, std::int64_t v) + { + append_u64(out, static_cast(v)); + } + + void append_str(std::string& out, std::string_view s) + { + append_u32(out, static_cast(s.size())); + out.append(s); + } + + void append_bytes(std::string& out, const std::vector& b) + { + append_u32(out, static_cast(b.size())); + if (!b.empty()) { + out.append(reinterpret_cast(b.data()), b.size()); + } + } + + [[nodiscard]] bool read_u8(std::string_view& in, + std::uint8_t& out) noexcept + { + if (in.empty()) return false; + out = static_cast(static_cast(in[0])); + in.remove_prefix(1U); + return true; + } + + [[nodiscard]] bool read_u32(std::string_view& in, + std::uint32_t& out) noexcept + { + if (in.size() < 4U) return false; + out = (static_cast(static_cast(in[0])) + << 24U) | + (static_cast(static_cast(in[1])) + << 16U) | + (static_cast(static_cast(in[2])) + << 8U) | + static_cast(static_cast(in[3])); + in.remove_prefix(4U); + return true; + } + + [[nodiscard]] bool read_u64(std::string_view& in, + std::uint64_t& out) noexcept + { + if (in.size() < 8U) return false; + std::uint64_t v = 0; + for (std::size_t i = 0; i < 8U; ++i) { + v = (v << 8U) | static_cast( + static_cast(in[i])); + } + in.remove_prefix(8U); + out = v; + return true; + } + + [[nodiscard]] bool read_i64(std::string_view& in, + std::int64_t& out) noexcept + { + std::uint64_t u = 0; + if (!read_u64(in, u)) return false; + out = static_cast(u); + return true; + } + + [[nodiscard]] bool read_str(std::string_view& in, std::string& out) + { + std::uint32_t len = 0; + if (!read_u32(in, len) || len > in.size()) return false; + out.assign(in.data(), len); + in.remove_prefix(len); + return true; + } + + [[nodiscard]] bool read_bytes(std::string_view& in, + std::vector& out) + { + std::uint32_t len = 0; + if (!read_u32(in, len) || len > in.size()) return false; + out.resize(len); + if (len > 0U) { + std::memcpy(out.data(), in.data(), len); + } + in.remove_prefix(len); + return true; + } + + [[nodiscard]] std::string encode_job(const JobRecord& j) + { + std::string out; + append_u32(out, kSchemaVersion); + append_u64(out, j.revision); + append_u64(out, j.invalidated_before_revision); + append_u8(out, j.tombstoned ? 1U : 0U); + append_i64(out, j.cursor_utc_ms); + append_i64(out, j.cursor_monotonic_ns); + append_u8(out, j.cursor_initialized ? 1U : 0U); + append_u8(out, j.one_shot_materialized ? 1U : 0U); + append_u64(out, j.next_sequence); + + append_str(out, j.spec.id); + append_str(out, j.spec.handler_id); + append_u32(out, j.spec.payload_schema); + append_bytes(out, j.spec.payload); + append_u8(out, static_cast(j.spec.misfire)); + append_u8(out, static_cast(j.spec.overlap)); + append_u32(out, j.spec.max_concurrent); + append_u32(out, j.spec.retry.max_attempts); + append_i64(out, j.spec.retry.base_delay.count()); + append_i64(out, j.spec.retry.max_delay.count()); + append_u32(out, j.spec.retry.multiplier); + + append_u8(out, static_cast(j.spec.schedule.kind)); + append_i64(out, j.spec.schedule.start_utc_ms); + append_u8(out, j.spec.schedule.due_monotonic.has_value() ? 1U : 0U); + append_i64(out, j.spec.schedule.due_monotonic.has_value() + ? to_ns(*j.spec.schedule.due_monotonic) + : 0LL); + append_i64(out, j.spec.schedule.interval.count()); + append_str(out, j.spec.schedule.calendar.expression); + append_str(out, j.spec.schedule.calendar.timezone); + append_u32(out, j.spec.schedule.calendar.tz_data_version); + append_u8(out, + static_cast( + j.spec.schedule.calendar.gap_policy)); + append_u8(out, + static_cast( + j.spec.schedule.calendar.fold_policy)); + return out; + } + + [[nodiscard]] Result decode_job(std::string_view raw) + { + std::uint32_t ver = 0; + if (!read_u32(raw, ver) || ver != kSchemaVersion) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::CorruptRecord, + "SchedulerStorage: unsupported or corrupt job record " + "version")); + } + JobRecord j{}; + j.format_version = ver; + std::uint8_t tomb = 0, cinit = 0, osdone = 0, misf = 0, ovl = 0, + skind = 0, has_mono = 0, gap = 0, fold = 0; + std::int64_t rbase = 0, rmax = 0, mono_ns = 0, iv_ms = 0; + if (!read_u64(raw, j.revision) || + !read_u64(raw, j.invalidated_before_revision) || + !read_u8(raw, tomb) || !read_i64(raw, j.cursor_utc_ms) || + !read_i64(raw, j.cursor_monotonic_ns) || !read_u8(raw, cinit) || + !read_u8(raw, osdone) || !read_u64(raw, j.next_sequence) || + !read_str(raw, j.spec.id) || !read_str(raw, j.spec.handler_id) || + !read_u32(raw, j.spec.payload_schema) || + !read_bytes(raw, j.spec.payload) || !read_u8(raw, misf) || + !read_u8(raw, ovl) || !read_u32(raw, j.spec.max_concurrent) || + !read_u32(raw, j.spec.retry.max_attempts) || + !read_i64(raw, rbase) || !read_i64(raw, rmax) || + !read_u32(raw, j.spec.retry.multiplier) || + !read_u8(raw, skind) || + !read_i64(raw, j.spec.schedule.start_utc_ms) || + !read_u8(raw, has_mono) || !read_i64(raw, mono_ns) || + !read_i64(raw, iv_ms) || + !read_str(raw, j.spec.schedule.calendar.expression) || + !read_str(raw, j.spec.schedule.calendar.timezone) || + !read_u32(raw, j.spec.schedule.calendar.tz_data_version) || + !read_u8(raw, gap) || !read_u8(raw, fold) || !raw.empty()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::CorruptRecord, + "SchedulerStorage: corrupt job record payload")); + } + j.tombstoned = (tomb != 0U); + j.cursor_initialized = (cinit != 0U); + j.one_shot_materialized = (osdone != 0U); + j.spec.misfire = static_cast(misf); + j.spec.overlap = static_cast(ovl); + j.spec.retry.base_delay = std::chrono::milliseconds{rbase}; + j.spec.retry.max_delay = std::chrono::milliseconds{rmax}; + j.spec.schedule.kind = static_cast(skind); + if (has_mono != 0U) { + j.spec.schedule.due_monotonic = + Void::Time::MonotonicClock::time_point{ + std::chrono::duration_cast< + Void::Time::MonotonicClock::time_point::duration>( + std::chrono::nanoseconds{mono_ns})}; + } + j.spec.schedule.interval = std::chrono::milliseconds{iv_ms}; + j.spec.schedule.calendar.gap_policy = static_cast(gap); + j.spec.schedule.calendar.fold_policy = + static_cast(fold); + return j; + } + + [[nodiscard]] std::string encode_occ(const OccurrenceRecord& o) + { + std::string out; + append_u32(out, kSchemaVersion); + append_str(out, o.id.job_id); + append_u64(out, o.id.revision); + append_u64(out, o.id.sequence); + append_i64(out, o.intended_utc_ms); + append_i64(out, o.due_monotonic_ns); + append_u8(out, o.fold_index); + append_u8(out, static_cast(o.status)); + append_u32(out, o.attempt); + append_str(out, o.handler_id); + append_u32(out, o.payload_schema); + append_bytes(out, o.payload); + append_str(out, o.diagnostic_category); + append_i64(out, o.completed_utc_ms); + append_u8(out, o.dead_acknowledged ? 1U : 0U); + return out; + } + + [[nodiscard]] Result decode_occ(std::string_view raw) + { + std::uint32_t ver = 0; + if (!read_u32(raw, ver) || ver != kSchemaVersion) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::CorruptRecord, + "SchedulerStorage: unsupported or corrupt occurrence " + "version")); + } + OccurrenceRecord o{}; + o.format_version = ver; + std::uint8_t st = 0, dack = 0; + if (!read_str(raw, o.id.job_id) || !read_u64(raw, o.id.revision) || + !read_u64(raw, o.id.sequence) || + !read_i64(raw, o.intended_utc_ms) || + !read_i64(raw, o.due_monotonic_ns) || + !read_u8(raw, o.fold_index) || !read_u8(raw, st) || + !read_u32(raw, o.attempt) || !read_str(raw, o.handler_id) || + !read_u32(raw, o.payload_schema) || + !read_bytes(raw, o.payload) || + !read_str(raw, o.diagnostic_category) || + !read_i64(raw, o.completed_utc_ms) || !read_u8(raw, dack) || + !raw.empty()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::CorruptRecord, + "SchedulerStorage: corrupt occurrence record payload")); + } + if (st > static_cast(OccurrenceStatus::Cancelled)) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::CorruptRecord, + "SchedulerStorage: invalid occurrence status byte")); + } + o.status = static_cast(st); + o.dead_acknowledged = (dack != 0U); + return o; + } + + [[nodiscard]] std::string make_owner_key(const std::string& pfx) + { + return pfx + "owner"; + } + + [[nodiscard]] std::string make_job_key(const std::string& pfx, + std::string_view job_id) + { + return pfx + "job:" + std::string{job_id}; + } + + [[nodiscard]] std::string make_occ_key(const std::string& pfx, + const OccurrenceId& id) + { + return std::format("{}occ:{}\x1F{:020}\x1F{:020}", pfx, id.job_id, + id.revision, id.sequence); + } + + [[nodiscard]] std::string make_slot_key(const std::string& pfx, + std::string_view job_id, + std::uint64_t rev, + std::int64_t utc_ms, + std::uint8_t fold) + { + const std::uint64_t biased = + static_cast(utc_ms) ^ + (1ULL << 63U); // order-preserving signed->unsigned bias + return std::format("{}slot:{}\x1F{:020}\x1F{:020}\x1F{}", pfx, + job_id, rev, biased, static_cast(fold)); + } + + [[nodiscard]] std::size_t + estimate_batch_bytes(const Void::Storage::Batch& batch) noexcept + { + std::size_t total = 0; + for (const auto& m : batch.mutations()) { + total += m.key.size() + m.value.size() + 32U; + } + for (const auto& p : batch.preconditions()) { + total += p.key.size() + p.expected_value.size() + 32U; + } + return total; + } + + [[nodiscard]] Error + map_write_failure(const Void::Storage::WriteFailure& wf, + SchedulerErrorCode conflict_code = + SchedulerErrorCode::Conflict) + { + if (wf.outcome == Void::Storage::Outcome::Unknown) { + return make_scheduler_error( + SchedulerErrorCode::UnknownOutcome, + "SchedulerStorage: durable write outcome is unknown: " + + wf.cause.error.message()); + } + if (wf.cause.code == Void::Storage::StorageErrorCode::conflict) { + return make_scheduler_error( + conflict_code, + "SchedulerStorage: conditional conflict: " + + wf.cause.error.message()); + } + return make_scheduler_error( + SchedulerErrorCode::PersistenceError, + "SchedulerStorage: durable write failed: " + + wf.cause.error.message()); + } + + [[nodiscard]] Result> + scan_prefix_all(const Void::Storage::Engine& engine, + const Void::Storage::Snapshot& snap, + std::string_view prefix) + { + // Note: Engine::scan takes Snapshot by value, so caller opens a + // fresh snapshot when needed or uses engine.scan. + (void)snap; + auto s = const_cast(engine).snapshot(); + if (!s.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, s.error().message())); + } + auto cur = engine.scan(std::move(*s), + Void::Storage::ScanBounds::prefix(prefix)); + if (!cur.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, + cur.error().message())); + } + std::vector entries; + for (;;) { + auto page = cur->next_page(); + if (!page.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, + page.error().message())); + } + for (auto& e : page->entries) { + entries.push_back(std::move(e)); + } + if (!page->has_more) { + break; + } + } + return entries; + } + } // namespace + + StorageJobStore::StorageJobStore(Void::Storage::Engine& engine, + StorageJobStoreOptions options) + : m_engine(&engine), m_options(std::move(options)) + { + } + + Result StorageJobStore::acquire_ownership(std::string_view owner_id) + { + if (m_engine == nullptr) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "StorageJobStore: null Storage::Engine")); + } + const std::string key = make_owner_key(m_options.key_prefix); + Void::Storage::Batch batch{}; + if (!m_options.recover_stale_owner) { + batch.require_absent(key); + } + batch.put(key, owner_id); + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure( + wr.error(), SchedulerErrorCode::OwnershipLocked)); + } + m_owner_id = std::string{owner_id}; + return {}; + } + + Result StorageJobStore::release_ownership() + { + if (m_engine == nullptr || m_owner_id.empty()) { + return {}; + } + const std::string key = make_owner_key(m_options.key_prefix); + Void::Storage::Batch batch{}; + batch.require_value(key, m_owner_id); + batch.erase(key); + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + m_owner_id.clear(); + if (!wr.has_value()) { + if (wr.error().cause.code == + Void::Storage::StorageErrorCode::conflict) { + return {}; + } + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result StorageJobStore::put_job(const JobRecord& job) + { + auto st = stats(); + if (!st.has_value()) return Void::Result::fail(st.error()); + if (st->jobs >= m_options.limits.max_jobs) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Overloaded, + "StorageJobStore: max_jobs limit reached")); + } + if (st->retention_saturated) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::RetentionFull, + "StorageJobStore: occurrence retention cap saturated")); + } + + const std::string key = make_job_key(m_options.key_prefix, job.spec.id); + const std::string val = encode_job(job); + Void::Storage::Batch batch{}; + batch.require_absent(key); + batch.put(key, val); + if (estimate_batch_bytes(batch) > + m_options.limits.max_durable_batch_bytes) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "StorageJobStore: batch exceeds max_durable_batch_bytes")); + } + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result StorageJobStore::update_job(const JobRecord& updated, + std::uint64_t expected_revision) + { + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string key = + make_job_key(m_options.key_prefix, updated.spec.id); + auto cur = m_engine->get(*snap, key); + if (!cur.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "StorageJobStore: job not found: " + updated.spec.id)); + } + auto decoded = decode_job(cur->as_string_view()); + if (!decoded.has_value()) return Void::Result::fail(decoded.error()); + if (decoded->tombstoned) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, "StorageJobStore: job tombstoned")); + } + if (decoded->revision != expected_revision) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "StorageJobStore: job revision mismatch on update")); + } + + Void::Storage::Batch batch{}; + batch.require_version(key, cur->version); + batch.put(key, encode_job(updated)); + if (estimate_batch_bytes(batch) > + m_options.limits.max_durable_batch_bytes) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "StorageJobStore: update batch exceeds 1 MiB cap")); + } + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result StorageJobStore::tombstone_job(std::string_view job_id) + { + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string key = make_job_key(m_options.key_prefix, job_id); + auto cur = m_engine->get(*snap, key); + if (!cur.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, "StorageJobStore: job not found")); + } + auto decoded = decode_job(cur->as_string_view()); + if (!decoded.has_value()) return Void::Result::fail(decoded.error()); + decoded->tombstoned = true; + + Void::Storage::Batch batch{}; + batch.require_version(key, cur->version); + batch.put(key, encode_job(*decoded)); + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result> StorageJobStore::load_jobs() const + { + Void::Storage::Snapshot dummy{}; + auto entries = + scan_prefix_all(*m_engine, dummy, m_options.key_prefix + "job:"); + if (!entries.has_value()) return Void::Result::fail(entries.error()); + std::vector out; + out.reserve(entries->size()); + for (const auto& e : *entries) { + auto j = decode_job(Void::Storage::to_string_view(e.value)); + if (!j.has_value()) return Void::Result::fail(j.error()); + out.push_back(std::move(*j)); + } + return out; + } + + Result> + StorageJobStore::load_occurrences() const + { + Void::Storage::Snapshot dummy{}; + auto entries = + scan_prefix_all(*m_engine, dummy, m_options.key_prefix + "occ:"); + if (!entries.has_value()) return Void::Result::fail(entries.error()); + std::vector out; + out.reserve(entries->size()); + for (const auto& e : *entries) { + auto o = decode_occ(Void::Storage::to_string_view(e.value)); + if (!o.has_value()) return Void::Result::fail(o.error()); + out.push_back(std::move(*o)); + } + return out; + } + + Result StorageJobStore::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& records) + { + auto st = stats(); + if (!st.has_value()) return Void::Result::fail(st.error()); + + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string job_key = make_job_key(m_options.key_prefix, job_id); + auto cur = m_engine->get(*snap, job_key); + if (!cur.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, "StorageJobStore: job missing")); + } + auto job = decode_job(cur->as_string_view()); + if (!job.has_value()) return Void::Result::fail(job.error()); + if (job->tombstoned || job->revision != expected_revision) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "StorageJobStore: job tombstoned or revision changed")); + } + + // Dedup calendar slots against persisted unique slot index BEFORE + // enforcing retention cap and advancing cursor! + std::vector filtered; + filtered.reserve(records.size()); + for (const auto& rec : records) { + if (job->spec.schedule.kind == ScheduleKind::Calendar) { + const std::string skey = make_slot_key( + m_options.key_prefix, rec.id.job_id, rec.id.revision, + rec.intended_utc_ms, rec.fold_index); + if (m_engine->get(*snap, skey).has_value()) { + continue; + } + } + const std::string okey = make_occ_key(m_options.key_prefix, rec.id); + if (m_engine->get(*snap, okey).has_value()) { + continue; + } + filtered.push_back(&rec); + } + + if (st->total_retained + filtered.size() > + m_options.limits.max_retained_occurrences) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::RetentionFull, + "StorageJobStore: occurrence retention cap reached; pausing " + "materialization without advancing cursor")); + } + + job->cursor_utc_ms = new_cursor_utc_ms; + job->cursor_monotonic_ns = new_cursor_monotonic_ns; + job->cursor_initialized = cursor_initialized; + job->one_shot_materialized = one_shot_materialized; + job->next_sequence = next_sequence; + + Void::Storage::Batch batch{}; + batch.require_version(job_key, cur->version); + batch.put(job_key, encode_job(*job)); + + for (const auto* rec : filtered) { + const std::string okey = + make_occ_key(m_options.key_prefix, rec->id); + batch.require_absent(okey); + batch.put(okey, encode_occ(*rec)); + if (job->spec.schedule.kind == ScheduleKind::Calendar) { + const std::string skey = make_slot_key( + m_options.key_prefix, rec->id.job_id, rec->id.revision, + rec->intended_utc_ms, rec->fold_index); + batch.require_absent(skey); + batch.put(skey, rec->id.to_idempotency_key()); + } + } + + if (estimate_batch_bytes(batch) > + m_options.limits.max_durable_batch_bytes) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Overloaded, + "StorageJobStore: materialization batch exceeds 1 MiB cap")); + } + + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return filtered.size(); + } + + Result + StorageJobStore::claim_occurrence(const OccurrenceId& id, + std::uint32_t expected_attempt) + { + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string job_key = + make_job_key(m_options.key_prefix, id.job_id); + const std::string occ_key = make_occ_key(m_options.key_prefix, id); + + auto jval = m_engine->get(*snap, job_key); + if (!jval.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, "StorageJobStore: job missing")); + } + auto job = decode_job(jval->as_string_view()); + if (!job.has_value()) return Void::Result::fail(job.error()); + if (job->tombstoned || id.revision < job->invalidated_before_revision) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Cancelled, + "StorageJobStore: occurrence cancelled by tombstone or " + "revision invalidation watermark")); + } + + auto oval = m_engine->get(*snap, occ_key); + if (!oval.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "StorageJobStore: occurrence missing")); + } + auto occ = decode_occ(oval->as_string_view()); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + if (occ->status != OccurrenceStatus::Pending || + occ->attempt != expected_attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "StorageJobStore: occurrence state changed before claim")); + } + + occ->status = OccurrenceStatus::Running; + occ->attempt += 1U; + + // Atomically pin BOTH job watermark version AND occurrence version so + // an edit cannot race a stale claim! + Void::Storage::Batch batch{}; + batch.require_version(job_key, jval->version); + batch.require_version(occ_key, oval->version); + batch.put(occ_key, encode_occ(*occ)); + + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return *occ; + } + + Result StorageJobStore::complete_occurrence( + const OccurrenceId& id, std::uint32_t attempt, + std::int64_t completed_utc_ms, + std::optional fixed_delay_next_monotonic_ns) + { + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string occ_key = make_occ_key(m_options.key_prefix, id); + auto oval = m_engine->get(*snap, occ_key); + if (!oval.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "StorageJobStore: occurrence missing on complete")); + } + auto occ = decode_occ(oval->as_string_view()); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + if (occ->status != OccurrenceStatus::Running || + occ->attempt != attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "StorageJobStore: stale attempt on complete")); + } + + occ->status = OccurrenceStatus::Completed; + occ->completed_utc_ms = completed_utc_ms; + + Void::Storage::Batch batch{}; + batch.require_version(occ_key, oval->version); + batch.put(occ_key, encode_occ(*occ)); + + if (fixed_delay_next_monotonic_ns.has_value()) { + const std::string job_key = + make_job_key(m_options.key_prefix, id.job_id); + if (auto jval = m_engine->get(*snap, job_key); jval.has_value()) { + if (auto job = decode_job(jval->as_string_view()); + job.has_value() && !job->tombstoned && + job->revision == id.revision) { + job->cursor_monotonic_ns = *fixed_delay_next_monotonic_ns; + job->cursor_initialized = true; + batch.require_version(job_key, jval->version); + batch.put(job_key, encode_job(*job)); + } + } + } + + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result StorageJobStore::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) + { + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string occ_key = make_occ_key(m_options.key_prefix, id); + auto oval = m_engine->get(*snap, occ_key); + if (!oval.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "StorageJobStore: occurrence missing on fail")); + } + auto occ = decode_occ(oval->as_string_view()); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + if (occ->status != OccurrenceStatus::Running || + occ->attempt != attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "StorageJobStore: stale attempt on fail")); + } + + occ->diagnostic_category = std::move(diagnostic_category); + if (mark_dead) { + occ->status = OccurrenceStatus::Dead; + } else { + occ->status = OccurrenceStatus::Pending; + occ->due_monotonic_ns = next_due_monotonic_ns; + occ->intended_utc_ms = next_due_utc_ms; + } + + Void::Storage::Batch batch{}; + batch.require_version(occ_key, oval->version); + batch.put(occ_key, encode_occ(*occ)); + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result StorageJobStore::requeue_on_shutdown(const OccurrenceId& id, + std::uint32_t attempt) + { + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string occ_key = make_occ_key(m_options.key_prefix, id); + auto oval = m_engine->get(*snap, occ_key); + if (!oval.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "StorageJobStore: occurrence missing on shutdown requeue")); + } + auto occ = decode_occ(oval->as_string_view()); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + if (occ->status != OccurrenceStatus::Running || + occ->attempt != attempt) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::Conflict, + "StorageJobStore: stale attempt on shutdown requeue")); + } + + occ->status = OccurrenceStatus::Pending; + if (occ->attempt > 0U) { + occ->attempt -= 1U; + } + + Void::Storage::Batch batch{}; + batch.require_version(occ_key, oval->version); + batch.put(occ_key, encode_occ(*occ)); + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result StorageJobStore::recover_running_occurrences() + { + Void::Storage::Snapshot dummy{}; + auto entries = + scan_prefix_all(*m_engine, dummy, m_options.key_prefix + "occ:"); + if (!entries.has_value()) return Void::Result::fail(entries.error()); + + std::size_t recovered = 0; + Void::Storage::Batch batch{}; + auto flush_batch = [&]() -> Result { + if (batch.empty()) return {}; + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + batch = Void::Storage::Batch{}; + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + }; + + for (const auto& e : *entries) { + auto occ = decode_occ(Void::Storage::to_string_view(e.value)); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + if (occ->status == OccurrenceStatus::Running) { + occ->status = OccurrenceStatus::Pending; + const std::string encoded = encode_occ(*occ); + if (!batch.empty() && + estimate_batch_bytes(batch) + e.key.size() + + encoded.size() + 64U > + m_options.limits.max_durable_batch_bytes) { + if (auto fl = flush_batch(); !fl.has_value()) { + return Void::Result::fail(fl.error()); + } + } + batch.require_version(e.key, e.version); + batch.put(e.key, Void::Storage::to_byte_view(encoded)); + ++recovered; + } + } + if (auto fl = flush_batch(); !fl.has_value()) { + return Void::Result::fail(fl.error()); + } + return recovered; + } + + Result StorageJobStore::acknowledge_dead(const OccurrenceId& id) + { + auto snap = m_engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::PersistenceError, snap.error().message())); + } + const std::string occ_key = make_occ_key(m_options.key_prefix, id); + auto oval = m_engine->get(*snap, occ_key); + if (!oval.has_value()) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::NotFound, + "StorageJobStore: occurrence not found")); + } + auto occ = decode_occ(oval->as_string_view()); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + if (occ->status != OccurrenceStatus::Dead) { + return Void::Result::fail(make_scheduler_error( + SchedulerErrorCode::InvalidArgument, + "StorageJobStore: occurrence is not Dead")); + } + occ->dead_acknowledged = true; + Void::Storage::Batch batch{}; + batch.require_version(occ_key, oval->version); + batch.put(occ_key, encode_occ(*occ)); + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result + StorageJobStore::prune_completed(std::int64_t before_utc_ms, + std::size_t max_count) + { + Void::Storage::Snapshot dummy{}; + auto entries = + scan_prefix_all(*m_engine, dummy, m_options.key_prefix + "occ:"); + if (!entries.has_value()) return Void::Result::fail(entries.error()); + + std::size_t pruned = 0; + Void::Storage::Batch batch{}; + for (const auto& e : *entries) { + if (pruned >= max_count) break; + auto occ = decode_occ(Void::Storage::to_string_view(e.value)); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + const bool ok = + (occ->status == OccurrenceStatus::Completed && + occ->completed_utc_ms <= before_utc_ms) || + (occ->status == OccurrenceStatus::Dead && + occ->dead_acknowledged); + if (ok) { + if (estimate_batch_bytes(batch) + e.key.size() + 64U > + m_options.limits.max_durable_batch_bytes) { + break; + } + batch.require_version(e.key, e.version); + batch.erase(e.key); + ++pruned; + } + } + if (!batch.empty()) { + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + } + return pruned; + } + + Result + StorageJobStore::reclaim_invalidated(std::size_t max_count) + { + auto jobs_res = load_jobs(); + if (!jobs_res.has_value()) return Void::Result::fail(jobs_res.error()); + std::map> jmap; + for (auto& j : *jobs_res) { + jmap.emplace(j.spec.id, std::move(j)); + } + + Void::Storage::Snapshot dummy{}; + auto entries = + scan_prefix_all(*m_engine, dummy, m_options.key_prefix + "occ:"); + if (!entries.has_value()) return Void::Result::fail(entries.error()); + + std::size_t reclaimed = 0; + Void::Storage::Batch batch{}; + for (const auto& e : *entries) { + if (reclaimed >= max_count) break; + auto occ = decode_occ(Void::Storage::to_string_view(e.value)); + if (!occ.has_value()) return Void::Result::fail(occ.error()); + bool inv = occ->status == OccurrenceStatus::Cancelled; + if (!inv && occ->status == OccurrenceStatus::Pending) { + auto jit = jmap.find(occ->id.job_id); + if (jit != jmap.end() && + (jit->second.tombstoned || + occ->id.revision < + jit->second.invalidated_before_revision)) { + inv = true; + } + } + if (inv) { + if (estimate_batch_bytes(batch) + e.key.size() + 64U > + m_options.limits.max_durable_batch_bytes) { + break; + } + batch.require_version(e.key, e.version); + batch.erase(e.key); + ++reclaimed; + } + } + if (!batch.empty()) { + auto wr = m_engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + } + return reclaimed; + } + + Result StorageJobStore::stats() const + { + auto jobs = load_jobs(); + if (!jobs.has_value()) return Void::Result::fail(jobs.error()); + auto occs = load_occurrences(); + if (!occs.has_value()) return Void::Result::fail(occs.error()); + + StoreStats s{}; + s.jobs = jobs->size(); + for (const auto& o : *occs) { + switch (o.status) { + case OccurrenceStatus::Pending: ++s.pending; break; + case OccurrenceStatus::Running: ++s.running; break; + case OccurrenceStatus::Completed: ++s.completed; break; + case OccurrenceStatus::Dead: ++s.dead; break; + case OccurrenceStatus::Cancelled: ++s.cancelled; break; + } + } + s.total_retained = occs->size(); + s.retention_saturated = + s.total_retained >= m_options.limits.max_retained_occurrences; + return s; + } + +} // namespace Void::SchedulerStorage diff --git a/src/SchedulerStorage/module.cmake b/src/SchedulerStorage/module.cmake new file mode 100644 index 0000000..064f7d1 --- /dev/null +++ b/src/SchedulerStorage/module.cmake @@ -0,0 +1,3 @@ +void_add_module(SchedulerStorage + INTERNAL_DEPS Scheduler Storage +) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index eeb75eb..d358da8 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -323,6 +323,11 @@ 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() + # 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) diff --git a/tests/package/SchedulerOnly/CMakeLists.txt b/tests/package/SchedulerOnly/CMakeLists.txt new file mode 100644 index 0000000..f5c88cb --- /dev/null +++ b/tests/package/SchedulerOnly/CMakeLists.txt @@ -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) diff --git a/tests/package/SchedulerOnly/main.cpp b/tests/package/SchedulerOnly/main.cpp new file mode 100644 index 0000000..9f3edc9 --- /dev/null +++ b/tests/package/SchedulerOnly/main.cpp @@ -0,0 +1,41 @@ +#include + +#include + +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, + Void::Async::OperationOptions) + -> Void::Scheduler::Result { + ++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; +} diff --git a/tests/standalone/Scheduler/Scheduler.cpp b/tests/standalone/Scheduler/Scheduler.cpp new file mode 100644 index 0000000..f895ba6 --- /dev/null +++ b/tests/standalone/Scheduler/Scheduler.cpp @@ -0,0 +1,307 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +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 order; + Void::Testing::require( + sched + ->register_handler( + "record", + [&](const OccurrenceContext& ctx, std::span, + Void::Async::OperationOptions) -> Result { + 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, + Void::Async::OperationOptions) -> Result { + ++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(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(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(0)); + Void::Testing::expect_eq((*twice)[1].fold_index, + static_cast(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 concurrent_now{0}; + std::atomic max_concurrent_seen{0}; + + Void::Testing::require( + sched + ->register_handler( + "slow", + [&](const OccurrenceContext&, std::span, + Void::Async::OperationOptions) -> Result { + 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); +} diff --git a/tests/standalone/SchedulerStorage/StorageJobStore.cpp b/tests/standalone/SchedulerStorage/StorageJobStore.cpp new file mode 100644 index 0000000..80c3894 --- /dev/null +++ b/tests/standalone/SchedulerStorage/StorageJobStore.cpp @@ -0,0 +1,172 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +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(*eng); + auto store2 = std::make_shared(*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(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( + *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, + Void::Async::OperationOptions) -> Result { + 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( + *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()); +} From 60ee28e4ca9bcd786a426377007cdf9d8a3377a8 Mon Sep 17 00:00:00 2001 From: faumaray Date: Fri, 27 Nov 2026 05:45:43 +0300 Subject: [PATCH 4/5] feat(messaging): implement P3 S-MESSAGING-01..04 Messaging queue, StorageQueue/OutboxInbox, and MessagingRpc adapter --- include/Void/Messaging/Queue.hpp | 180 ++ include/Void/Messaging/Types.hpp | 260 +++ include/Void/MessagingRpc/RpcAdapter.hpp | 89 + include/Void/MessagingStorage/OutboxInbox.hpp | 260 +++ .../Void/MessagingStorage/StorageQueue.hpp | 121 ++ src/Messaging/Queue.cpp | 1075 +++++++++++ src/Messaging/module.cmake | 3 + src/MessagingRpc/RpcAdapter.cpp | 513 +++++ src/MessagingRpc/module.cmake | 3 + src/MessagingStorage/StorageQueue.cpp | 1663 +++++++++++++++++ src/MessagingStorage/module.cmake | 3 + tests/package/InstalledComponents.cmake | 5 + tests/package/MessagingOnly/CMakeLists.txt | 14 + tests/package/MessagingOnly/main.cpp | 33 + tests/standalone/Messaging/Messaging.cpp | 148 ++ tests/standalone/MessagingRpc/RpcAdapter.cpp | 56 + .../MessagingStorage/StorageQueue.cpp | 215 +++ 17 files changed, 4641 insertions(+) create mode 100644 include/Void/Messaging/Queue.hpp create mode 100644 include/Void/Messaging/Types.hpp create mode 100644 include/Void/MessagingRpc/RpcAdapter.hpp create mode 100644 include/Void/MessagingStorage/OutboxInbox.hpp create mode 100644 include/Void/MessagingStorage/StorageQueue.hpp create mode 100644 src/Messaging/Queue.cpp create mode 100644 src/Messaging/module.cmake create mode 100644 src/MessagingRpc/RpcAdapter.cpp create mode 100644 src/MessagingRpc/module.cmake create mode 100644 src/MessagingStorage/StorageQueue.cpp create mode 100644 src/MessagingStorage/module.cmake create mode 100644 tests/package/MessagingOnly/CMakeLists.txt create mode 100644 tests/package/MessagingOnly/main.cpp create mode 100644 tests/standalone/Messaging/Messaging.cpp create mode 100644 tests/standalone/MessagingRpc/RpcAdapter.cpp create mode 100644 tests/standalone/MessagingStorage/StorageQueue.cpp diff --git a/include/Void/Messaging/Queue.hpp b/include/Void/Messaging/Queue.hpp new file mode 100644 index 0000000..d37dc1f --- /dev/null +++ b/include/Void/Messaging/Queue.hpp @@ -0,0 +1,180 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +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 + create_queue(QueueConfig config) = 0; + + [[nodiscard]] virtual Result + create_group(std::string_view queue, GroupConfig config) = 0; + + [[nodiscard]] virtual Result publish( + std::string_view queue, Message message, + PublishDurability durability, + Void::Async::OperationOptions options = {}) = 0; + + [[nodiscard]] virtual Result> + try_receive(std::string_view queue, std::string_view group) = 0; + + [[nodiscard]] virtual Result receive( + std::string_view queue, std::string_view group, + Void::Async::OperationOptions options = {}) = 0; + + [[nodiscard]] virtual Result + ack(const Receipt& receipt, + Void::Async::OperationOptions options = {}) = 0; + + [[nodiscard]] virtual Result nack( + const Receipt& receipt, + std::optional delay = std::nullopt, + Void::Async::OperationOptions options = {}) = 0; + + [[nodiscard]] virtual Result + 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 quarantine_corrupt( + const Receipt& receipt, std::string reason, + Void::Async::OperationOptions options = {}) = 0; + + [[nodiscard]] virtual Result + query_receipt(const Receipt& receipt) const = 0; + + [[nodiscard]] virtual Result> + 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 + reap_expired_visibility() = 0; + + /// Apply configured retention policy (paused when civil clock + /// health is degraded). + [[nodiscard]] virtual Result expire_retention() = 0; + + virtual void set_clock_healthy(bool healthy) noexcept = 0; + + [[nodiscard]] virtual Result close_and_join( + Void::Async::OperationOptions options = {}) = 0; + + [[nodiscard]] virtual Result 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 create_queue(QueueConfig config) override; + [[nodiscard]] Result + create_group(std::string_view queue, + GroupConfig config) override; + + [[nodiscard]] Result publish( + std::string_view queue, Message message, + PublishDurability durability, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Result> + try_receive(std::string_view queue, + std::string_view group) override; + + [[nodiscard]] Result receive( + std::string_view queue, std::string_view group, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Result + ack(const Receipt& receipt, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Result nack( + const Receipt& receipt, + std::optional delay = std::nullopt, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Result + extend_visibility( + const Receipt& receipt, std::chrono::milliseconds extension, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Result quarantine_corrupt( + const Receipt& receipt, std::string reason, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Result + query_receipt(const Receipt& receipt) const override; + + [[nodiscard]] Result> + 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 + reap_expired_visibility() override; + + [[nodiscard]] Result expire_retention() override; + + void set_clock_healthy(bool healthy) noexcept override; + + [[nodiscard]] Result close_and_join( + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Result stats() const override; + + private: + + struct State; + std::shared_ptr m_state; + }; + +} // namespace Void::Messaging diff --git a/include/Void/Messaging/Types.hpp b/include/Void/Messaging/Types.hpp new file mode 100644 index 0000000..3b731c0 --- /dev/null +++ b/include/Void/Messaging/Types.hpp @@ -0,0 +1,260 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Messaging +{ + using Void::Result::Error; + template using Result = Void::Result::Result; + + 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(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 payload{}; + std::map> 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; + + [[nodiscard]] Result + validate_identifier(std::string_view name, std::string_view label); + + [[nodiscard]] Result 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( + 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( + tp.time_since_epoch()) + .count(); + } + +} // namespace Void::Messaging diff --git a/include/Void/MessagingRpc/RpcAdapter.hpp b/include/Void/MessagingRpc/RpcAdapter.hpp new file mode 100644 index 0000000..f360437 --- /dev/null +++ b/include/Void/MessagingRpc/RpcAdapter.hpp @@ -0,0 +1,89 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +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 + mount(Void::RPC::Server& server, + Void::Messaging::Queue& queue); + + void unmount_and_drain() noexcept; + + private: + + std::vector 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 + 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> + try_receive(std::string_view queue, std::string_view group, + const Void::RPC::CallOptions& options = {}); + + [[nodiscard]] Void::Messaging::Result + ack(const Void::Messaging::Receipt& receipt, + const Void::RPC::CallOptions& options = {}); + + [[nodiscard]] Void::Messaging::Result + nack(const Void::Messaging::Receipt& receipt, + std::optional delay = + std::nullopt, + const Void::RPC::CallOptions& options = {}); + + [[nodiscard]] Void::Messaging::Result + query_receipt(const Void::Messaging::Receipt& receipt, + const Void::RPC::CallOptions& options = {}); + + private: + + Void::RPC::Client m_client; + }; + +} // namespace Void::MessagingRpc diff --git a/include/Void/MessagingStorage/OutboxInbox.hpp b/include/Void/MessagingStorage/OutboxInbox.hpp new file mode 100644 index 0000000..127c0b1 --- /dev/null +++ b/include/Void/MessagingStorage/OutboxInbox.hpp @@ -0,0 +1,260 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +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 + 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((v >> 24U) & 0xFFU)); + out.push_back(static_cast((v >> 16U) & 0xFFU)); + out.push_back(static_cast((v >> 8U) & 0xFFU)); + out.push_back(static_cast(v & 0xFFU)); + } + + static void append_str(std::string& out, std::string_view s) + { + append_u32(out, static_cast(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( + static_cast(in[0])) + << 24U) | + (static_cast( + static_cast(in[1])) + << 16U) | + (static_cast( + static_cast(in[2])) + << 8U) | + static_cast( + static_cast(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(r.message.payload.size())); + if (!r.message.payload.empty()) { + out.append( + reinterpret_cast(r.message.payload.data()), + r.message.payload.size()); + } + append_u32( + out, static_cast(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 + 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 diff --git a/include/Void/MessagingStorage/StorageQueue.hpp b/include/Void/MessagingStorage/StorageQueue.hpp new file mode 100644 index 0000000..3b51641 --- /dev/null +++ b/include/Void/MessagingStorage/StorageQueue.hpp @@ -0,0 +1,121 @@ +#pragma once + +#include +#include + +#include +#include + +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 + 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 + create_queue(Void::Messaging::QueueConfig config) override; + + [[nodiscard]] Void::Messaging::Result + create_group(std::string_view queue, + Void::Messaging::GroupConfig config) override; + + [[nodiscard]] Void::Messaging::Result + publish(std::string_view queue, Void::Messaging::Message message, + Void::Messaging::PublishDurability durability, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Void::Messaging::Result< + std::optional> + try_receive(std::string_view queue, + std::string_view group) override; + + [[nodiscard]] Void::Messaging::Result + receive(std::string_view queue, std::string_view group, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Void::Messaging::Result + ack(const Void::Messaging::Receipt& receipt, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Void::Messaging::Result nack( + const Void::Messaging::Receipt& receipt, + std::optional 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 quarantine_corrupt( + const Void::Messaging::Receipt& receipt, std::string reason, + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Void::Messaging::Result + query_receipt( + const Void::Messaging::Receipt& receipt) const override; + + [[nodiscard]] Void::Messaging::Result< + std::vector> + 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 + reap_expired_visibility() override; + + [[nodiscard]] Void::Messaging::Result + expire_retention() override; + + void set_clock_healthy(bool healthy) noexcept override; + + [[nodiscard]] Void::Messaging::Result + close_and_join( + Void::Async::OperationOptions options = {}) override; + + [[nodiscard]] Void::Messaging::Result + stats() const override; + + private: + + struct State; + explicit StorageQueue(std::shared_ptr state) noexcept; + std::shared_ptr m_state; + }; + +} // namespace Void::MessagingStorage diff --git a/src/Messaging/Queue.cpp b/src/Messaging/Queue.cpp new file mode 100644 index 0000000..49a4ba8 --- /dev/null +++ b/src/Messaging/Queue.cpp @@ -0,0 +1,1075 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Messaging +{ + Result validate_identifier(std::string_view name, + std::string_view label) + { + if (name.empty() || name.size() > 256U) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: invalid " + std::string{label} + " length")); + } + for (unsigned char c : name) { + if (c < 0x21U || c > 0x7EU) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: invalid character in " + std::string{label})); + } + } + return {}; + } + + Result validate_message(const Message& message, + const QueueLimits& limits) + { + if (auto id_ok = validate_identifier(message.id, "message.id"); + !id_ok.has_value()) { + return id_ok; + } + if (message.payload.size() > limits.max_message_bytes) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: message payload exceeds max_message_bytes")); + } + if (message.headers.size() > limits.max_header_count) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: header count exceeds max_header_count")); + } + std::size_t hbytes = 0; + for (const auto& [k, v] : message.headers) { + if (k.empty()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: header key must not be empty")); + } + for (unsigned char c : k) { + if (c < 0x20U || c > 0x7EU) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: invalid header key character")); + } + } + for (unsigned char c : v) { + if (c < 0x20U || c > 0x7EU) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: invalid header value character")); + } + } + hbytes += k.size() + v.size(); + if (hbytes > limits.max_headers_bytes) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: headers exceed max_headers_bytes")); + } + } + return {}; + } + + std::size_t estimate_message_bytes(const Message& message) noexcept + { + std::size_t total = message.id.size() + message.payload.size() + 64U; + for (const auto& [k, v] : message.headers) { + total += k.size() + v.size() + 16U; + } + return total; + } + + std::int64_t compute_retry_backoff_ms(const RetryPolicy& retry, + std::uint32_t attempt, + const RandomU64Fn& rng) + { + const std::int64_t base_ms = + std::max(0LL, retry.base_delay.count()); + const std::int64_t max_ms = + std::max(base_ms, retry.max_delay.count()); + if (max_ms == 0LL) { + return 0LL; + } + std::int64_t cap = base_ms; + for (std::uint32_t i = 1U; i < attempt; ++i) { + if (cap > max_ms / 2LL) { + cap = max_ms; + break; + } + cap *= 2LL; + } + cap = std::min(cap, max_ms); + if (cap <= 0LL) { + return 0LL; + } + const std::uint64_t r = rng ? rng() : 0ULL; + return static_cast( + r % (static_cast(cap) + 1ULL)); + } + + namespace + { + struct StoredMsg { + std::uint64_t sequence{0}; + Message message{}; + std::int64_t published_utc_ms{0}; + std::size_t bytes{0}; + }; + + struct DeliverySlot { + std::uint64_t sequence{0}; + std::string message_id{}; + DeliveryState state{DeliveryState::Pending}; + std::uint64_t generation{0}; + std::uint32_t attempt{0}; + Void::Time::MonotonicClock::time_point available_at{}; + Void::Time::MonotonicClock::time_point visibility_deadline{}; + bool stuck_dlq{false}; + }; + + struct GroupState { + GroupConfig config{}; + std::map slots{}; + std::vector dlq{}; + std::size_t in_flight{0}; + std::size_t stuck_dlq{0}; + }; + + struct IdempotencyEntry { + std::uint64_t sequence{0}; + std::int64_t published_utc_ms{0}; + }; + + struct QueueData { + QueueConfig config{}; + std::uint64_t next_sequence{1}; + std::map messages{}; + std::map> groups{}; + std::map> + idempotency{}; + }; + } // namespace + + struct InMemoryQueue::State { + QueueLimits limits{}; + const Void::Time::MonotonicClock* mono{ + &Void::Time::SystemMonotonicClock::instance()}; + const Void::Time::CivilClock* civil{ + &Void::Time::SystemCivilClock::instance()}; + RandomU64Fn rng{}; + + mutable std::mutex mu{}; + std::condition_variable cv{}; + bool closing{false}; + bool clock_healthy{true}; + std::size_t waiting_receives{0}; + std::size_t transient_bytes{0}; + std::map> queues{}; + + [[nodiscard]] std::size_t total_dlq_locked() const noexcept + { + std::size_t n = 0; + for (const auto& [qn, qd] : queues) { + (void)qn; + for (const auto& [gn, gs] : qd.groups) { + (void)gn; + n += gs.dlq.size(); + } + } + return n; + } + + [[nodiscard]] std::size_t total_idem_locked() const noexcept + { + std::size_t n = 0; + for (const auto& [qn, qd] : queues) { + (void)qn; + n += qd.idempotency.size(); + } + return n; + } + + void gc_expired_idempotency_locked(std::int64_t now_utc_ms) + { + if (!clock_healthy) { + return; + } + const std::int64_t cutoff = + now_utc_ms - limits.idempotency_retention.count(); + for (auto& [qn, qd] : queues) { + (void)qn; + for (auto it = qd.idempotency.begin(); + it != qd.idempotency.end();) { + if (it->second.published_utc_ms <= cutoff) { + it = qd.idempotency.erase(it); + } else { + ++it; + } + } + } + } + + Result move_to_dlq_locked(QueueData& qd, GroupState& gs, + DeliverySlot& slot, + std::string reason) + { + if (total_dlq_locked() >= limits.max_dlq_messages) { + if (!slot.stuck_dlq) { + slot.stuck_dlq = true; + ++gs.stuck_dlq; + } + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::DlqFull, + "Messaging: DLQ capacity full; message retained")); + } + auto mit = qd.messages.find(slot.sequence); + Message msg{}; + if (mit != qd.messages.end()) { + msg = mit->second.message; + } else { + msg.id = slot.message_id; + } + DeadLetterEntry dle{}; + dle.message = std::move(msg); + dle.queue = qd.config.name; + dle.group = gs.config.name; + dle.sequence = slot.sequence; + dle.attempts = slot.attempt; + dle.reason = std::move(reason); + dle.dead_lettered_utc_ms = to_utc_ms(civil->now()); + gs.dlq.push_back(std::move(dle)); + if (slot.stuck_dlq) { + slot.stuck_dlq = false; + if (gs.stuck_dlq > 0U) { + --gs.stuck_dlq; + } + } + if (slot.state == DeliveryState::InFlight && gs.in_flight > 0U) { + --gs.in_flight; + } + slot.state = DeliveryState::DeadLetter; + return {}; + } + + std::size_t reap_expired_locked() + { + const auto now = mono->now(); + std::size_t reaped = 0; + for (auto& [qn, qd] : queues) { + (void)qn; + for (auto& [gn, gs] : qd.groups) { + (void)gn; + for (auto& [seq, slot] : gs.slots) { + (void)seq; + if (slot.state != DeliveryState::InFlight) { + continue; + } + if (now < slot.visibility_deadline) { + continue; + } + if (slot.attempt >= qd.config.retry.max_attempts) { + auto mr = move_to_dlq_locked( + qd, gs, slot, + "visibility timeout retry exhaustion"); + if (mr.has_value()) { + ++reaped; + } + } else { + const std::int64_t backoff_ms = + compute_retry_backoff_ms( + qd.config.retry, slot.attempt, rng); + slot.state = DeliveryState::Pending; + if (gs.in_flight > 0U) { + --gs.in_flight; + } + slot.available_at = + now + std::chrono::milliseconds{backoff_ms}; + ++reaped; + } + } + } + } + if (reaped > 0U) { + cv.notify_all(); + } + return reaped; + } + + Result> + try_receive_locked(std::string_view queue, + std::string_view group) + { + auto qit = queues.find(queue); + if (qit == queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "Messaging: queue not found: " + std::string{queue})); + } + auto& qd = qit->second; + auto git = qd.groups.find(group); + if (git == qd.groups.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "Messaging: consumer group not found: " + + std::string{group})); + } + auto& gs = git->second; + + const std::size_t eff_cap = + gs.config.mode == ConsumerMode::SingleActive + ? 1U + : std::min(gs.config.max_in_flight, + limits.max_in_flight_per_group); + if (gs.in_flight >= eff_cap) { + return std::optional{std::nullopt}; + } + + const auto now = mono->now(); + for (auto& [seq, slot] : gs.slots) { + if (slot.state == DeliveryState::Acked || + slot.state == DeliveryState::DeadLetter) { + continue; + } + if (gs.config.mode == ConsumerMode::SingleActive) { + // Head-of-line order: block group head if head is + // InFlight or waiting on retry backoff. + if (slot.state == DeliveryState::InFlight || + slot.available_at > now) { + return std::optional{std::nullopt}; + } + } + if (slot.state != DeliveryState::Pending || + slot.available_at > now) { + continue; + } + auto mit = qd.messages.find(seq); + if (mit == qd.messages.end()) { + continue; + } + + slot.state = DeliveryState::InFlight; + slot.generation += 1U; + slot.attempt += 1U; + slot.visibility_deadline = + now + gs.config.visibility_timeout; + gs.in_flight += 1U; + + Delivery d{}; + d.message = mit->second.message; + d.receipt = Receipt{ + .queue = qd.config.name, + .group = gs.config.name, + .message_id = slot.message_id, + .sequence = seq, + .generation = slot.generation, + }; + d.attempt = slot.attempt; + d.visibility_deadline = slot.visibility_deadline; + return std::optional{std::move(d)}; + } + return std::optional{std::nullopt}; + } + }; + + InMemoryQueue::InMemoryQueue(InMemoryQueueOptions options) + : m_state(std::make_shared()) + { + m_state->limits = options.limits; + m_state->mono = + options.monotonic_clock != nullptr + ? options.monotonic_clock + : &Void::Time::SystemMonotonicClock::instance(); + m_state->civil = options.civil_clock != nullptr + ? options.civil_clock + : &Void::Time::SystemCivilClock::instance(); + if (options.rng) { + m_state->rng = std::move(options.rng); + } else { + auto prng = std::make_shared(0xD1B54A32D192ED03ULL); + auto pmu = std::make_shared(); + m_state->rng = [prng, pmu]() -> std::uint64_t { + std::lock_guard lk{*pmu}; + return (*prng)(); + }; + } + } + + InMemoryQueue::~InMemoryQueue() noexcept + { + if (m_state) { + { + std::lock_guard lk{m_state->mu}; + m_state->closing = true; + } + m_state->cv.notify_all(); + } + } + + InMemoryQueue::InMemoryQueue(InMemoryQueue&&) noexcept = default; + InMemoryQueue& InMemoryQueue::operator=(InMemoryQueue&&) noexcept = default; + + Result InMemoryQueue::create_queue(QueueConfig config) + { + if (auto ok = validate_identifier(config.name, "queue"); !ok.has_value()) { + return ok; + } + if (config.retry.max_attempts == 0U || + config.retry.base_delay < std::chrono::milliseconds{0} || + config.retry.max_delay < config.retry.base_delay) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: invalid RetryPolicy")); + } + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "Messaging queue is closed")); + } + if (m_state->queues.contains(config.name)) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Conflict, + "Messaging: queue already exists: " + config.name)); + } + if (m_state->queues.size() >= m_state->limits.max_queues) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Overloaded, + "Messaging: max_queues cap reached")); + } + QueueData qd{}; + qd.config = std::move(config); + m_state->queues.emplace(qd.config.name, std::move(qd)); + return {}; + } + + Result InMemoryQueue::create_group(std::string_view queue, + GroupConfig config) + { + if (auto ok = validate_identifier(config.name, "group"); !ok.has_value()) { + return ok; + } + if (config.visibility_timeout <= std::chrono::milliseconds{0} || + config.max_in_flight == 0U) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging: group visibility_timeout and max_in_flight must be " + "positive")); + } + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "Messaging queue is closed")); + } + auto qit = m_state->queues.find(queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "Messaging: queue not found: " + std::string{queue})); + } + auto& qd = qit->second; + if (qd.groups.contains(config.name)) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Conflict, + "Messaging: group already exists: " + config.name)); + } + if (qd.groups.size() >= m_state->limits.max_groups_per_queue) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Overloaded, + "Messaging: max_groups_per_queue reached")); + } + GroupState gs{}; + gs.config = std::move(config); + // Materialize pending delivery slots for existing unacknowledged + // messages in this queue. + const auto now = m_state->mono->now(); + for (const auto& [seq, msg] : qd.messages) { + gs.slots.emplace(seq, DeliverySlot{ + .sequence = seq, + .message_id = msg.message.id, + .state = DeliveryState::Pending, + .generation = 0, + .attempt = 0, + .available_at = now, + }); + } + qd.groups.emplace(gs.config.name, std::move(gs)); + m_state->cv.notify_all(); + return {}; + } + + Result + InMemoryQueue::publish(std::string_view queue, Message message, + PublishDurability durability, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, "Messaging::publish cancelled")); + } + if (durability == PublishDurability::Durable) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::UnsupportedDurability, + "InMemoryQueue is explicitly nondurable and cannot satisfy " + "PublishDurability::Durable")); + } + if (auto vm = validate_message(message, m_state->limits); + !vm.has_value()) { + return Void::Result::fail(vm.error()); + } + + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "Messaging queue is closed")); + } + auto qit = m_state->queues.find(queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "Messaging: queue not found: " + std::string{queue})); + } + auto& qd = qit->second; + const std::int64_t now_utc = to_utc_ms(m_state->civil->now()); + m_state->gc_expired_idempotency_locked(now_utc); + + // Check bounded idempotency ledger. + if (auto iit = qd.idempotency.find(message.id); + iit != qd.idempotency.end()) { + return PublishReceipt{ + .queue = qd.config.name, + .message_id = message.id, + .sequence = iit->second.sequence, + .durability = PublishDurability::Memory, + .deduplicated = true, + }; + } + if (m_state->total_idem_locked() >= + m_state->limits.max_idempotency_entries) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::IdempotencyCapacityExceeded, + "Messaging: idempotency ledger at capacity; refusing silent " + "eviction")); + } + + const std::size_t msg_bytes = estimate_message_bytes(message); + if (m_state->transient_bytes + msg_bytes > + m_state->limits.max_transient_payload_bytes) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::QuotaExceeded, + "Messaging: transient payload budget exceeded")); + } + + const std::uint64_t seq = qd.next_sequence++; + const auto now_mono = m_state->mono->now(); + const std::string msg_id = message.id; + + qd.messages.emplace(seq, StoredMsg{ + .sequence = seq, + .message = std::move(message), + .published_utc_ms = now_utc, + .bytes = msg_bytes, + }); + qd.idempotency.emplace(msg_id, IdempotencyEntry{ + .sequence = seq, + .published_utc_ms = now_utc, + }); + m_state->transient_bytes += msg_bytes; + + for (auto& [gn, gs] : qd.groups) { + (void)gn; + gs.slots.emplace(seq, DeliverySlot{ + .sequence = seq, + .message_id = msg_id, + .state = DeliveryState::Pending, + .generation = 0, + .attempt = 0, + .available_at = now_mono, + }); + } + + m_state->cv.notify_all(); + return PublishReceipt{ + .queue = qd.config.name, + .message_id = msg_id, + .sequence = seq, + .durability = PublishDurability::Memory, + .deduplicated = false, + }; + } + + Result> + InMemoryQueue::try_receive(std::string_view queue, + std::string_view group) + { + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "Messaging queue is closed")); + } + m_state->reap_expired_locked(); + return m_state->try_receive_locked(queue, group); + } + + Result InMemoryQueue::receive( + std::string_view queue, std::string_view group, + Void::Async::OperationOptions options) + { + std::unique_lock lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "Messaging queue is closed")); + } + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, "Messaging::receive cancelled")); + } + + m_state->reap_expired_locked(); + auto immediate = m_state->try_receive_locked(queue, group); + if (!immediate.has_value()) { + return Void::Result::fail(immediate.error()); + } + if (immediate->has_value()) { + return std::move(**immediate); + } + + if (m_state->waiting_receives >= m_state->limits.max_waiting_receives) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Overloaded, + "Messaging: max_waiting_receives cap reached")); + } + + ++m_state->waiting_receives; + struct WaitGuard { + std::size_t& counter; + ~WaitGuard() noexcept { --counter; } + } wguard{m_state->waiting_receives}; + + std::stop_callback stop_cb(options.stop, + [this] { m_state->cv.notify_all(); }); + + for (;;) { + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, + "Messaging queue closed while waiting to receive")); + } + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "Messaging::receive cancelled while waiting")); + } + m_state->reap_expired_locked(); + auto polled = m_state->try_receive_locked(queue, group); + if (!polled.has_value()) { + return Void::Result::fail(polled.error()); + } + if (polled->has_value()) { + return std::move(**polled); + } + if (options.deadline.has_value()) { + const auto rem = Void::Time::remaining_until( + *m_state->mono, *options.deadline); + if (rem <= std::chrono::nanoseconds{0}) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Timeout, + "Messaging::receive deadline expired")); + } + const auto slice = + std::min(rem, std::chrono::duration_cast< + std::chrono::nanoseconds>( + std::chrono::milliseconds{5})); + m_state->cv.wait_for(lk, slice); + } else { + m_state->cv.wait_for(lk, std::chrono::milliseconds{5}); + } + } + } + + Result InMemoryQueue::ack(const Receipt& receipt, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, "Messaging::ack cancelled")); + } + std::lock_guard lk{m_state->mu}; + auto qit = m_state->queues.find(receipt.queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: queue not found")); + } + auto git = qit->second.groups.find(receipt.group); + if (git == qit->second.groups.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: group not found")); + } + auto sit = git->second.slots.find(receipt.sequence); + if (sit == git->second.slots.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: receipt not found")); + } + auto& slot = sit->second; + // Repeat ack of the same already-acknowledged receipt is idempotent OK! + if (slot.state == DeliveryState::Acked && + slot.generation == receipt.generation) { + return {}; + } + if (slot.state != DeliveryState::InFlight || + slot.generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "Messaging::ack receipt generation is stale")); + } + slot.state = DeliveryState::Acked; + if (git->second.in_flight > 0U) { + --git->second.in_flight; + } + m_state->cv.notify_all(); + return {}; + } + + Result InMemoryQueue::nack( + const Receipt& receipt, std::optional delay, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, "Messaging::nack cancelled")); + } + std::lock_guard lk{m_state->mu}; + auto qit = m_state->queues.find(receipt.queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: queue not found")); + } + auto& qd = qit->second; + auto git = qd.groups.find(receipt.group); + if (git == qd.groups.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: group not found")); + } + auto& gs = git->second; + auto sit = gs.slots.find(receipt.sequence); + if (sit == gs.slots.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: receipt not found")); + } + auto& slot = sit->second; + if (slot.state != DeliveryState::InFlight || + slot.generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "Messaging::nack receipt generation is stale")); + } + + if (slot.attempt >= qd.config.retry.max_attempts) { + auto dlq_res = m_state->move_to_dlq_locked( + qd, gs, slot, "nack retry exhaustion"); + m_state->cv.notify_all(); + return dlq_res; + } + + const std::int64_t wait_ms = + delay.has_value() + ? std::max(0LL, delay->count()) + : compute_retry_backoff_ms(qd.config.retry, slot.attempt, + m_state->rng); + slot.state = DeliveryState::Pending; + if (gs.in_flight > 0U) { + --gs.in_flight; + } + slot.available_at = + m_state->mono->now() + std::chrono::milliseconds{wait_ms}; + m_state->cv.notify_all(); + return {}; + } + + Result + InMemoryQueue::extend_visibility(const Receipt& receipt, + std::chrono::milliseconds extension, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "Messaging::extend_visibility cancelled")); + } + if (extension <= std::chrono::milliseconds{0} || + extension > m_state->limits.max_visibility_extension) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "Messaging::extend_visibility must be in (0, " + "max_visibility_extension]")); + } + std::lock_guard lk{m_state->mu}; + auto qit = m_state->queues.find(receipt.queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: queue not found")); + } + auto git = qit->second.groups.find(receipt.group); + if (git == qit->second.groups.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: group not found")); + } + auto sit = git->second.slots.find(receipt.sequence); + if (sit == git->second.slots.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: receipt not found")); + } + auto& slot = sit->second; + if (slot.state != DeliveryState::InFlight || + slot.generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "Messaging::extend_visibility receipt generation is stale")); + } + slot.visibility_deadline = m_state->mono->now() + extension; + return slot.visibility_deadline; + } + + Result InMemoryQueue::quarantine_corrupt( + const Receipt& receipt, std::string reason, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "Messaging::quarantine_corrupt cancelled")); + } + std::lock_guard lk{m_state->mu}; + auto qit = m_state->queues.find(receipt.queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: queue not found")); + } + auto& qd = qit->second; + auto git = qd.groups.find(receipt.group); + if (git == qd.groups.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: group not found")); + } + auto& gs = git->second; + auto sit = gs.slots.find(receipt.sequence); + if (sit == gs.slots.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: receipt not found")); + } + auto& slot = sit->second; + if (slot.state != DeliveryState::InFlight || + slot.generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "Messaging::quarantine_corrupt receipt generation is stale")); + } + auto res = m_state->move_to_dlq_locked( + qd, gs, slot, + reason.empty() ? std::string{"corrupt payload"} : std::move(reason)); + m_state->cv.notify_all(); + return res; + } + + Result + InMemoryQueue::query_receipt(const Receipt& receipt) const + { + std::lock_guard lk{m_state->mu}; + auto qit = m_state->queues.find(receipt.queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: queue not found")); + } + auto git = qit->second.groups.find(receipt.group); + if (git == qit->second.groups.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: group not found")); + } + auto sit = git->second.slots.find(receipt.sequence); + if (sit == git->second.slots.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: receipt not found")); + } + return sit->second.state; + } + + Result> + InMemoryQueue::list_dead_letters(std::string_view queue, + std::string_view group, + std::size_t limit) const + { + std::lock_guard lk{m_state->mu}; + auto qit = m_state->queues.find(queue); + if (qit == m_state->queues.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: queue not found")); + } + auto git = qit->second.groups.find(group); + if (git == qit->second.groups.end()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, "Messaging: group not found")); + } + const auto& dlq = git->second.dlq; + const std::size_t n = std::min(limit, dlq.size()); + return std::vector(dlq.begin(), + dlq.begin() + + static_cast(n)); + } + + std::size_t InMemoryQueue::stuck_dlq_count(std::string_view queue, + std::string_view group) const + noexcept + { + std::lock_guard lk{m_state->mu}; + auto qit = m_state->queues.find(queue); + if (qit == m_state->queues.end()) return 0; + auto git = qit->second.groups.find(group); + if (git == qit->second.groups.end()) return 0; + return git->second.stuck_dlq; + } + + Result InMemoryQueue::reap_expired_visibility() + { + std::lock_guard lk{m_state->mu}; + return m_state->reap_expired_locked(); + } + + Result InMemoryQueue::expire_retention() + { + std::lock_guard lk{m_state->mu}; + if (!m_state->clock_healthy) { + // Pause retention expiry when civil clock health is degraded! + return 0U; + } + const std::int64_t cutoff = + to_utc_ms(m_state->civil->now()) - + m_state->limits.logical_retention.count(); + std::size_t expired = 0; + + for (auto& [qn, qd] : m_state->queues) { + (void)qn; + for (auto mit = qd.messages.begin(); mit != qd.messages.end();) { + if (mit->second.published_utc_ms > cutoff) { + ++mit; + continue; + } + const std::uint64_t seq = mit->first; + bool all_terminal = true; + bool any_in_flight = false; + for (const auto& [gn, gs] : qd.groups) { + (void)gn; + auto sit = gs.slots.find(seq); + if (sit != gs.slots.end()) { + if (sit->second.state == DeliveryState::InFlight) { + any_in_flight = true; + all_terminal = false; + } else if (sit->second.state == DeliveryState::Pending) { + all_terminal = false; + } + } + } + const bool can_drop = + !any_in_flight && + (all_terminal || + qd.config.retention_policy == + RetentionPolicy::DropOldestLossy); + if (can_drop) { + for (auto& [gn, gs] : qd.groups) { + (void)gn; + gs.slots.erase(seq); + } + if (m_state->transient_bytes >= mit->second.bytes) { + m_state->transient_bytes -= mit->second.bytes; + } else { + m_state->transient_bytes = 0; + } + mit = qd.messages.erase(mit); + ++expired; + } else { + ++mit; + } + } + } + return expired; + } + + void InMemoryQueue::set_clock_healthy(bool healthy) noexcept + { + std::lock_guard lk{m_state->mu}; + m_state->clock_healthy = healthy; + } + + Result + InMemoryQueue::close_and_join(Void::Async::OperationOptions options) + { + std::unique_lock lk{m_state->mu}; + m_state->closing = true; + m_state->cv.notify_all(); + + auto count_in_flight = [&]() { + std::size_t n = 0; + for (const auto& [qn, qd] : m_state->queues) { + (void)qn; + for (const auto& [gn, gs] : qd.groups) { + (void)gn; + n += gs.in_flight; + } + } + return n; + }; + + const auto deadline = + options.deadline.value_or(m_state->mono->now() + + m_state->limits.shutdown_drain_timeout); + while (count_in_flight() > 0U || m_state->waiting_receives > 0U) { + const auto rem = Void::Time::remaining_until(*m_state->mono, deadline); + if (rem <= std::chrono::nanoseconds{0}) { + const std::size_t live = count_in_flight(); + return ShutdownReport{ + .complete = (live == 0U && m_state->waiting_receives == 0U), + .remaining_in_flight = live, + }; + } + const auto slice = + std::min(rem, std::chrono::duration_cast< + std::chrono::nanoseconds>( + std::chrono::milliseconds{5})); + m_state->cv.wait_for(lk, slice); + } + return ShutdownReport{.complete = true, .remaining_in_flight = 0}; + } + + Result InMemoryQueue::stats() const + { + std::lock_guard lk{m_state->mu}; + QueueStats s{}; + s.queues = m_state->queues.size(); + s.retained_bytes = m_state->transient_bytes; + for (const auto& [qn, qd] : m_state->queues) { + (void)qn; + s.idempotency_entries += qd.idempotency.size(); + for (const auto& [gn, gs] : qd.groups) { + (void)gn; + s.dead_letter += gs.dlq.size(); + s.stuck_dlq += gs.stuck_dlq; + for (const auto& [seq, slot] : gs.slots) { + (void)seq; + switch (slot.state) { + case DeliveryState::Pending: ++s.pending; break; + case DeliveryState::InFlight: ++s.in_flight; break; + case DeliveryState::Acked: ++s.acked; break; + case DeliveryState::DeadLetter: break; + } + } + } + } + return s; + } + +} // namespace Void::Messaging diff --git a/src/Messaging/module.cmake b/src/Messaging/module.cmake new file mode 100644 index 0000000..bf54683 --- /dev/null +++ b/src/Messaging/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Messaging + INTERNAL_DEPS Core Functional Binary Time Async +) diff --git a/src/MessagingRpc/RpcAdapter.cpp b/src/MessagingRpc/RpcAdapter.cpp new file mode 100644 index 0000000..5b6132c --- /dev/null +++ b/src/MessagingRpc/RpcAdapter.cpp @@ -0,0 +1,513 @@ +#include + +#include +#include +#include +#include +#include + +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(v)); + } + + void put_u32(Void::RPC::OwnedBytes& out, std::uint32_t v) + { + out.push_back(static_cast((v >> 24U) & 0xFFU)); + out.push_back(static_cast((v >> 16U) & 0xFFU)); + out.push_back(static_cast((v >> 8U) & 0xFFU)); + out.push_back(static_cast(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((v >> shift) & 0xFFU)); + } + } + + void put_i64(Void::RPC::OwnedBytes& out, std::int64_t v) + { + put_u64(out, static_cast(v)); + } + + void put_str(Void::RPC::OwnedBytes& out, std::string_view s) + { + put_u32(out, static_cast(s.size())); + for (char c : s) { + out.push_back(static_cast(c)); + } + } + + void put_bytes(Void::RPC::OwnedBytes& out, + const std::vector& b) + { + put_u32(out, static_cast(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(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 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(data[pos++]); + return true; + } + + [[nodiscard]] bool read_u32(std::uint32_t& v) noexcept + { + if (pos + 4U > data.size()) return false; + v = (static_cast( + std::to_integer(data[pos])) + << 24U) | + (static_cast( + std::to_integer(data[pos + 1])) + << 16U) | + (static_cast( + std::to_integer(data[pos + 2])) + << 8U) | + static_cast( + std::to_integer(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::to_integer(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(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& 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 RpcQueueServer::mount(Void::RPC::Server& server, Queue& queue) + { + auto bind_one = [&](Void::RPC::MethodId id, std::string name, + Void::RPC::UnaryHandler handler) -> Result { + 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 { + 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(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(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 { + 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 { + 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 { + 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 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 { + 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(*res)); + return out; + }); + !r.has_value()) { + return r; + } + + return {}; + } + + // ── RpcQueueClient ──────────────────────────────────────────────────────── + + RpcQueueClient::RpcQueueClient(Void::RPC::ClientOptions options) + : m_client(std::move(options)) + { + } + + Result 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(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(dur); + pr.deduplicated = (dedup != 0U); + return pr; + } + + Result> + 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{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{std::move(d)}; + } + + Result 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 + RpcQueueClient::nack(const Receipt& receipt, + std::optional 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 + 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(DeliveryState::DeadLetter)) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::CorruptPayload, + "MessagingRpc: corrupt query_receipt response")); + } + return static_cast(st); + } + +} // namespace Void::MessagingRpc diff --git a/src/MessagingRpc/module.cmake b/src/MessagingRpc/module.cmake new file mode 100644 index 0000000..6f15ec4 --- /dev/null +++ b/src/MessagingRpc/module.cmake @@ -0,0 +1,3 @@ +void_add_module(MessagingRpc + INTERNAL_DEPS Messaging RPC +) diff --git a/src/MessagingStorage/StorageQueue.cpp b/src/MessagingStorage/StorageQueue.cpp new file mode 100644 index 0000000..1941660 --- /dev/null +++ b/src/MessagingStorage/StorageQueue.cpp @@ -0,0 +1,1663 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::MessagingStorage +{ + using namespace Void::Messaging; + using Void::Messaging::Result; + + namespace + { + constexpr std::uint32_t kSchemaVersion = 1U; + + void append_u8(std::string& out, std::uint8_t v) + { + out.push_back(static_cast(v)); + } + + void append_u32(std::string& out, std::uint32_t v) + { + out.push_back(static_cast((v >> 24U) & 0xFFU)); + out.push_back(static_cast((v >> 16U) & 0xFFU)); + out.push_back(static_cast((v >> 8U) & 0xFFU)); + out.push_back(static_cast(v & 0xFFU)); + } + + void append_u64(std::string& out, std::uint64_t v) + { + for (int shift = 56; shift >= 0; shift -= 8) { + out.push_back(static_cast((v >> shift) & 0xFFU)); + } + } + + void append_i64(std::string& out, std::int64_t v) + { + append_u64(out, static_cast(v)); + } + + void append_str(std::string& out, std::string_view s) + { + append_u32(out, static_cast(s.size())); + out.append(s); + } + + void append_bytes(std::string& out, const std::vector& b) + { + append_u32(out, static_cast(b.size())); + if (!b.empty()) { + out.append(reinterpret_cast(b.data()), b.size()); + } + } + + [[nodiscard]] bool read_u8(std::string_view& in, + std::uint8_t& out) noexcept + { + if (in.empty()) return false; + out = static_cast(static_cast(in[0])); + in.remove_prefix(1U); + return true; + } + + [[nodiscard]] bool read_u32(std::string_view& in, + std::uint32_t& out) noexcept + { + if (in.size() < 4U) return false; + out = (static_cast(static_cast(in[0])) + << 24U) | + (static_cast(static_cast(in[1])) + << 16U) | + (static_cast(static_cast(in[2])) + << 8U) | + static_cast(static_cast(in[3])); + in.remove_prefix(4U); + return true; + } + + [[nodiscard]] bool read_u64(std::string_view& in, + std::uint64_t& out) noexcept + { + if (in.size() < 8U) return false; + std::uint64_t v = 0; + for (std::size_t i = 0; i < 8U; ++i) { + v = (v << 8U) | static_cast( + static_cast(in[i])); + } + in.remove_prefix(8U); + out = v; + return true; + } + + [[nodiscard]] bool read_i64(std::string_view& in, + std::int64_t& out) noexcept + { + std::uint64_t u = 0; + if (!read_u64(in, u)) return false; + out = static_cast(u); + return true; + } + + [[nodiscard]] bool read_str(std::string_view& in, std::string& out) + { + std::uint32_t len = 0; + if (!read_u32(in, len) || len > in.size()) return false; + out.assign(in.data(), len); + in.remove_prefix(len); + return true; + } + + [[nodiscard]] bool read_bytes(std::string_view& in, + std::vector& out) + { + std::uint32_t len = 0; + if (!read_u32(in, len) || len > in.size()) return false; + out.resize(len); + if (len > 0U) { + std::memcpy(out.data(), in.data(), len); + } + in.remove_prefix(len); + return true; + } + + struct PersistedQueue { + QueueConfig config{}; + std::uint64_t next_sequence{1}; + }; + + struct PersistedMessage { + std::uint64_t sequence{0}; + std::int64_t published_utc_ms{0}; + Message message{}; + }; + + struct PersistedIdem { + std::uint64_t sequence{0}; + std::int64_t published_utc_ms{0}; + }; + + struct PersistedDelivery { + std::string queue{}; + std::string group{}; + std::uint64_t sequence{0}; + std::string message_id{}; + DeliveryState state{DeliveryState::Pending}; + std::uint64_t generation{0}; + std::uint32_t attempt{0}; + std::int64_t available_mono_ns{0}; + std::int64_t visibility_deadline_mono_ns{0}; + bool stuck_dlq{false}; + }; + + void append_message(std::string& out, const Message& m) + { + append_str(out, m.id); + append_u32(out, m.schema_version); + append_bytes(out, m.payload); + append_u32(out, static_cast(m.headers.size())); + for (const auto& [k, v] : m.headers) { + append_str(out, k); + append_str(out, v); + } + } + + [[nodiscard]] bool read_message(std::string_view& in, Message& m) + { + std::uint32_t hcount = 0; + if (!read_str(in, m.id) || !read_u32(in, m.schema_version) || + !read_bytes(in, m.payload) || !read_u32(in, hcount)) { + return false; + } + m.headers.clear(); + for (std::uint32_t i = 0; i < hcount; ++i) { + std::string k, v; + if (!read_str(in, k) || !read_str(in, v)) return false; + m.headers.emplace(std::move(k), std::move(v)); + } + return true; + } + + [[nodiscard]] std::string encode_queue(const PersistedQueue& q) + { + std::string out; + append_u32(out, kSchemaVersion); + append_str(out, q.config.name); + append_u8(out, static_cast(q.config.retention_policy)); + append_u32(out, q.config.retry.max_attempts); + append_i64(out, q.config.retry.base_delay.count()); + append_i64(out, q.config.retry.max_delay.count()); + append_u64(out, q.next_sequence); + return out; + } + + [[nodiscard]] Result decode_queue(std::string_view raw) + { + std::uint32_t ver = 0; + std::uint8_t rp = 0; + std::int64_t bms = 0, mms = 0; + PersistedQueue q{}; + if (!read_u32(raw, ver) || ver != kSchemaVersion || + !read_str(raw, q.config.name) || !read_u8(raw, rp) || + !read_u32(raw, q.config.retry.max_attempts) || + !read_i64(raw, bms) || !read_i64(raw, mms) || + !read_u64(raw, q.next_sequence) || !raw.empty()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::CorruptPayload, + "MessagingStorage: corrupt queue metadata")); + } + q.config.retention_policy = static_cast(rp); + q.config.retry.base_delay = std::chrono::milliseconds{bms}; + q.config.retry.max_delay = std::chrono::milliseconds{mms}; + return q; + } + + [[nodiscard]] std::string encode_group(const GroupConfig& g) + { + std::string out; + append_u32(out, kSchemaVersion); + append_str(out, g.name); + append_u8(out, static_cast(g.mode)); + append_i64(out, g.visibility_timeout.count()); + append_u64(out, static_cast(g.max_in_flight)); + return out; + } + + [[nodiscard]] Result decode_group(std::string_view raw) + { + std::uint32_t ver = 0; + std::uint8_t mode = 0; + std::int64_t vt = 0; + std::uint64_t mif = 0; + GroupConfig g{}; + if (!read_u32(raw, ver) || ver != kSchemaVersion || + !read_str(raw, g.name) || !read_u8(raw, mode) || + !read_i64(raw, vt) || !read_u64(raw, mif) || !raw.empty()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::CorruptPayload, + "MessagingStorage: corrupt group metadata")); + } + g.mode = static_cast(mode); + g.visibility_timeout = std::chrono::milliseconds{vt}; + g.max_in_flight = static_cast(mif); + return g; + } + + [[nodiscard]] std::string encode_pmsg(const PersistedMessage& pm) + { + std::string out; + append_u32(out, kSchemaVersion); + append_u64(out, pm.sequence); + append_i64(out, pm.published_utc_ms); + append_message(out, pm.message); + return out; + } + + [[nodiscard]] Result decode_pmsg(std::string_view raw) + { + std::uint32_t ver = 0; + PersistedMessage pm{}; + if (!read_u32(raw, ver) || ver != kSchemaVersion || + !read_u64(raw, pm.sequence) || + !read_i64(raw, pm.published_utc_ms) || + !read_message(raw, pm.message) || !raw.empty()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::CorruptPayload, + "MessagingStorage: corrupt message payload")); + } + return pm; + } + + [[nodiscard]] std::string encode_idem(const PersistedIdem& pi) + { + std::string out; + append_u32(out, kSchemaVersion); + append_u64(out, pi.sequence); + append_i64(out, pi.published_utc_ms); + return out; + } + + [[nodiscard]] Result decode_idem(std::string_view raw) + { + std::uint32_t ver = 0; + PersistedIdem pi{}; + if (!read_u32(raw, ver) || ver != kSchemaVersion || + !read_u64(raw, pi.sequence) || + !read_i64(raw, pi.published_utc_ms) || !raw.empty()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::CorruptPayload, + "MessagingStorage: corrupt idempotency record")); + } + return pi; + } + + [[nodiscard]] std::string encode_deliv(const PersistedDelivery& d) + { + std::string out; + append_u32(out, kSchemaVersion); + append_str(out, d.queue); + append_str(out, d.group); + append_u64(out, d.sequence); + append_str(out, d.message_id); + append_u8(out, static_cast(d.state)); + append_u64(out, d.generation); + append_u32(out, d.attempt); + append_i64(out, d.available_mono_ns); + append_i64(out, d.visibility_deadline_mono_ns); + append_u8(out, d.stuck_dlq ? 1U : 0U); + return out; + } + + [[nodiscard]] Result + decode_deliv(std::string_view raw) + { + std::uint32_t ver = 0; + std::uint8_t st = 0, stuck = 0; + PersistedDelivery d{}; + if (!read_u32(raw, ver) || ver != kSchemaVersion || + !read_str(raw, d.queue) || !read_str(raw, d.group) || + !read_u64(raw, d.sequence) || !read_str(raw, d.message_id) || + !read_u8(raw, st) || !read_u64(raw, d.generation) || + !read_u32(raw, d.attempt) || !read_i64(raw, d.available_mono_ns) || + !read_i64(raw, d.visibility_deadline_mono_ns) || + !read_u8(raw, stuck) || !raw.empty()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::CorruptPayload, + "MessagingStorage: corrupt delivery record")); + } + d.state = static_cast(st); + d.stuck_dlq = (stuck != 0U); + return d; + } + + [[nodiscard]] std::string encode_dlq(const DeadLetterEntry& e) + { + std::string out; + append_u32(out, kSchemaVersion); + append_str(out, e.queue); + append_str(out, e.group); + append_u64(out, e.sequence); + append_u32(out, e.attempts); + append_str(out, e.reason); + append_i64(out, e.dead_lettered_utc_ms); + append_message(out, e.message); + return out; + } + + [[nodiscard]] Result decode_dlq(std::string_view raw) + { + std::uint32_t ver = 0; + DeadLetterEntry e{}; + if (!read_u32(raw, ver) || ver != kSchemaVersion || + !read_str(raw, e.queue) || !read_str(raw, e.group) || + !read_u64(raw, e.sequence) || !read_u32(raw, e.attempts) || + !read_str(raw, e.reason) || + !read_i64(raw, e.dead_lettered_utc_ms) || + !read_message(raw, e.message) || !raw.empty()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::CorruptPayload, + "MessagingStorage: corrupt DLQ record")); + } + return e; + } + + [[nodiscard]] std::string queue_key(const std::string& pfx, + std::string_view q) + { + return pfx + "queue:" + std::string{q}; + } + + [[nodiscard]] std::string group_key(const std::string& pfx, + std::string_view q, + std::string_view g) + { + return pfx + "group:" + std::string{q} + "\x1F" + std::string{g}; + } + + [[nodiscard]] std::string msg_key(const std::string& pfx, + std::string_view q, + std::uint64_t seq) + { + return std::format("{}msg:{}\x1F{:020}", pfx, q, seq); + } + + [[nodiscard]] std::string idem_key(const std::string& pfx, + std::string_view q, + std::string_view msg_id) + { + return pfx + "idem:" + std::string{q} + "\x1F" + + std::string{msg_id}; + } + + [[nodiscard]] std::string deliv_key(const std::string& pfx, + std::string_view q, + std::string_view g, + std::uint64_t seq) + { + return std::format("{}deliv:{}\x1F{}\x1F{:020}", pfx, q, g, seq); + } + + [[nodiscard]] std::string dlq_key(const std::string& pfx, + std::string_view q, + std::string_view g, + std::uint64_t seq) + { + return std::format("{}dlq:{}\x1F{}\x1F{:020}", pfx, q, g, seq); + } + + [[nodiscard]] Error + map_write_failure(const Void::Storage::WriteFailure& wf) + { + if (wf.outcome == Void::Storage::Outcome::Unknown) { + return make_messaging_error( + MessagingErrorCode::UnknownOutcome, + "MessagingStorage: durable write outcome is unknown: " + + wf.cause.error.message()); + } + if (wf.cause.code == Void::Storage::StorageErrorCode::conflict) { + return make_messaging_error( + MessagingErrorCode::Conflict, + "MessagingStorage: conditional conflict: " + + wf.cause.error.message()); + } + return make_messaging_error( + MessagingErrorCode::PersistenceError, + "MessagingStorage: durable write failed: " + + wf.cause.error.message()); + } + + [[nodiscard]] Result> + scan_all(Void::Storage::Engine& engine, std::string_view prefix) + { + auto s = engine.snapshot(); + if (!s.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, s.error().message())); + } + auto cur = engine.scan(std::move(*s), + Void::Storage::ScanBounds::prefix(prefix)); + if (!cur.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, + cur.error().message())); + } + std::vector entries; + for (;;) { + auto page = cur->next_page(); + if (!page.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, + page.error().message())); + } + for (auto& e : page->entries) { + entries.push_back(std::move(e)); + } + if (!page->has_more) { + break; + } + } + return entries; + } + } // namespace + + struct StorageQueue::State { + Void::Storage::Engine* engine{nullptr}; + StorageQueueOptions opts{}; + + mutable std::mutex mu{}; + std::condition_variable cv{}; + bool closing{false}; + bool clock_healthy{true}; + std::size_t waiting_receives{0}; + + [[nodiscard]] Result total_bytes_locked() const + { + auto entries = scan_all(*engine, opts.key_prefix); + if (!entries.has_value()) { + return Void::Result::fail(entries.error()); + } + std::uint64_t total = 0; + for (const auto& e : *entries) { + total += e.key.size() + e.value.size(); + } + return total; + } + + [[nodiscard]] Result total_dlq_locked() const + { + auto entries = scan_all(*engine, opts.key_prefix + "dlq:"); + if (!entries.has_value()) { + return Void::Result::fail(entries.error()); + } + return entries->size(); + } + + [[nodiscard]] Result + gc_expired_idem_locked(std::int64_t now_utc_ms) + { + auto entries = scan_all(*engine, opts.key_prefix + "idem:"); + if (!entries.has_value()) { + return Void::Result::fail(entries.error()); + } + if (!clock_healthy) { + return entries->size(); + } + const std::int64_t cutoff = + now_utc_ms - opts.limits.idempotency_retention.count(); + std::size_t remaining = 0; + Void::Storage::Batch erase_b{}; + for (const auto& e : *entries) { + auto pi = decode_idem(Void::Storage::to_string_view(e.value)); + if (!pi.has_value()) return Void::Result::fail(pi.error()); + if (pi->published_utc_ms <= cutoff) { + erase_b.require_version(e.key, e.version); + erase_b.erase(e.key); + } else { + ++remaining; + } + } + if (!erase_b.empty()) { + auto wr = engine->write(std::move(erase_b), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + } + return remaining; + } + + [[nodiscard]] Result atomic_move_to_dlq_locked( + const std::string& dkey, Void::Storage::Sequence dver, + PersistedDelivery& d, std::string reason) + { + auto dlq_cnt = total_dlq_locked(); + if (!dlq_cnt.has_value()) { + return Void::Result::fail(dlq_cnt.error()); + } + if (*dlq_cnt >= opts.limits.max_dlq_messages) { + // Mark stuck_dlq durably and keep message intact — never + // drop data! + if (!d.stuck_dlq) { + d.stuck_dlq = true; + Void::Storage::Batch sb{}; + sb.require_version(dkey, dver); + sb.put(dkey, encode_deliv(d)); + (void)engine->write(std::move(sb), + Void::Storage::Durability::Sync); + } + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::DlqFull, + "MessagingStorage: DLQ full; message kept durable")); + } + + auto snap = engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, + snap.error().message())); + } + Message msg{}; + msg.id = d.message_id; + if (auto mv = engine->get( + *snap, msg_key(opts.key_prefix, d.queue, d.sequence)); + mv.has_value()) { + if (auto pm = decode_pmsg(mv->as_string_view()); + pm.has_value()) { + msg = std::move(pm->message); + } + } + + DeadLetterEntry dle{}; + dle.message = std::move(msg); + dle.queue = d.queue; + dle.group = d.group; + dle.sequence = d.sequence; + dle.attempts = d.attempt; + dle.reason = std::move(reason); + dle.dead_lettered_utc_ms = to_utc_ms(opts.civil_clock->now()); + + d.state = DeliveryState::DeadLetter; + d.stuck_dlq = false; + + // ONE atomic batch: insert DLQ entry + update source delivery! + const std::string k_dlq = + dlq_key(opts.key_prefix, d.queue, d.group, d.sequence); + Void::Storage::Batch batch{}; + batch.require_version(dkey, dver); + batch.require_absent(k_dlq); + batch.put(k_dlq, encode_dlq(dle)); + batch.put(dkey, encode_deliv(d)); + + auto wr = engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + [[nodiscard]] Result recover_in_flight_locked() + { + auto entries = scan_all(*engine, opts.key_prefix + "deliv:"); + if (!entries.has_value()) { + return Void::Result::fail(entries.error()); + } + std::size_t recovered = 0; + const std::int64_t now_ns = to_mono_ns(opts.monotonic_clock->now()); + for (const auto& e : *entries) { + auto d = decode_deliv(Void::Storage::to_string_view(e.value)); + if (!d.has_value()) return Void::Result::fail(d.error()); + if (d->state == DeliveryState::InFlight) { + d->state = DeliveryState::Pending; + // Bump generation so any pre-restart receipt is fenced + // as StaleReceipt, while preserving `attempt` count! + d->generation += 1U; + d->available_mono_ns = now_ns; + d->visibility_deadline_mono_ns = 0; + Void::Storage::Batch batch{}; + batch.require_version(e.key, e.version); + batch.put(e.key, + Void::Storage::to_byte_view(encode_deliv(*d))); + auto wr = engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail( + map_write_failure(wr.error())); + } + ++recovered; + } + } + return recovered; + } + + [[nodiscard]] Result reap_expired_locked() + { + auto entries = scan_all(*engine, opts.key_prefix + "deliv:"); + if (!entries.has_value()) { + return Void::Result::fail(entries.error()); + } + const std::int64_t now_ns = to_mono_ns(opts.monotonic_clock->now()); + std::size_t reaped = 0; + + for (const auto& e : *entries) { + auto d = decode_deliv(Void::Storage::to_string_view(e.value)); + if (!d.has_value()) return Void::Result::fail(d.error()); + if (d->state != DeliveryState::InFlight) { + continue; + } + if (now_ns < d->visibility_deadline_mono_ns) { + continue; + } + + auto snap = engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, + snap.error().message())); + } + auto qv = engine->get( + *snap, queue_key(opts.key_prefix, d->queue)); + if (!qv.has_value()) { + continue; + } + auto pq = decode_queue(qv->as_string_view()); + if (!pq.has_value()) return Void::Result::fail(pq.error()); + + const std::string dkey{ + Void::Storage::to_string_view(e.key)}; + if (d->attempt >= pq->config.retry.max_attempts) { + auto mv = atomic_move_to_dlq_locked( + dkey, e.version, *d, + "visibility timeout retry exhaustion"); + if (mv.has_value()) { + ++reaped; + } + } else { + const std::int64_t backoff_ms = + compute_retry_backoff_ms(pq->config.retry, + d->attempt, opts.rng); + d->state = DeliveryState::Pending; + d->available_mono_ns = now_ns + backoff_ms * 1000000LL; + d->visibility_deadline_mono_ns = 0; + Void::Storage::Batch batch{}; + batch.require_version(e.key, e.version); + batch.put(e.key, + Void::Storage::to_byte_view(encode_deliv(*d))); + auto wr = engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail( + map_write_failure(wr.error())); + } + ++reaped; + } + } + if (reaped > 0U) { + cv.notify_all(); + } + return reaped; + } + + [[nodiscard]] Result> + try_receive_locked(std::string_view queue, + std::string_view group) + { + auto snap = engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, + snap.error().message())); + } + auto qv = engine->get(*snap, queue_key(opts.key_prefix, queue)); + if (!qv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: queue not found")); + } + auto gv = + engine->get(*snap, group_key(opts.key_prefix, queue, group)); + if (!gv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: group not found")); + } + auto gcfg = decode_group(gv->as_string_view()); + if (!gcfg.has_value()) return Void::Result::fail(gcfg.error()); + + const std::string prefix = opts.key_prefix + "deliv:" + + std::string{queue} + "\x1F" + + std::string{group} + "\x1F"; + auto entries = scan_all(*engine, prefix); + if (!entries.has_value()) { + return Void::Result::fail(entries.error()); + } + + std::size_t in_flight = 0; + for (const auto& e : *entries) { + auto d = decode_deliv(Void::Storage::to_string_view(e.value)); + if (!d.has_value()) return Void::Result::fail(d.error()); + if (d->state == DeliveryState::InFlight) { + ++in_flight; + } + } + + const std::size_t eff_cap = + gcfg->mode == ConsumerMode::SingleActive + ? 1U + : std::min(gcfg->max_in_flight, + opts.limits.max_in_flight_per_group); + if (in_flight >= eff_cap) { + return std::optional{std::nullopt}; + } + + const auto now_tp = opts.monotonic_clock->now(); + const std::int64_t now_ns = to_mono_ns(now_tp); + + for (const auto& e : *entries) { + auto d = decode_deliv(Void::Storage::to_string_view(e.value)); + if (!d.has_value()) return Void::Result::fail(d.error()); + if (d->state == DeliveryState::Acked || + d->state == DeliveryState::DeadLetter) { + continue; + } + if (gcfg->mode == ConsumerMode::SingleActive) { + if (d->state == DeliveryState::InFlight || + d->available_mono_ns > now_ns) { + return std::optional{std::nullopt}; + } + } + if (d->state != DeliveryState::Pending || + d->available_mono_ns > now_ns) { + continue; + } + + auto mv = engine->get( + *snap, msg_key(opts.key_prefix, queue, d->sequence)); + if (!mv.has_value()) { + continue; + } + auto pm = decode_pmsg(mv->as_string_view()); + if (!pm.has_value()) return Void::Result::fail(pm.error()); + + const auto deadline_tp = now_tp + gcfg->visibility_timeout; + d->state = DeliveryState::InFlight; + d->generation += 1U; + d->attempt += 1U; + d->visibility_deadline_mono_ns = to_mono_ns(deadline_tp); + + // Persist generation + attempt BEFORE returning receipt! + Void::Storage::Batch batch{}; + batch.require_version(e.key, e.version); + batch.put(e.key, + Void::Storage::to_byte_view(encode_deliv(*d))); + auto wr = engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + + Delivery out{}; + out.message = std::move(pm->message); + out.receipt = Receipt{ + .queue = d->queue, + .group = d->group, + .message_id = d->message_id, + .sequence = d->sequence, + .generation = d->generation, + }; + out.attempt = d->attempt; + out.visibility_deadline = deadline_tp; + return std::optional{std::move(out)}; + } + return std::optional{std::nullopt}; + } + }; + + StorageQueue::StorageQueue(std::shared_ptr state) noexcept + : m_state(std::move(state)) + { + } + + StorageQueue::~StorageQueue() noexcept + { + if (m_state) { + { + std::lock_guard lk{m_state->mu}; + m_state->closing = true; + } + m_state->cv.notify_all(); + } + } + + StorageQueue::StorageQueue(StorageQueue&&) noexcept = default; + StorageQueue& StorageQueue::operator=(StorageQueue&&) noexcept = default; + + Result StorageQueue::open(Void::Storage::Engine& engine, + StorageQueueOptions options) + { + auto st = std::make_shared(); + st->engine = &engine; + st->opts = std::move(options); + if (st->opts.monotonic_clock == nullptr) { + st->opts.monotonic_clock = + &Void::Time::SystemMonotonicClock::instance(); + } + if (st->opts.civil_clock == nullptr) { + st->opts.civil_clock = &Void::Time::SystemCivilClock::instance(); + } + if (!st->opts.rng) { + auto prng = std::make_shared(0xA5A5A5A55A5A5A5AULL); + auto pmu = std::make_shared(); + st->opts.rng = [prng, pmu]() -> std::uint64_t { + std::lock_guard lk{*pmu}; + return (*prng)(); + }; + } + if (auto rec = st->recover_in_flight_locked(); !rec.has_value()) { + return Void::Result::fail(rec.error()); + } + return StorageQueue{std::move(st)}; + } + + Result StorageQueue::create_queue(QueueConfig config) + { + if (auto ok = validate_identifier(config.name, "queue"); !ok.has_value()) { + return ok; + } + if (config.retry.max_attempts == 0U || + config.retry.base_delay < std::chrono::milliseconds{0} || + config.retry.max_delay < config.retry.base_delay) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "MessagingStorage: invalid RetryPolicy")); + } + + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "MessagingStorage is closed")); + } + auto existing = scan_all(*m_state->engine, m_state->opts.key_prefix + "queue:"); + if (!existing.has_value()) return Void::Result::fail(existing.error()); + if (existing->size() >= m_state->opts.limits.max_queues) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Overloaded, + "MessagingStorage: max_queues reached")); + } + + const std::string key = queue_key(m_state->opts.key_prefix, config.name); + PersistedQueue pq{.config = std::move(config), .next_sequence = 1}; + Void::Storage::Batch batch{}; + batch.require_absent(key); + batch.put(key, encode_queue(pq)); + auto wr = m_state->engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return {}; + } + + Result StorageQueue::create_group(std::string_view queue, + GroupConfig config) + { + if (auto ok = validate_identifier(config.name, "group"); !ok.has_value()) { + return ok; + } + if (config.visibility_timeout <= std::chrono::milliseconds{0} || + config.max_in_flight == 0U) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "MessagingStorage: invalid group config")); + } + + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "MessagingStorage is closed")); + } + auto snap = m_state->engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, snap.error().message())); + } + if (!m_state->engine + ->get(*snap, queue_key(m_state->opts.key_prefix, queue)) + .has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: queue not found")); + } + + const std::string gpfx = + m_state->opts.key_prefix + "group:" + std::string{queue} + "\x1F"; + auto groups = scan_all(*m_state->engine, gpfx); + if (!groups.has_value()) return Void::Result::fail(groups.error()); + if (groups->size() >= m_state->opts.limits.max_groups_per_queue) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Overloaded, + "MessagingStorage: max_groups_per_queue reached")); + } + + const std::string gkey = + group_key(m_state->opts.key_prefix, queue, config.name); + const std::string mpfx = + m_state->opts.key_prefix + "msg:" + std::string{queue} + "\x1F"; + auto msgs = scan_all(*m_state->engine, mpfx); + if (!msgs.has_value()) return Void::Result::fail(msgs.error()); + + const std::int64_t now_ns = to_mono_ns(m_state->opts.monotonic_clock->now()); + Void::Storage::Batch batch{}; + batch.require_absent(gkey); + batch.put(gkey, encode_group(config)); + for (const auto& me : *msgs) { + auto pm = decode_pmsg(Void::Storage::to_string_view(me.value)); + if (!pm.has_value()) return Void::Result::fail(pm.error()); + PersistedDelivery pd{}; + pd.queue = std::string{queue}; + pd.group = config.name; + pd.sequence = pm->sequence; + pd.message_id = pm->message.id; + pd.state = DeliveryState::Pending; + pd.available_mono_ns = now_ns; + const std::string dk = + deliv_key(m_state->opts.key_prefix, queue, config.name, + pm->sequence); + batch.require_absent(dk); + batch.put(dk, encode_deliv(pd)); + } + + auto wr = m_state->engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + m_state->cv.notify_all(); + return {}; + } + + Result + StorageQueue::publish(std::string_view queue, Message message, + PublishDurability durability, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, "MessagingStorage::publish cancelled")); + } + if (auto vm = validate_message(message, m_state->opts.limits); + !vm.has_value()) { + return Void::Result::fail(vm.error()); + } + + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "MessagingStorage is closed")); + } + + const std::int64_t now_utc = to_utc_ms(m_state->opts.civil_clock->now()); + auto idem_count = m_state->gc_expired_idem_locked(now_utc); + if (!idem_count.has_value()) { + return Void::Result::fail(idem_count.error()); + } + + auto snap = m_state->engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, snap.error().message())); + } + + const std::string qkey = queue_key(m_state->opts.key_prefix, queue); + auto qval = m_state->engine->get(*snap, qkey); + if (!qval.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: queue not found")); + } + auto pq = decode_queue(qval->as_string_view()); + if (!pq.has_value()) return Void::Result::fail(pq.error()); + + // Check publish idempotency ledger. + const std::string ikey = + idem_key(m_state->opts.key_prefix, queue, message.id); + if (auto iv = m_state->engine->get(*snap, ikey); iv.has_value()) { + auto pi = decode_idem(iv->as_string_view()); + if (!pi.has_value()) return Void::Result::fail(pi.error()); + return PublishReceipt{ + .queue = pq->config.name, + .message_id = message.id, + .sequence = pi->sequence, + .durability = durability, + .deduplicated = true, + }; + } + if (*idem_count >= m_state->opts.limits.max_idempotency_entries) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::IdempotencyCapacityExceeded, + "MessagingStorage: idempotency table at capacity; refusing " + "silent eviction")); + } + + // Enforce persistent byte quota (BlockAtQuota blocks publish without + // dropping unread work). + auto used = m_state->total_bytes_locked(); + if (!used.has_value()) return Void::Result::fail(used.error()); + const std::uint64_t add_est = estimate_message_bytes(message); + if (*used + add_est > m_state->opts.limits.persistent_quota_bytes) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::QuotaExceeded, + "MessagingStorage: persistent quota exceeded; admission " + "blocked")); + } + + const std::string gpfx = + m_state->opts.key_prefix + "group:" + std::string{queue} + "\x1F"; + auto groups = scan_all(*m_state->engine, gpfx); + if (!groups.has_value()) return Void::Result::fail(groups.error()); + + const std::uint64_t seq = pq->next_sequence++; + const std::string msg_id = message.id; + const std::int64_t now_ns = to_mono_ns(m_state->opts.monotonic_clock->now()); + + PersistedMessage pm{ + .sequence = seq, + .published_utc_ms = now_utc, + .message = std::move(message), + }; + PersistedIdem pi{ + .sequence = seq, + .published_utc_ms = now_utc, + }; + + Void::Storage::Batch batch{}; + batch.require_version(qkey, qval->version); + batch.put(qkey, encode_queue(*pq)); + const std::string mkey = msg_key(m_state->opts.key_prefix, queue, seq); + batch.require_absent(mkey); + batch.put(mkey, encode_pmsg(pm)); + batch.require_absent(ikey); + batch.put(ikey, encode_idem(pi)); + + for (const auto& ge : *groups) { + auto gcfg = decode_group(Void::Storage::to_string_view(ge.value)); + if (!gcfg.has_value()) return Void::Result::fail(gcfg.error()); + PersistedDelivery pd{}; + pd.queue = pq->config.name; + pd.group = gcfg->name; + pd.sequence = seq; + pd.message_id = msg_id; + pd.state = DeliveryState::Pending; + pd.available_mono_ns = now_ns; + const std::string dk = + deliv_key(m_state->opts.key_prefix, queue, gcfg->name, seq); + batch.require_absent(dk); + batch.put(dk, encode_deliv(pd)); + } + + const auto stor_dur = + durability == PublishDurability::Durable + ? Void::Storage::Durability::Sync + : Void::Storage::Durability::Buffered; + auto wr = m_state->engine->write(std::move(batch), stor_dur); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + + m_state->cv.notify_all(); + return PublishReceipt{ + .queue = pq->config.name, + .message_id = msg_id, + .sequence = seq, + .durability = durability, + .deduplicated = false, + }; + } + + Result> + StorageQueue::try_receive(std::string_view queue, + std::string_view group) + { + std::lock_guard lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "MessagingStorage is closed")); + } + if (auto rp = m_state->reap_expired_locked(); !rp.has_value()) { + return Void::Result::fail(rp.error()); + } + return m_state->try_receive_locked(queue, group); + } + + Result StorageQueue::receive( + std::string_view queue, std::string_view group, + Void::Async::OperationOptions options) + { + std::unique_lock lk{m_state->mu}; + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, "MessagingStorage is closed")); + } + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "MessagingStorage::receive cancelled")); + } + if (auto rp = m_state->reap_expired_locked(); !rp.has_value()) { + return Void::Result::fail(rp.error()); + } + auto imm = m_state->try_receive_locked(queue, group); + if (!imm.has_value()) return Void::Result::fail(imm.error()); + if (imm->has_value()) return std::move(**imm); + + if (m_state->waiting_receives >= + m_state->opts.limits.max_waiting_receives) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Overloaded, + "MessagingStorage: max_waiting_receives reached")); + } + + ++m_state->waiting_receives; + struct Guard { + std::size_t& c; + ~Guard() noexcept { --c; } + } wg{m_state->waiting_receives}; + + std::stop_callback scb(options.stop, + [this] { m_state->cv.notify_all(); }); + for (;;) { + if (m_state->closing) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Closed, + "MessagingStorage closed while waiting")); + } + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "MessagingStorage::receive cancelled")); + } + if (auto rp = m_state->reap_expired_locked(); !rp.has_value()) { + return Void::Result::fail(rp.error()); + } + auto polled = m_state->try_receive_locked(queue, group); + if (!polled.has_value()) return Void::Result::fail(polled.error()); + if (polled->has_value()) return std::move(**polled); + + if (options.deadline.has_value()) { + const auto rem = Void::Time::remaining_until( + *m_state->opts.monotonic_clock, *options.deadline); + if (rem <= std::chrono::nanoseconds{0}) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Timeout, + "MessagingStorage::receive timeout")); + } + const auto slice = + std::min(rem, std::chrono::duration_cast< + std::chrono::nanoseconds>( + std::chrono::milliseconds{5})); + m_state->cv.wait_for(lk, slice); + } else { + m_state->cv.wait_for(lk, std::chrono::milliseconds{5}); + } + } + } + + Result StorageQueue::ack(const Receipt& receipt, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, "MessagingStorage::ack cancelled")); + } + std::lock_guard lk{m_state->mu}; + auto snap = m_state->engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, snap.error().message())); + } + const std::string dkey = deliv_key( + m_state->opts.key_prefix, receipt.queue, receipt.group, + receipt.sequence); + auto dv = m_state->engine->get(*snap, dkey); + if (!dv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage::ack receipt not found")); + } + auto d = decode_deliv(dv->as_string_view()); + if (!d.has_value()) return Void::Result::fail(d.error()); + + // Repeat ack of the same acknowledged receipt -> idempotent OK! + if (d->state == DeliveryState::Acked && + d->generation == receipt.generation) { + return {}; + } + if (d->state != DeliveryState::InFlight || + d->generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "MessagingStorage::ack stale receipt generation")); + } + + d->state = DeliveryState::Acked; + Void::Storage::Batch batch{}; + batch.require_version(dkey, dv->version); + batch.put(dkey, encode_deliv(*d)); + auto wr = m_state->engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + m_state->cv.notify_all(); + return {}; + } + + Result StorageQueue::nack( + const Receipt& receipt, std::optional delay, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "MessagingStorage::nack cancelled")); + } + std::lock_guard lk{m_state->mu}; + auto snap = m_state->engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, snap.error().message())); + } + const std::string qkey = + queue_key(m_state->opts.key_prefix, receipt.queue); + auto qv = m_state->engine->get(*snap, qkey); + if (!qv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: queue not found")); + } + auto pq = decode_queue(qv->as_string_view()); + if (!pq.has_value()) return Void::Result::fail(pq.error()); + + const std::string dkey = deliv_key( + m_state->opts.key_prefix, receipt.queue, receipt.group, + receipt.sequence); + auto dv = m_state->engine->get(*snap, dkey); + if (!dv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage::nack receipt not found")); + } + auto d = decode_deliv(dv->as_string_view()); + if (!d.has_value()) return Void::Result::fail(d.error()); + + if (d->state != DeliveryState::InFlight || + d->generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "MessagingStorage::nack stale receipt generation")); + } + + if (d->attempt >= pq->config.retry.max_attempts) { + auto mv = m_state->atomic_move_to_dlq_locked( + dkey, dv->version, *d, "nack retry exhaustion"); + m_state->cv.notify_all(); + return mv; + } + + const std::int64_t wait_ms = + delay.has_value() + ? std::max(0LL, delay->count()) + : compute_retry_backoff_ms(pq->config.retry, d->attempt, + m_state->opts.rng); + d->state = DeliveryState::Pending; + d->available_mono_ns = + to_mono_ns(m_state->opts.monotonic_clock->now()) + + wait_ms * 1000000LL; + d->visibility_deadline_mono_ns = 0; + + Void::Storage::Batch batch{}; + batch.require_version(dkey, dv->version); + batch.put(dkey, encode_deliv(*d)); + auto wr = m_state->engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + m_state->cv.notify_all(); + return {}; + } + + Result + StorageQueue::extend_visibility(const Receipt& receipt, + std::chrono::milliseconds extension, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "MessagingStorage::extend_visibility cancelled")); + } + if (extension <= std::chrono::milliseconds{0} || + extension > m_state->opts.limits.max_visibility_extension) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::InvalidArgument, + "MessagingStorage::extend_visibility out of range")); + } + std::lock_guard lk{m_state->mu}; + auto snap = m_state->engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, snap.error().message())); + } + const std::string dkey = deliv_key( + m_state->opts.key_prefix, receipt.queue, receipt.group, + receipt.sequence); + auto dv = m_state->engine->get(*snap, dkey); + if (!dv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: receipt not found")); + } + auto d = decode_deliv(dv->as_string_view()); + if (!d.has_value()) return Void::Result::fail(d.error()); + if (d->state != DeliveryState::InFlight || + d->generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "MessagingStorage: stale receipt on extend_visibility")); + } + const auto new_dl = m_state->opts.monotonic_clock->now() + extension; + d->visibility_deadline_mono_ns = to_mono_ns(new_dl); + Void::Storage::Batch batch{}; + batch.require_version(dkey, dv->version); + batch.put(dkey, encode_deliv(*d)); + auto wr = m_state->engine->write(std::move(batch), + Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + return new_dl; + } + + Result StorageQueue::quarantine_corrupt( + const Receipt& receipt, std::string reason, + Void::Async::OperationOptions options) + { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::Cancelled, + "MessagingStorage::quarantine_corrupt cancelled")); + } + std::lock_guard lk{m_state->mu}; + auto snap = m_state->engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, snap.error().message())); + } + const std::string dkey = deliv_key( + m_state->opts.key_prefix, receipt.queue, receipt.group, + receipt.sequence); + auto dv = m_state->engine->get(*snap, dkey); + if (!dv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: receipt not found")); + } + auto d = decode_deliv(dv->as_string_view()); + if (!d.has_value()) return Void::Result::fail(d.error()); + if (d->state != DeliveryState::InFlight || + d->generation != receipt.generation) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::StaleReceipt, + "MessagingStorage: stale receipt on quarantine")); + } + auto mv = m_state->atomic_move_to_dlq_locked( + dkey, dv->version, *d, + reason.empty() ? std::string{"corrupt payload"} : std::move(reason)); + m_state->cv.notify_all(); + return mv; + } + + Result + StorageQueue::query_receipt(const Receipt& receipt) const + { + std::lock_guard lk{m_state->mu}; + auto snap = m_state->engine->snapshot(); + if (!snap.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::PersistenceError, snap.error().message())); + } + const std::string dkey = deliv_key( + m_state->opts.key_prefix, receipt.queue, receipt.group, + receipt.sequence); + auto dv = m_state->engine->get(*snap, dkey); + if (!dv.has_value()) { + return Void::Result::fail(make_messaging_error( + MessagingErrorCode::NotFound, + "MessagingStorage: receipt not found")); + } + auto d = decode_deliv(dv->as_string_view()); + if (!d.has_value()) return Void::Result::fail(d.error()); + return d->state; + } + + Result> + StorageQueue::list_dead_letters(std::string_view queue, + std::string_view group, + std::size_t limit) const + { + std::lock_guard lk{m_state->mu}; + const std::string pfx = m_state->opts.key_prefix + "dlq:" + + std::string{queue} + "\x1F" + + std::string{group} + "\x1F"; + auto entries = scan_all(*m_state->engine, pfx); + if (!entries.has_value()) return Void::Result::fail(entries.error()); + std::vector out; + const std::size_t n = std::min(limit, entries->size()); + out.reserve(n); + for (std::size_t i = 0; i < n; ++i) { + auto dle = + decode_dlq(Void::Storage::to_string_view((*entries)[i].value)); + if (!dle.has_value()) return Void::Result::fail(dle.error()); + out.push_back(std::move(*dle)); + } + return out; + } + + std::size_t StorageQueue::stuck_dlq_count(std::string_view queue, + std::string_view group) const + noexcept + { + std::lock_guard lk{m_state->mu}; + const std::string pfx = m_state->opts.key_prefix + "deliv:" + + std::string{queue} + "\x1F" + + std::string{group} + "\x1F"; + auto entries = scan_all(*m_state->engine, pfx); + if (!entries.has_value()) return 0; + std::size_t stuck = 0; + for (const auto& e : *entries) { + if (auto d = decode_deliv(Void::Storage::to_string_view(e.value)); + d.has_value() && d->stuck_dlq) { + ++stuck; + } + } + return stuck; + } + + Result StorageQueue::reap_expired_visibility() + { + std::lock_guard lk{m_state->mu}; + return m_state->reap_expired_locked(); + } + + Result StorageQueue::expire_retention() + { + std::lock_guard lk{m_state->mu}; + if (!m_state->clock_healthy) { + return 0U; + } + const std::int64_t cutoff = + to_utc_ms(m_state->opts.civil_clock->now()) - + m_state->opts.limits.logical_retention.count(); + + auto qentries = scan_all(*m_state->engine, m_state->opts.key_prefix + "queue:"); + if (!qentries.has_value()) return Void::Result::fail(qentries.error()); + + std::size_t expired = 0; + for (const auto& qe : *qentries) { + auto pq = decode_queue(Void::Storage::to_string_view(qe.value)); + if (!pq.has_value()) return Void::Result::fail(pq.error()); + + const std::string mpfx = + m_state->opts.key_prefix + "msg:" + pq->config.name + "\x1F"; + auto msgs = scan_all(*m_state->engine, mpfx); + if (!msgs.has_value()) return Void::Result::fail(msgs.error()); + + const std::string dpfx = + m_state->opts.key_prefix + "deliv:" + pq->config.name + "\x1F"; + auto delivs = scan_all(*m_state->engine, dpfx); + if (!delivs.has_value()) return Void::Result::fail(delivs.error()); + + for (const auto& me : *msgs) { + auto pm = decode_pmsg(Void::Storage::to_string_view(me.value)); + if (!pm.has_value()) return Void::Result::fail(pm.error()); + if (pm->published_utc_ms > cutoff) { + continue; + } + bool all_terminal = true; + bool any_in_flight = false; + std::vector matching_delivs; + for (const auto& de : *delivs) { + auto pd = decode_deliv(Void::Storage::to_string_view(de.value)); + if (!pd.has_value()) return Void::Result::fail(pd.error()); + if (pd->sequence != pm->sequence) continue; + matching_delivs.push_back(&de); + if (pd->state == DeliveryState::InFlight) { + any_in_flight = true; + all_terminal = false; + } else if (pd->state == DeliveryState::Pending) { + all_terminal = false; + } + } + const bool can_drop = + !any_in_flight && + (all_terminal || + pq->config.retention_policy == + RetentionPolicy::DropOldestLossy); + if (!can_drop) { + continue; + } + Void::Storage::Batch batch{}; + batch.require_version(me.key, me.version); + batch.erase(me.key); + for (const auto* de : matching_delivs) { + batch.require_version(de->key, de->version); + batch.erase(de->key); + } + auto wr = m_state->engine->write( + std::move(batch), Void::Storage::Durability::Sync); + if (!wr.has_value()) { + return Void::Result::fail(map_write_failure(wr.error())); + } + ++expired; + } + } + return expired; + } + + void StorageQueue::set_clock_healthy(bool healthy) noexcept + { + std::lock_guard lk{m_state->mu}; + m_state->clock_healthy = healthy; + } + + Result + StorageQueue::close_and_join(Void::Async::OperationOptions options) + { + std::unique_lock lk{m_state->mu}; + m_state->closing = true; + m_state->cv.notify_all(); + + auto count_in_flight = [&]() -> std::size_t { + auto entries = + scan_all(*m_state->engine, m_state->opts.key_prefix + "deliv:"); + if (!entries.has_value()) return 0; + std::size_t n = 0; + for (const auto& e : *entries) { + if (auto d = + decode_deliv(Void::Storage::to_string_view(e.value)); + d.has_value() && d->state == DeliveryState::InFlight) { + ++n; + } + } + return n; + }; + + const auto deadline = options.deadline.value_or( + m_state->opts.monotonic_clock->now() + + m_state->opts.limits.shutdown_drain_timeout); + while (count_in_flight() > 0U || m_state->waiting_receives > 0U) { + const auto rem = Void::Time::remaining_until( + *m_state->opts.monotonic_clock, deadline); + if (rem <= std::chrono::nanoseconds{0}) { + const std::size_t live = count_in_flight(); + return ShutdownReport{ + .complete = (live == 0U && m_state->waiting_receives == 0U), + .remaining_in_flight = live, + }; + } + const auto slice = + std::min(rem, std::chrono::duration_cast< + std::chrono::nanoseconds>( + std::chrono::milliseconds{5})); + m_state->cv.wait_for(lk, slice); + } + return ShutdownReport{.complete = true, .remaining_in_flight = 0}; + } + + Result StorageQueue::stats() const + { + std::lock_guard lk{m_state->mu}; + QueueStats s{}; + auto qs = scan_all(*m_state->engine, m_state->opts.key_prefix + "queue:"); + if (!qs.has_value()) return Void::Result::fail(qs.error()); + s.queues = qs->size(); + + auto ds = scan_all(*m_state->engine, m_state->opts.key_prefix + "deliv:"); + if (!ds.has_value()) return Void::Result::fail(ds.error()); + for (const auto& e : *ds) { + auto d = decode_deliv(Void::Storage::to_string_view(e.value)); + if (!d.has_value()) return Void::Result::fail(d.error()); + if (d->stuck_dlq) ++s.stuck_dlq; + switch (d->state) { + case DeliveryState::Pending: ++s.pending; break; + case DeliveryState::InFlight: ++s.in_flight; break; + case DeliveryState::Acked: ++s.acked; break; + case DeliveryState::DeadLetter: break; + } + } + + auto dlqs = scan_all(*m_state->engine, m_state->opts.key_prefix + "dlq:"); + if (!dlqs.has_value()) return Void::Result::fail(dlqs.error()); + s.dead_letter = dlqs->size(); + + auto idems = scan_all(*m_state->engine, m_state->opts.key_prefix + "idem:"); + if (!idems.has_value()) return Void::Result::fail(idems.error()); + s.idempotency_entries = idems->size(); + + auto bytes = m_state->total_bytes_locked(); + if (!bytes.has_value()) return Void::Result::fail(bytes.error()); + s.retained_bytes = *bytes; + return s; + } + +} // namespace Void::MessagingStorage diff --git a/src/MessagingStorage/module.cmake b/src/MessagingStorage/module.cmake new file mode 100644 index 0000000..977a086 --- /dev/null +++ b/src/MessagingStorage/module.cmake @@ -0,0 +1,3 @@ +void_add_module(MessagingStorage + INTERNAL_DEPS Messaging Storage +) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index d358da8..1bef59a 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -328,6 +328,11 @@ 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) diff --git a/tests/package/MessagingOnly/CMakeLists.txt b/tests/package/MessagingOnly/CMakeLists.txt new file mode 100644 index 0000000..717f198 --- /dev/null +++ b/tests/package/MessagingOnly/CMakeLists.txt @@ -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) diff --git a/tests/package/MessagingOnly/main.cpp b/tests/package/MessagingOnly/main.cpp new file mode 100644 index 0000000..72f6cc1 --- /dev/null +++ b/tests/package/MessagingOnly/main.cpp @@ -0,0 +1,33 @@ +#include + +#include + +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; +} diff --git a/tests/standalone/Messaging/Messaging.cpp b/tests/standalone/Messaging/Messaging.cpp new file mode 100644 index 0000000..8b96c79 --- /dev/null +++ b/tests/standalone/Messaging/Messaging.cpp @@ -0,0 +1,148 @@ +#include +#include +#include + +#include +#include +#include +#include + +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(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(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(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); +} diff --git a/tests/standalone/MessagingRpc/RpcAdapter.cpp b/tests/standalone/MessagingRpc/RpcAdapter.cpp new file mode 100644 index 0000000..56e11b7 --- /dev/null +++ b/tests/standalone/MessagingRpc/RpcAdapter.cpp @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include + +#include + +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(); +} diff --git a/tests/standalone/MessagingStorage/StorageQueue.cpp b/tests/standalone/MessagingStorage/StorageQueue.cpp new file mode 100644 index 0000000..0e3fc0c --- /dev/null +++ b/tests/standalone/MessagingStorage/StorageQueue.cpp @@ -0,0 +1,215 @@ +#include +#include +#include +#include +#include +#include + +#include +#include + +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(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(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(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( + 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()); +} From f3f66e0c8c5889c69b934156afc833b70a5833f2 Mon Sep 17 00:00:00 2001 From: faumaray Date: Fri, 27 Nov 2026 05:55:45 +0300 Subject: [PATCH 5/5] docs(workflow): record Wave 10 P3 Discovery, Scheduler, and Messaging verification --- docs/agent-workflow/STATE.md | 25 +++++++++++++++++++------ docs/agent-workflow/TASKS.md | 8 ++++++++ docs/agent-workflow/VERIFICATION.md | 7 +++++++ 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 27855f2..1232a2b 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -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`). diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index e7c0657..4666440 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -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 diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index efe6f43..47511b4 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -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 |