Files
Library/src/Discovery/Catalog.cpp
T

1589 lines
45 KiB
C++

#include <Void/Discovery/Catalog.hpp>
#include <Void/Core/Hash.hpp>
#include <algorithm>
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <coroutine>
#include <deque>
#include <limits>
#include <map>
#include <mutex>
#include <set>
#include <thread>
#include <utility>
#include <vector>
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<unsigned char>(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<std::size_t>* 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<std::pair<WatchEvent, std::size_t>> 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<void> 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<promise_type>::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<promise_type> handle{};
};
DetachedWatchPump run_watch_pump(std::shared_ptr<WatchNode> 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<WatchNode>& 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<void> 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::string,
std::map<std::string, StoredRecord, std::less<>>,
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<Error> provider_error{};
bool closed{false};
std::map<std::uint64_t, std::shared_ptr<WatchNode>> watches{};
std::atomic<std::size_t> 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<std::shared_ptr<WatchNode>>
matching_watches_locked(std::string_view service) const
{
std::vector<std::shared_ptr<WatchNode>> 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<Catalog::State>(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<Void::Time::MonotonicClock::time_point>
Registration::expires_at() const noexcept
{
if (!m_active || !m_leased || !m_catalog_state) {
return std::nullopt;
}
auto state = std::static_pointer_cast<Catalog::State>(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<Void::Time::MonotonicClock::time_point> 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<Catalog::State>(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<Catalog::State>(m_catalog_state);
m_catalog_state.reset();
std::vector<std::shared_ptr<WatchNode>> 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<WatchNode>(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<WatchNode>(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<WatchNode>(m_watch_node);
node->cancel();
}
if (m_catalog_state && m_watch_id != 0) {
auto state =
std::static_pointer_cast<Catalog::State>(m_catalog_state);
std::lock_guard lk{state->mu};
state->watches.erase(m_watch_id);
}
m_watch_id = 0;
}
Result<void> WatchHandle::join() noexcept
{
if (!m_watch_node) {
return {};
}
auto node = std::static_pointer_cast<WatchNode>(m_watch_node);
return node->join();
}
bool WatchHandle::deliver_one()
{
if (!m_watch_node) {
return false;
}
auto node = std::static_pointer_cast<WatchNode>(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<WatchNode>(m_watch_node);
return node->deliver_all();
}
// ── Catalog ───────────────────────────────────────────────────────────────
Catalog::Catalog(CatalogOptions options)
: m_state(std::make_shared<State>())
{
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<std::shared_ptr<WatchNode>> 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<std::uint64_t>
Catalog::replace_static(std::vector<EndpointRecord> 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::string,
std::map<std::string, EndpointRecord, std::less<>>,
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<WatchNode> node{};
WatchEvent event{};
Snapshot full_snap{};
};
std::vector<WatchDelivery> 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::string,
std::map<std::string, StoredRecord, std::less<>>,
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<std::string, std::less<>> 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<Error> 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<Snapshot> 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<Registration> 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<std::shared_ptr<WatchNode>> 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<WatchHandle> 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<WatchNode>();
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<WatchNode> node{};
WatchEvent event{};
Snapshot full_snap{};
};
std::vector<WatchDelivery> 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::string, std::vector<std::string>, 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<void> Catalog::shutdown_and_join() noexcept
{
if (!m_state) {
return {};
}
std::vector<std::shared_ptr<WatchNode>> 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(&registration),
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<bool> 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<EndpointRecord>
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<std::int64_t>::min();
for (std::size_t i = 0; i < snapshot.records.size(); ++i) {
const auto& rec = snapshot.records[i];
const auto w = static_cast<std::int64_t>(
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<EndpointRecord>
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<double>((h >> 11U) + 1ULL)) /
static_cast<double>((1ULL << 53U) + 1ULL);
const double neg_log = -std::log(u);
const double weight =
static_cast<double>(rec.weight > 0U ? rec.weight : 1U);
const double score =
neg_log > 0.0 ? (weight / neg_log)
: std::numeric_limits<double>::max();
if (score > best_score) {
best_score = score;
best_idx = i;
}
}
return snapshot.records[best_idx];
}
} // namespace Void::Discovery