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(); +}