Skip to main content

toolkit/runtime/
gear_manager.rs

1//! Gear Manager - tracks and manages all live gear instances in the runtime
2
3use dashmap::DashMap;
4use std::collections::{BTreeMap, HashMap};
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7use uuid::Uuid;
8
9/// Represents an endpoint where a gear instance can be reached
10#[derive(Clone, Debug, PartialEq, Eq, Hash)]
11pub struct Endpoint {
12    pub uri: String,
13}
14
15/// Typed view of an endpoint for parsing and matching
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum EndpointKind {
18    /// TCP endpoint with resolved socket address
19    Tcp(std::net::SocketAddr),
20    /// Unix domain socket with file path
21    Uds(std::path::PathBuf),
22    /// Other/unparsed endpoint URI
23    Other(String),
24}
25
26impl Endpoint {
27    pub fn from_uri<S: Into<String>>(s: S) -> Self {
28        Self { uri: s.into() }
29    }
30
31    pub fn uds(path: impl AsRef<std::path::Path>) -> Self {
32        Self {
33            uri: format!("unix://{}", path.as_ref().display()),
34        }
35    }
36
37    #[must_use]
38    pub fn http(host: &str, port: u16) -> Self {
39        Self {
40            uri: format!("http://{host}:{port}"),
41        }
42    }
43
44    #[must_use]
45    pub fn https(host: &str, port: u16) -> Self {
46        Self {
47            uri: format!("https://{host}:{port}"),
48        }
49    }
50
51    /// Parse the endpoint URI into a typed view
52    #[must_use]
53    pub fn kind(&self) -> EndpointKind {
54        if let Some(rest) = self.uri.strip_prefix("unix://") {
55            return EndpointKind::Uds(std::path::PathBuf::from(rest));
56        }
57        if let Some(rest) = self.uri.strip_prefix("http://")
58            && let Ok(addr) = rest.parse::<std::net::SocketAddr>()
59        {
60            return EndpointKind::Tcp(addr);
61        }
62        if let Some(rest) = self.uri.strip_prefix("https://")
63            && let Ok(addr) = rest.parse::<std::net::SocketAddr>()
64        {
65            return EndpointKind::Tcp(addr);
66        }
67        EndpointKind::Other(self.uri.clone())
68    }
69}
70
71/// Observable state of an instance, *derived* from its lease and reported
72/// state at read time (`cpt-cf-adr-directory-persistence-and-replication`).
73/// The directory never writes this; it is computed by
74/// [`GearInstance::observed_state_at`] from the
75/// [`ReportedState`] the instance last declared and whether its lease is still
76/// valid.
77///
78/// Only [`Healthy`](Self::Healthy) (and the deprecated [`Ready`](Self::Ready),
79/// kept for wire compatibility and still read as serving) are **serving**.
80/// [`Quarantined`](Self::Quarantined) now means *the lease expired* (missed
81/// heartbeats), not a failing readiness check — a failing readiness check is
82/// reported as `Starting` and reads as [`Registered`](Self::Registered). A
83/// record whose lease expired more than `grace` ago is not observable at all
84/// (see [`observed_state_at`](GearInstance::observed_state_at)).
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum InstanceState {
87    Registered,
88    /// Deprecated: no longer produced by the directory, kept in the enum for
89    /// wire compatibility and still treated as serving when read.
90    Ready,
91    Healthy,
92    Quarantined,
93    Draining,
94}
95
96/// What an instance declares about itself in `RegisterInstance` / `Heartbeat`.
97/// The directory derives the observable [`InstanceState`] from this
98/// plus the lease; it is the only liveness signal an instance writes.
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
100pub enum ReportedState {
101    /// Not yet serving (starting up, or failing its readiness check).
102    #[default]
103    Starting,
104    /// Serving and heartbeating.
105    Serving,
106    /// Gracefully draining; upstreams should stop routing new work.
107    Draining,
108}
109
110/// The directory's lease policy: how long a registration/heartbeat keeps an
111/// instance observable (`ttl`), and the extra window it reads as
112/// [`InstanceState::Quarantined`] before becoming unobservable (`grace`).
113#[derive(Clone, Copy, Debug)]
114struct LeasePolicy {
115    ttl: Duration,
116    grace: Duration,
117}
118
119/// Runtime liveness of an instance (guarded by `RwLock` for safe mutation).
120///
121/// Holds the instance's **lease**: `lease_expires_at` is set to `now + ttl` by
122/// every registration and heartbeat, and the observable state is computed from
123/// it at read time rather than written by a background task.
124#[derive(Clone, Debug)]
125struct InstanceRuntimeState {
126    /// Instant the lease expires: last registration/heartbeat `+ ttl`.
127    lease_expires_at: Instant,
128    /// Window after `lease_expires_at` during which the record reads as
129    /// [`InstanceState::Quarantined`] before becoming unobservable.
130    grace: Duration,
131    /// The state the instance last reported about itself.
132    reported: ReportedState,
133}
134
135/// Represents a single instance of a gear
136#[derive(Debug)]
137#[must_use]
138pub struct GearInstance {
139    pub gear: String,
140    pub instance_id: Uuid,
141    pub control: Option<Endpoint>,
142    pub grpc_services: HashMap<String, Endpoint>,
143    pub version: Option<String>,
144    pub rest_endpoint: Option<Endpoint>,
145    pub openapi_spec: Option<String>,
146    /// Stable addressing labels (k8s `matchLabels` style) advertised by this
147    /// instance, used for label-based instance selection.
148    pub labels: BTreeMap<String, String>,
149    /// State the registrant declares about itself, or `None` when unspecified
150    /// (`optional reported_state`). On a *new* registration `None`
151    /// means [`ReportedState::Starting`]; on a *re-registration* `None` means
152    /// "keep whatever the record already reports", so a periodic self-heal that
153    /// omits the field never knocks a serving instance back to `Starting`.
154    pub reported_state: Option<ReportedState>,
155    inner: Arc<parking_lot::RwLock<InstanceRuntimeState>>,
156}
157
158impl Clone for GearInstance {
159    fn clone(&self) -> Self {
160        Self {
161            gear: self.gear.clone(),
162            instance_id: self.instance_id,
163            control: self.control.clone(),
164            grpc_services: self.grpc_services.clone(),
165            version: self.version.clone(),
166            rest_endpoint: self.rest_endpoint.clone(),
167            openapi_spec: self.openapi_spec.clone(),
168            labels: self.labels.clone(),
169            reported_state: self.reported_state,
170            inner: Arc::clone(&self.inner),
171        }
172    }
173}
174
175impl GearInstance {
176    /// Build a new instance record using `other`'s metadata but preserving
177    /// `self`'s `inner` runtime-state lock. This makes re-registration atomic:
178    /// a concurrent `heartbeat` keeps writing the same state object instead of
179    /// racing with a copied/swapped `InstanceRuntimeState`.
180    ///
181    /// One process registers an instance from two places: the gRPC hub with
182    /// its services, the host with its REST endpoint and `OpenAPI` spec. Each
183    /// writes only its own half, and they race, so an absent half keeps the
184    /// stored one instead of clearing it, as labels do.
185    fn with_metadata_of(&self, other: &GearInstance) -> GearInstance {
186        GearInstance {
187            gear: other.gear.clone(),
188            instance_id: other.instance_id,
189            control: other.control.clone(),
190            grpc_services: if other.grpc_services.is_empty() {
191                self.grpc_services.clone()
192            } else {
193                other.grpc_services.clone()
194            },
195            version: other.version.clone(),
196            rest_endpoint: other
197                .rest_endpoint
198                .clone()
199                .or_else(|| self.rest_endpoint.clone()),
200            openapi_spec: other
201                .openapi_spec
202                .clone()
203                .or_else(|| self.openapi_spec.clone()),
204            // Empty incoming labels mean "keep the stored set", not "clear"; a
205            // non-empty set replaces it. See `RegisterInstanceInfo::with_labels`
206            // for why (self-heal / REST-augmentation re-registers omit labels).
207            labels: if other.labels.is_empty() {
208                self.labels.clone()
209            } else {
210                other.labels.clone()
211            },
212            // The declared state rides on the merged record so
213            // `register_instance` can apply it (or preserve the stored one when
214            // `None`) after rebuilding the instance.
215            reported_state: other.reported_state,
216            inner: Arc::clone(&self.inner),
217        }
218    }
219}
220
221impl GearInstance {
222    pub fn new(gear: impl Into<String>, instance_id: Uuid) -> Self {
223        Self {
224            gear: gear.into(),
225            instance_id,
226            control: None,
227            grpc_services: HashMap::new(),
228            version: None,
229            rest_endpoint: None,
230            openapi_spec: None,
231            labels: BTreeMap::new(),
232            reported_state: None,
233            // Placeholder lease: already expired, so an instance that is never
234            // registered is never observable. `register_instance` stamps the
235            // real lease (`now + ttl`) and grace from the manager policy.
236            inner: Arc::new(parking_lot::RwLock::new(InstanceRuntimeState {
237                lease_expires_at: Instant::now(),
238                grace: Duration::ZERO,
239                reported: ReportedState::Starting,
240            })),
241        }
242    }
243
244    pub fn with_control(mut self, ep: Endpoint) -> Self {
245        self.control = Some(ep);
246        self
247    }
248
249    pub fn with_version(mut self, v: impl Into<String>) -> Self {
250        self.version = Some(v.into());
251        self
252    }
253
254    pub fn with_grpc_service(mut self, name: impl Into<String>, ep: Endpoint) -> Self {
255        self.grpc_services.insert(name.into(), ep);
256        self
257    }
258
259    pub fn with_rest_endpoint(mut self, ep: Endpoint) -> Self {
260        self.rest_endpoint = Some(ep);
261        self
262    }
263
264    pub fn with_openapi_spec(mut self, spec: impl Into<String>) -> Self {
265        self.openapi_spec = Some(spec.into());
266        self
267    }
268
269    pub fn with_labels(mut self, labels: BTreeMap<String, String>) -> Self {
270        self.labels = labels;
271        self
272    }
273
274    /// Set the state the registrant declares about itself.
275    pub fn with_reported_state(mut self, reported: ReportedState) -> Self {
276        self.reported_state = Some(reported);
277        self
278    }
279
280    /// The observable [`InstanceState`] derived from the lease and reported
281    /// state at `now`, or `None` when the record has expired more than `grace`
282    /// past its lease and is therefore no longer observable (the sweeper will
283    /// remove it; reads hide it in the meantime).
284    ///
285    /// | Condition | Returns |
286    /// |---|---|
287    /// | lease valid, reported `Starting` | `Registered` |
288    /// | lease valid, reported `Serving` | `Healthy` |
289    /// | lease valid, reported `Draining` | `Draining` |
290    /// | lease expired, less than `grace` ago | `Quarantined` |
291    /// | lease expired `grace` ago or more | `None` |
292    #[must_use]
293    pub fn observed_state_at(&self, now: Instant) -> Option<InstanceState> {
294        let s = self.inner.read();
295        if now <= s.lease_expires_at {
296            Some(match s.reported {
297                ReportedState::Starting => InstanceState::Registered,
298                ReportedState::Serving => InstanceState::Healthy,
299                ReportedState::Draining => InstanceState::Draining,
300            })
301        } else if now <= s.lease_expires_at + s.grace {
302            Some(InstanceState::Quarantined)
303        } else {
304            None
305        }
306    }
307
308    /// The current observable state (evaluated against the wall clock now).
309    ///
310    /// A record past its grace window is no longer observable; callers that
311    /// enumerate instances filter those out, so this collapses the
312    /// unobservable case onto `Quarantined` for the rare direct caller.
313    #[must_use]
314    pub fn state(&self) -> InstanceState {
315        self.observed_state_at(Instant::now())
316            .unwrap_or(InstanceState::Quarantined)
317    }
318}
319
320/// Central registry that tracks all running gear instances in the system.
321/// Provides discovery, health tracking, and round-robin load balancing.
322///
323/// Always shared as an `Arc<GearManager>` and NOT `Clone`: a by-value clone
324/// would deep-copy the `DashMap` directories while sharing the guards, so the
325/// registration lock would no longer serialize the map it guards.
326#[must_use]
327pub struct GearManager {
328    inner: DashMap<String, Vec<Arc<GearInstance>>>,
329    rr_counters: DashMap<String, usize>,
330    /// Lease policy (ttl + grace), behind a lock so the `service-discovery`
331    /// gear can apply its configured `lease` settings onto the
332    /// host-owned manager after it is constructed and shared.
333    lease: parking_lot::RwLock<LeasePolicy>,
334    /// Serializes gRPC-service-name ownership check + insert in
335    /// [`register_instance`](Self::register_instance) so two
336    /// gears cannot both pass an "unowned" check and then both commit the same
337    /// name. `DashMap` locks per entry, giving no boundary across the
338    /// cross-gear ownership scan and the single-entry write; this gate provides
339    /// it.
340    ///
341    /// Contract: every operation that *creates* a name→gear binding must hold
342    /// this lock — today `register_instance`, `set_grpc_service_owners`, and
343    /// `merge_authoritative_grpc_service_owners`. `deregister` / `sweep_expired`
344    /// only *free* names and `heartbeat` only renews a lease, so they cannot
345    /// create a second owner and need not take it. Any future mutator that can
346    /// bind a name must.
347    reg_lock: parking_lot::Mutex<()>,
348    /// Authoritative gRPC-service-name -> owning-gear map. When a name appears
349    /// here, ownership is fixed to the named gear: only that gear may advertise
350    /// it and no other gear can ever claim it, regardless of which registered
351    /// first — the stable ownership source the dynamic registration scan is
352    /// not. Populated by the runtime at startup (see
353    /// [`set_grpc_service_owners`](Self::set_grpc_service_owners)); names absent
354    /// from the map fall back to first-registration ownership.
355    service_owners: parking_lot::RwLock<HashMap<String, String>>,
356}
357
358/// Returned by [`GearManager::register_instance`] when an instance
359/// advertises a gRPC service name already owned by a *different* gear. The
360/// store is left unchanged; the caller maps this onto a gRPC status (see
361/// `DirectoryServiceNameConflict`), whose code depends on [`recoverable`].
362///
363/// [`recoverable`]: Self::recoverable
364#[derive(Debug, Clone, PartialEq, Eq)]
365pub struct GrpcServiceNameConflict {
366    /// The gRPC service name that is already owned.
367    pub service_name: String,
368    /// The gear that currently owns `service_name`.
369    pub owner: String,
370    /// Whether waiting could clear the conflict: `false` when the name is pinned
371    /// to `owner` by the authoritative ownership map (permanent), `true` when
372    /// `owner` merely currently advertises it (clears when it deregisters). Set
373    /// at the two rejection sites in [`GearManager::register_instance`].
374    pub recoverable: bool,
375}
376
377impl std::fmt::Display for GrpcServiceNameConflict {
378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379        write!(
380            f,
381            "gRPC service name '{}' is already owned by gear '{}'",
382            self.service_name, self.owner
383        )
384    }
385}
386
387impl std::error::Error for GrpcServiceNameConflict {}
388
389impl std::fmt::Debug for GearManager {
390    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391        let gears: Vec<String> = self.inner.iter().map(|e| e.key().clone()).collect();
392        let lease = *self.lease.read();
393        f.debug_struct("GearManager")
394            .field("instances_count", &self.inner.len())
395            .field("gears", &gears)
396            .field("lease_ttl", &lease.ttl)
397            .field("lease_grace", &lease.grace)
398            .finish_non_exhaustive()
399    }
400}
401
402impl GearManager {
403    pub fn new() -> Self {
404        Self {
405            inner: DashMap::new(),
406            rr_counters: DashMap::new(),
407            // Lease defaults (`cpt-cf-adr-directory-persistence-and-replication`):
408            // a crashed instance stops being preferred within `ttl` and becomes
409            // unobservable within `ttl + grace`.
410            lease: parking_lot::RwLock::new(LeasePolicy {
411                ttl: Duration::from_secs(30),
412                grace: Duration::from_secs(30),
413            }),
414            reg_lock: parking_lot::Mutex::new(()),
415            service_owners: parking_lot::RwLock::new(HashMap::new()),
416        }
417    }
418
419    /// Set the lease policy, builder-style. Equivalent to
420    /// [`set_lease_policy`](Self::set_lease_policy) before the manager is shared.
421    pub fn with_lease_policy(self, ttl: Duration, grace: Duration) -> Self {
422        self.set_lease_policy(ttl, grace);
423        self
424    }
425
426    /// Set the lease policy at runtime. Used by the
427    /// `service-discovery` gear to apply its configured `lease` settings onto
428    /// the host-owned manager after construction. Only affects leases stamped
429    /// by registrations/heartbeats after this call; already-stamped records
430    /// keep the grace they were given.
431    pub fn set_lease_policy(&self, ttl: Duration, grace: Duration) {
432        *self.lease.write() = LeasePolicy { ttl, grace };
433    }
434
435    /// The lease TTL this directory grants, so `RegisterInstance` can return
436    /// `lease_ttl_ms` and a worker can heartbeat at `ttl / 3`.
437    #[must_use]
438    pub fn lease_ttl(&self) -> Duration {
439        self.lease.read().ttl
440    }
441
442    /// Install the authoritative gRPC-service-name -> owning-gear map.
443    ///
444    /// A listed name may be advertised only by its owner (enforced in
445    /// [`register_instance`](Self::register_instance)), closing the hole where a
446    /// gear could squat another's service name by registering first; unlisted
447    /// names keep first-registration ownership. Seeded from operator config, then
448    /// layered with the compiled-in owners via
449    /// [`merge_authoritative_grpc_service_owners`](Self::merge_authoritative_grpc_service_owners) —
450    /// as each group's installers become available. Configure application/`OoP` names
451    /// explicitly to protect them before initialization and registration.
452    ///
453    /// Taken under `reg_lock` so it can't interleave with an in-flight
454    /// [`register_instance`](Self::register_instance) check + commit.
455    pub fn set_grpc_service_owners(&self, owners: HashMap<String, String>) {
456        let _gate = self.reg_lock.lock();
457        *self.service_owners.write() = owners;
458    }
459
460    /// Merge a compiled-in `service_name -> gear` map into the ownership map,
461    /// overriding any conflicting operator-configured entry.
462    ///
463    /// The compiled binary is ground truth — a gear physically *provides* the
464    /// service — so config must not reassign that name elsewhere (that would
465    /// re-open the squat); a disagreeing entry is overridden and warned. Names
466    /// absent here (e.g. remote / out-of-process gears) keep their configured
467    /// owner.
468    ///
469    /// Runs before each group's registration, under `reg_lock`.
470    pub fn merge_authoritative_grpc_service_owners(&self, authoritative: HashMap<String, String>) {
471        let _gate = self.reg_lock.lock();
472        let mut owners = self.service_owners.write();
473        for (service_name, gear) in authoritative {
474            if let Some(configured) = owners.get(&service_name)
475                && configured != &gear
476            {
477                tracing::warn!(
478                    service = %service_name,
479                    configured_owner = %configured,
480                    compiled_owner = %gear,
481                    "grpc-service-owners: operator config assigned a compiled-in service name to a \
482                     different gear; the compiled-in provider is authoritative and overrides it"
483                );
484            }
485            owners.insert(service_name, gear);
486        }
487    }
488
489    /// Register or update a gear instance, enforcing single-gear ownership of
490    /// every gRPC service name it advertises — atomically.
491    ///
492    /// The ownership check ([`check_grpc_service_ownership`](Self::check_grpc_service_ownership))
493    /// and the insert run under one registration lock, so two gears cannot both
494    /// pass an "unowned" check and then both commit the same name — a
495    /// check-then-write race the per-entry `DashMap` locks do not prevent. On a
496    /// conflict the store is left untouched.
497    ///
498    /// Registration **renews the lease**: `lease_expires_at` is set
499    /// to `now + ttl`, including on re-registration of an existing record.
500    ///
501    /// Re-registering an existing `instance_id` is otherwise an idempotent
502    /// endpoint / metadata refresh that preserves the same
503    /// `Arc<RwLock<InstanceRuntimeState>>`, so a concurrent `heartbeat` keeps
504    /// writing the same lease. The declared [`ReportedState`]
505    /// ([`GearInstance::reported_state`]) is applied when present; when `None`
506    /// (a self-heal re-register that omits the field) the record *keeps* the
507    /// state it already reports, so a serving instance is never knocked back to
508    /// `Starting`. On a brand-new record `None` defaults to
509    /// [`ReportedState::Starting`].
510    ///
511    /// # Errors
512    /// Returns [`GrpcServiceNameConflict`] if an advertised gRPC service name is
513    /// owned by, or currently advertised by, another gear.
514    pub fn register_instance(
515        &self,
516        instance: Arc<GearInstance>,
517    ) -> Result<(), GrpcServiceNameConflict> {
518        let _gate = self.reg_lock.lock();
519        self.check_grpc_service_ownership(&instance)?;
520
521        let now = Instant::now();
522        let declared = instance.reported_state;
523        let gear = instance.gear.clone();
524        let mut vec = self.inner.entry(gear).or_default();
525        // replace by instance_id if it already exists
526        let record = if let Some(pos) = vec
527            .iter()
528            .position(|i| i.instance_id == instance.instance_id)
529        {
530            // A record whose lease has lapsed past its grace window is
531            // unobservable and may already have had its gRPC service names
532            // reclaimed by another gear (`check_grpc_service_ownership` skips
533            // dead records). Merging would restore those names from the stored
534            // half — names the ownership check above never saw, as it only
535            // validates `instance`'s own services — and revive the dead lease,
536            // leaving two gears advertising one name. Treat it as a fresh
537            // registration so only the just-validated half survives.
538            if vec[pos].observed_state_at(now).is_none() {
539                vec[pos] = Arc::clone(&instance);
540                instance
541            } else {
542                let merged = Arc::new(vec[pos].with_metadata_of(&instance));
543                vec[pos] = Arc::clone(&merged);
544                merged
545            }
546        } else {
547            vec.push(Arc::clone(&instance));
548            instance
549        };
550
551        // Renew the lease and apply the declared state. On a re-register that
552        // omits the state, keep the stored one (see the doc above).
553        let policy = *self.lease.read();
554        let mut s = record.inner.write();
555        s.lease_expires_at = now + policy.ttl;
556        s.grace = policy.grace;
557        if let Some(reported) = declared {
558            s.reported = reported;
559        }
560        Ok(())
561    }
562
563    /// Authorize every gRPC service name `instance` advertises, resolving
564    /// ownership in two tiers:
565    ///
566    /// 1. **Declared (authoritative).** If a name appears in the configured
567    ///    ownership map (see
568    ///    [`set_grpc_service_owners`](Self::set_grpc_service_owners)), only the
569    ///    declared owner may advertise it — any other gear is rejected even if
570    ///    it registers first. This stops a gear from squatting a name it was
571    ///    never assigned.
572    /// 2. **First-registration (fallback).** For names absent from that map, the
573    ///    first gear to register the name owns it.
574    ///
575    /// Authorization is necessary but not sufficient: a name currently
576    /// advertised by a *different* gear always conflicts, so even the declared
577    /// owner is refused while a stale advertiser still holds it (e.g. one that
578    /// registered under a previous ownership map before
579    /// [`set_grpc_service_owners`](Self::set_grpc_service_owners) reassigned the
580    /// name). This keeps ownership from splitting across two advertisers; the
581    /// declared owner succeeds once the stale holder deregisters or expires. A
582    /// name held by the *same* gear is always fine (re-register / additional
583    /// instance).
584    ///
585    /// Must be called with `reg_lock` held so the check stays atomic with the
586    /// caller's subsequent insert.
587    fn check_grpc_service_ownership(
588        &self,
589        instance: &GearInstance,
590    ) -> Result<(), GrpcServiceNameConflict> {
591        // Tier 1: reject a declared name claimed by a non-owner; the rest (the
592        // declared owner, and undeclared names) still need the tier-2 scan.
593        let declared = self.service_owners.read();
594        let mut to_scan: Vec<&str> = Vec::new();
595        for service_name in instance.grpc_services.keys() {
596            match declared.get(service_name) {
597                Some(owner) if *owner != instance.gear => {
598                    // Tier 1: the name is pinned to another gear by the
599                    // authoritative map — permanent, waiting cannot clear it.
600                    return Err(GrpcServiceNameConflict {
601                        service_name: service_name.clone(),
602                        owner: owner.clone(),
603                        recoverable: false,
604                    });
605                }
606                _ => to_scan.push(service_name),
607            }
608        }
609        drop(declared);
610        if to_scan.is_empty() {
611            return Ok(());
612        }
613
614        // Tier 2: one pass over the directory, checking every candidate name per
615        // instance visited rather than re-scanning once per name. A name already
616        // held by a *different* gear conflicts. An instance whose lease expired
617        // past its grace window is unobservable and no longer holds
618        // its names, so it is skipped — a successor can claim the name even
619        // before the sweeper removes the dead record.
620        let now = Instant::now();
621        for entry in &self.inner {
622            if entry.key() == &instance.gear {
623                continue; // same gear: re-register / additional instance is fine
624            }
625            for existing in entry.value() {
626                if existing.observed_state_at(now).is_none() {
627                    continue; // dead record: releases its gRPC names
628                }
629                if let Some(&name) = to_scan
630                    .iter()
631                    .find(|&&n| existing.grpc_services.contains_key(n))
632                {
633                    // Tier 2: a *different* gear currently advertises the name —
634                    // recoverable, it clears when that holder deregisters/expires.
635                    return Err(GrpcServiceNameConflict {
636                        service_name: name.to_owned(),
637                        owner: entry.key().clone(),
638                        recoverable: true,
639                    });
640                }
641            }
642        }
643        Ok(())
644    }
645
646    /// Renew an instance's lease and apply the state it reports.
647    ///
648    /// Called for every heartbeat. `reported` is `None` when the heartbeat
649    /// omits a state, which counts as [`ReportedState::Serving`] (so an old
650    /// worker that only ever heartbeats reads as `Healthy`). Returns `false`
651    /// when no such `(gear, instance_id)` is registered, letting the caller
652    /// answer `NOT_FOUND`.
653    ///
654    /// A record whose lease expired past its grace window is treated as absent:
655    /// it is no longer observable, and a successor gear may already have claimed
656    /// the gRPC service names it used to hold (ownership scans skip it, see
657    /// [`check_grpc_service_ownership`](Self::check_grpc_service_ownership)).
658    /// Renewing it here would revive a second advertiser of the same name, so a
659    /// heartbeat for such a record returns `false`. The caller re-registers,
660    /// which runs the ownership check in
661    /// [`register_instance`](Self::register_instance) and rejects the revival if
662    /// the name moved on.
663    #[must_use]
664    pub fn heartbeat(
665        &self,
666        gear: &str,
667        instance_id: Uuid,
668        reported: Option<ReportedState>,
669    ) -> bool {
670        if let Some(vec) = self.inner.get(gear)
671            && let Some(inst) = vec.iter().find(|i| i.instance_id == instance_id)
672        {
673            let policy = *self.lease.read();
674            // Read the expiry and renew under the *same* write lock, with a
675            // timestamp taken after acquiring it: the "is it still observable"
676            // decision and the renewing write must be one critical section.
677            // Checking against a `now` captured before the lock would let the
678            // grace boundary pass in between, reviving a record a concurrent
679            // `register_instance` may already have handed its gRPC name to a
680            // successor. Past the grace window the record is unobservable, so
681            // return `false` and force the caller onto the re-registration path
682            // (which re-checks ownership).
683            let mut s = inst.inner.write();
684            let now = Instant::now();
685            if now > s.lease_expires_at + s.grace {
686                return false;
687            }
688            s.lease_expires_at = now + policy.ttl;
689            s.grace = policy.grace;
690            s.reported = reported.unwrap_or(ReportedState::Serving);
691            return true;
692        }
693        false
694    }
695
696    /// Remove an instance from the directory
697    pub fn deregister(&self, gear: &str, instance_id: Uuid) {
698        if let Some(mut vec) = self.inner.get_mut(gear) {
699            vec.value_mut()
700                .retain(|inst| inst.instance_id != instance_id);
701        }
702
703        // Drop the gear entry only if it is *still* empty: a concurrent
704        // `register_instance` can insert a fresh instance between the retain
705        // above and this removal, and an unconditional `remove` would delete it.
706        // `remove_if` re-checks under the entry lock (same pattern as
707        // `sweep_expired`).
708        if self
709            .inner
710            .remove_if(gear, |_, vec| vec.is_empty())
711            .is_some()
712        {
713            self.rr_counters.remove(gear);
714            self.rr_counters.remove(&format!("rest:{gear}"));
715        }
716    }
717
718    /// Get all currently-observable instances of a specific gear.
719    ///
720    /// A record whose lease expired past its grace window is filtered out: it
721    /// is no longer observable, so callers never see it even before
722    /// [`sweep_expired`](Self::sweep_expired) removes it.
723    #[must_use]
724    pub fn instances_of(&self, gear: &str) -> Vec<Arc<GearInstance>> {
725        let now = Instant::now();
726        self.inner
727            .get(gear)
728            .map(|v| {
729                v.iter()
730                    .filter(|i| i.observed_state_at(now).is_some())
731                    .cloned()
732                    .collect()
733            })
734            .unwrap_or_default()
735    }
736
737    /// Get all currently-observable instances across all gears.
738    #[must_use]
739    pub fn all_instances(&self) -> Vec<Arc<GearInstance>> {
740        let now = Instant::now();
741        self.inner
742            .iter()
743            .flat_map(|entry| {
744                entry
745                    .value()
746                    .iter()
747                    .filter(|i| i.observed_state_at(now).is_some())
748                    .cloned()
749                    .collect::<Vec<_>>()
750            })
751            .collect()
752    }
753
754    /// Remove records whose lease expired more than `grace` ago.
755    ///
756    /// This is the `memory`-mode sweeper: a record is no longer observable once
757    /// its lease lapses past the grace window, so this only garbage-collects —
758    /// reads already hide such records. Removing a gear's last instance also
759    /// frees its round-robin counters and the gRPC service names it held.
760    pub fn sweep_expired(&self, now: Instant) {
761        let mut empty_gears = Vec::new();
762
763        for mut entry in self.inner.iter_mut() {
764            let gear = entry.key().clone();
765            let vec = entry.value_mut();
766            vec.retain(|inst| inst.observed_state_at(now).is_some());
767            if vec.is_empty() {
768                empty_gears.push(gear);
769            }
770        }
771
772        // Remove each emptied gear only if it is *still* empty: a
773        // `register_instance` can insert a fresh instance between the retain
774        // above and this removal, and an unconditional `remove` would delete it.
775        // `remove_if` re-checks under the entry lock, atomically with any
776        // concurrent registration on the same entry.
777        for gear in empty_gears {
778            if self
779                .inner
780                .remove_if(&gear, |_, vec| vec.is_empty())
781                .is_some()
782            {
783                self.rr_counters.remove(&gear);
784                self.rr_counters.remove(&format!("rest:{gear}"));
785            }
786        }
787    }
788
789    /// From a candidate set, return the serving subset (`Healthy`/`Ready`); if
790    /// none are serving, fall back to the not-yet-serving instances
791    /// (`Registered`/`Quarantined`) rather than failing closed. A `Draining`
792    /// instance is never a routing target, even as a fallback — draining means
793    /// "stop routing new work" — so a gear whose only instances are draining
794    /// resolves to nothing. `context` names the pool for the cold-path `debug!`.
795    fn prefer_serving(candidates: Vec<Arc<GearInstance>>, context: &str) -> Vec<Arc<GearInstance>> {
796        let now = Instant::now();
797        // Keep only routable instances: a fully-lapsed lease is unobservable and
798        // a `Draining` instance is shutting down — neither may be routed to, even
799        // as a fallback.
800        let routable: Vec<Arc<GearInstance>> = candidates
801            .into_iter()
802            .filter(|inst| {
803                !matches!(
804                    inst.observed_state_at(now),
805                    None | Some(InstanceState::Draining)
806                )
807            })
808            .collect();
809        let serving: Vec<Arc<GearInstance>> = routable
810            .iter()
811            .filter(|inst| {
812                matches!(
813                    inst.observed_state_at(now),
814                    Some(InstanceState::Healthy | InstanceState::Ready)
815                )
816            })
817            .cloned()
818            .collect();
819        if serving.is_empty() {
820            if !routable.is_empty() {
821                tracing::debug!(
822                    context,
823                    "no serving (Ready/Healthy) instance available; round-robining over the \
824                     not-serving set instead of returning None"
825                );
826            }
827            routable
828        } else {
829            serving
830        }
831    }
832
833    /// Pick an instance using round-robin selection, preferring serving instances
834    #[must_use]
835    pub fn pick_instance_round_robin(&self, gear: &str) -> Option<Arc<GearInstance>> {
836        let instances_entry = self.inner.get(gear)?;
837        let instances = instances_entry.value();
838
839        let candidates = Self::prefer_serving(instances.clone(), gear);
840        if candidates.is_empty() {
841            return None;
842        }
843
844        let len = candidates.len();
845        let mut counter = self.rr_counters.entry(gear.to_owned()).or_insert(0);
846        let idx = *counter % len;
847        *counter = (*counter + 1) % len;
848
849        candidates.get(idx).cloned()
850    }
851
852    /// Pick a service endpoint using round-robin, returning (gear, instance, endpoint).
853    /// Prefers healthy/ready instances and automatically rotates among them.
854    #[must_use]
855    pub fn pick_service_round_robin(
856        &self,
857        service_name: &str,
858    ) -> Option<(String, Arc<GearInstance>, Endpoint)> {
859        // Collect the `Arc` of every instance that provides this service, then
860        // apply the shared serving-preference fallback so gRPC resolution
861        // survives an all-not-ready gear instead of failing closed. Cloning an
862        // `Arc` is a refcount bump; the gear name and endpoint are cloned once,
863        // for the winner, after the index is chosen.
864        let mut providing: Vec<Arc<GearInstance>> = Vec::new();
865        for entry in &self.inner {
866            for inst in entry.value() {
867                if inst.grpc_services.contains_key(service_name) {
868                    providing.push(inst.clone());
869                }
870            }
871        }
872
873        if providing.is_empty() {
874            return None;
875        }
876
877        let mut candidates = Self::prefer_serving(providing, service_name);
878        if candidates.is_empty() {
879            return None;
880        }
881
882        // Use a counter keyed by service name for round-robin
883        let len = candidates.len();
884        let service_key = service_name.to_owned();
885        let mut counter = self.rr_counters.entry(service_key).or_insert(0);
886        let idx = *counter % len;
887        *counter = (*counter + 1) % len;
888
889        let inst = candidates.swap_remove(idx);
890        let endpoint = inst.grpc_services.get(service_name)?.clone();
891        let gear = inst.gear.clone();
892        Some((gear, inst, endpoint))
893    }
894
895    /// Resolve a REST endpoint for a gear using round-robin over instances that
896    /// expose one, preferring healthy/ready instances.
897    #[must_use]
898    pub fn pick_rest_endpoint_round_robin(&self, gear: &str) -> Option<Endpoint> {
899        let instances_entry = self.inner.get(gear)?;
900        let instances = instances_entry.value();
901
902        // Only instances that actually expose a REST endpoint are candidates.
903        let with_rest: Vec<_> = instances
904            .iter()
905            .filter(|inst| inst.rest_endpoint.is_some())
906            .cloned()
907            .collect();
908
909        if with_rest.is_empty() {
910            return None;
911        }
912
913        let candidates = Self::prefer_serving(with_rest, gear);
914        if candidates.is_empty() {
915            return None;
916        }
917
918        let len = candidates.len();
919        let rr_key = format!("rest:{gear}");
920        let mut counter = self.rr_counters.entry(rr_key).or_insert(0);
921        let idx = *counter % len;
922        *counter = (*counter + 1) % len;
923
924        candidates
925            .get(idx)
926            .and_then(|inst| inst.rest_endpoint.clone())
927    }
928
929    /// Return a gear that currently advertises the gRPC service `service_name`,
930    /// if any (any instance state counts); in the misconfigured multi-owner case
931    /// the first match in iteration order.
932    ///
933    /// Test-only: [`register_instance`](Self::register_instance) enforces single
934    /// ownership with its own inline scan, so this is not part of the public
935    /// surface — it exists purely to let the tests below assert who owns a name.
936    #[cfg(test)]
937    #[must_use]
938    fn grpc_service_owner(&self, service_name: &str) -> Option<String> {
939        let now = Instant::now();
940        for entry in &self.inner {
941            if entry.value().iter().any(|inst| {
942                inst.observed_state_at(now).is_some()
943                    && inst.grpc_services.contains_key(service_name)
944            }) {
945                return Some(entry.key().clone());
946            }
947        }
948        None
949    }
950
951    /// Retrieve the `OpenAPI` spec of a gear, taken from the first registered
952    /// instance that published one.
953    #[must_use]
954    pub fn openapi_spec_of(&self, gear: &str) -> Option<String> {
955        let instances_entry = self.inner.get(gear)?;
956        instances_entry
957            .value()
958            .iter()
959            .find_map(|inst| inst.openapi_spec.clone())
960    }
961}
962
963impl Default for GearManager {
964    fn default() -> Self {
965        Self::new()
966    }
967}
968
969#[cfg(test)]
970#[cfg_attr(coverage_nightly, coverage(off))]
971mod tests {
972    use super::*;
973    use std::time::Duration;
974
975    #[test]
976    fn test_register_and_retrieve_instances() {
977        let dir = GearManager::new();
978        let instance_id = Uuid::new_v4();
979        let instance = Arc::new(
980            GearInstance::new("test_gear", instance_id)
981                .with_control(Endpoint::http("localhost", 8080))
982                .with_version("1.0.0"),
983        );
984
985        seed(&dir, instance);
986
987        let instances = dir.instances_of("test_gear");
988        assert_eq!(instances.len(), 1);
989        assert_eq!(instances[0].instance_id, instance_id);
990        assert_eq!(instances[0].gear, "test_gear");
991        assert_eq!(instances[0].version, Some("1.0.0".to_owned()));
992    }
993
994    /// Seed the registry in a test. The fixture is assumed to advertise no
995    /// conflicting gRPC service name, so a conflict is a bug in the test, not
996    /// an expected outcome — surface it loudly rather than swallowing it.
997    #[track_caller]
998    fn seed(mgr: &GearManager, instance: Arc<GearInstance>) {
999        mgr.register_instance(instance)
1000            .expect("test fixture must not create a gRPC service-name conflict");
1001    }
1002
1003    /// Force a seeded instance's lease to have expired `ago` before now, with
1004    /// the given grace window. Registration stamps a fresh lease, so this is
1005    /// called *after* seeding to simulate a worker that stopped heartbeating.
1006    #[track_caller]
1007    fn expire_lease(inst: &GearInstance, ago: Duration, grace: Duration) {
1008        let mut s = inst.inner.write();
1009        s.lease_expires_at = Instant::now()
1010            .checked_sub(ago)
1011            .expect("test lease subtraction should not underflow");
1012        s.grace = grace;
1013    }
1014
1015    fn labels(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
1016        pairs
1017            .iter()
1018            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1019            .collect()
1020    }
1021
1022    #[test]
1023    fn reregister_without_labels_preserves_stored_labels() {
1024        let dir = GearManager::new();
1025        let instance_id = Uuid::new_v4();
1026
1027        // Initial registration carries a shard label.
1028        seed(
1029            &dir,
1030            Arc::new(
1031                GearInstance::new("shard-gear", instance_id).with_labels(labels(&[("shard", "7")])),
1032            ),
1033        );
1034
1035        // A label-less re-registration (e.g. periodic self-heal / REST
1036        // augmentation) must NOT wipe the stored labels.
1037        seed(
1038            &dir,
1039            Arc::new(GearInstance::new("shard-gear", instance_id).with_version("2.0.0")),
1040        );
1041
1042        let registered = dir.instances_of("shard-gear");
1043        assert_eq!(registered.len(), 1);
1044        assert_eq!(
1045            registered[0].labels.get("shard"),
1046            Some(&"7".to_owned()),
1047            "label-less re-registration must preserve stored labels"
1048        );
1049        assert_eq!(registered[0].version, Some("2.0.0".to_owned()));
1050    }
1051
1052    /// The hub's gRPC record and the host's REST record of one instance, in
1053    /// either order: each keeps the other's half.
1054    #[test]
1055    fn grpc_and_rest_halves_of_an_instance_survive_each_other() {
1056        let grpc = |id| {
1057            GearInstance::new("both", id)
1058                .with_grpc_service("pkg.Svc", Endpoint::from_uri("http://127.0.0.1:50051"))
1059        };
1060        let rest = |id| {
1061            GearInstance::new("both", id)
1062                .with_rest_endpoint(Endpoint::from_uri("http://127.0.0.1:8080"))
1063                .with_openapi_spec("{}")
1064        };
1065        for grpc_first in [true, false] {
1066            let dir = GearManager::new();
1067            let id = Uuid::new_v4();
1068            let (first, second) = if grpc_first {
1069                (grpc(id), rest(id))
1070            } else {
1071                (rest(id), grpc(id))
1072            };
1073            seed(&dir, Arc::new(first));
1074            seed(&dir, Arc::new(second));
1075
1076            let registered = dir.instances_of("both");
1077            assert_eq!(registered.len(), 1);
1078            assert!(
1079                registered[0].grpc_services.contains_key("pkg.Svc"),
1080                "gRPC kept (grpc_first={grpc_first})"
1081            );
1082            assert_eq!(
1083                registered[0].rest_endpoint.as_ref().map(|e| e.uri.as_str()),
1084                Some("http://127.0.0.1:8080"),
1085                "REST kept (grpc_first={grpc_first})"
1086            );
1087            assert_eq!(registered[0].openapi_spec.as_deref(), Some("{}"));
1088        }
1089    }
1090
1091    /// A present half still replaces the stored one.
1092    #[test]
1093    fn a_present_half_replaces_the_stored_one() {
1094        let dir = GearManager::new();
1095        let id = Uuid::new_v4();
1096        seed(
1097            &dir,
1098            Arc::new(
1099                GearInstance::new("moved", id)
1100                    .with_rest_endpoint(Endpoint::from_uri("http://127.0.0.1:8080")),
1101            ),
1102        );
1103        seed(
1104            &dir,
1105            Arc::new(
1106                GearInstance::new("moved", id)
1107                    .with_rest_endpoint(Endpoint::from_uri("http://127.0.0.1:9090")),
1108            ),
1109        );
1110        assert_eq!(
1111            dir.instances_of("moved")[0]
1112                .rest_endpoint
1113                .as_ref()
1114                .map(|e| e.uri.as_str()),
1115            Some("http://127.0.0.1:9090")
1116        );
1117    }
1118
1119    #[test]
1120    fn reregister_with_labels_replaces_stored_labels() {
1121        let dir = GearManager::new();
1122        let instance_id = Uuid::new_v4();
1123
1124        seed(
1125            &dir,
1126            Arc::new(
1127                GearInstance::new("shard-gear", instance_id).with_labels(labels(&[("shard", "7")])),
1128            ),
1129        );
1130        // An explicit non-empty set replaces the stored one wholesale.
1131        seed(
1132            &dir,
1133            Arc::new(
1134                GearInstance::new("shard-gear", instance_id).with_labels(labels(&[("shard", "8")])),
1135            ),
1136        );
1137
1138        let registered = dir.instances_of("shard-gear");
1139        assert_eq!(registered.len(), 1);
1140        assert_eq!(registered[0].labels.get("shard"), Some(&"8".to_owned()));
1141    }
1142
1143    #[test]
1144    fn test_register_multiple_instances() {
1145        let dir = GearManager::new();
1146
1147        let id1 = Uuid::new_v4();
1148        let id2 = Uuid::new_v4();
1149        let instance1 = Arc::new(GearInstance::new("test_gear", id1));
1150        let instance2 = Arc::new(GearInstance::new("test_gear", id2));
1151
1152        seed(&dir, instance1);
1153        seed(&dir, instance2);
1154
1155        let registered = dir.instances_of("test_gear");
1156        assert_eq!(registered.len(), 2);
1157
1158        let ids: Vec<_> = registered.iter().map(|i| i.instance_id).collect();
1159        assert!(ids.contains(&id1));
1160        assert!(ids.contains(&id2));
1161    }
1162
1163    #[test]
1164    fn test_update_existing_instance() {
1165        let dir = GearManager::new();
1166        let instance_id = Uuid::new_v4();
1167
1168        let initial_instance =
1169            Arc::new(GearInstance::new("test_gear", instance_id).with_version("1.0.0"));
1170        seed(&dir, initial_instance);
1171
1172        let updated_instance =
1173            Arc::new(GearInstance::new("test_gear", instance_id).with_version("2.0.0"));
1174        seed(&dir, updated_instance);
1175
1176        let registered = dir.instances_of("test_gear");
1177        assert_eq!(registered.len(), 1, "Should not duplicate instance");
1178        assert_eq!(registered[0].version, Some("2.0.0".to_owned()));
1179    }
1180
1181    #[test]
1182    fn test_reregistration_preserves_liveness_state() {
1183        let dir = GearManager::new();
1184        let instance_id = Uuid::new_v4();
1185
1186        // Register, then heartbeat so the instance is Healthy (routable).
1187        seed(
1188            &dir,
1189            Arc::new(GearInstance::new("test_gear", instance_id).with_version("1.0.0")),
1190        );
1191        assert!(dir.heartbeat("test_gear", instance_id, None));
1192        assert!(matches!(
1193            dir.instances_of("test_gear")[0].state(),
1194            InstanceState::Healthy
1195        ));
1196
1197        // A self-heal re-registration that omits the reported state must NOT
1198        // reset liveness back to Registered — otherwise the instance drops out
1199        // of gRPC round-robin until the next heartbeat (the "split-brain" flap).
1200        seed(
1201            &dir,
1202            Arc::new(GearInstance::new("test_gear", instance_id).with_version("2.0.0")),
1203        );
1204
1205        let instances = dir.instances_of("test_gear");
1206        assert_eq!(instances.len(), 1);
1207        assert!(
1208            matches!(instances[0].state(), InstanceState::Healthy),
1209            "re-registration must preserve the Healthy state"
1210        );
1211        assert_eq!(
1212            instances[0].version,
1213            Some("2.0.0".to_owned()),
1214            "re-registration must still refresh metadata/endpoints"
1215        );
1216    }
1217
1218    #[test]
1219    fn test_concurrent_reregister_and_heartbeat_preserves_state() {
1220        let dir = GearManager::new();
1221        let instance_id = Uuid::new_v4();
1222
1223        let initial = Arc::new(GearInstance::new("test_gear", instance_id).with_version("1.0.0"));
1224        seed(&dir, initial);
1225        assert!(dir.heartbeat("test_gear", instance_id, None));
1226        assert!(matches!(
1227            dir.instances_of("test_gear")[0].state(),
1228            InstanceState::Healthy
1229        ));
1230
1231        std::thread::scope(|s| {
1232            s.spawn(|| {
1233                for _ in 0..1000 {
1234                    // The record always exists here, so each heartbeat renews it.
1235                    assert!(dir.heartbeat("test_gear", instance_id, None));
1236                }
1237            });
1238            s.spawn(|| {
1239                for i in 0..1000 {
1240                    let version = if i % 2 == 0 { "2.0.0" } else { "3.0.0" };
1241                    let reinst = Arc::new(
1242                        GearInstance::new("test_gear", instance_id)
1243                            .with_version(version)
1244                            .with_rest_endpoint(Endpoint::http(
1245                                "127.0.0.1",
1246                                8000u16 + u16::try_from(i % 10).expect("i % 10 fits in u16"),
1247                            )),
1248                    );
1249                    seed(&dir, reinst);
1250                }
1251            });
1252        });
1253
1254        let instances = dir.instances_of("test_gear");
1255        assert_eq!(instances.len(), 1);
1256        assert!(
1257            matches!(instances[0].state(), InstanceState::Healthy),
1258            "concurrent re-registration must not reset Healthy state"
1259        );
1260    }
1261
1262    #[test]
1263    fn register_with_reported_serving_reads_healthy() {
1264        let dir = GearManager::new();
1265        let instance_id = Uuid::new_v4();
1266        // A registrant that already reports Serving is immediately Healthy,
1267        // without waiting for a heartbeat.
1268        seed(
1269            &dir,
1270            Arc::new(
1271                GearInstance::new("test_gear", instance_id)
1272                    .with_reported_state(ReportedState::Serving),
1273            ),
1274        );
1275
1276        let instances = dir.instances_of("test_gear");
1277        assert_eq!(instances.len(), 1);
1278        assert!(matches!(instances[0].state(), InstanceState::Healthy));
1279    }
1280
1281    #[test]
1282    fn heartbeat_renews_lease_and_reads_serving() {
1283        let dir = GearManager::new();
1284        let instance_id = Uuid::new_v4();
1285        seed(&dir, Arc::new(GearInstance::new("test_gear", instance_id)));
1286
1287        // No heartbeat yet: reported Starting reads as Registered.
1288        assert!(matches!(
1289            dir.instances_of("test_gear")[0].state(),
1290            InstanceState::Registered
1291        ));
1292
1293        // A heartbeat with no reported state counts as Serving -> Healthy.
1294        assert!(dir.heartbeat("test_gear", instance_id, None));
1295        assert!(matches!(
1296            dir.instances_of("test_gear")[0].state(),
1297            InstanceState::Healthy
1298        ));
1299
1300        // A heartbeat for an unknown instance returns false (NOT_FOUND).
1301        assert!(!dir.heartbeat("test_gear", Uuid::new_v4(), None));
1302    }
1303
1304    #[test]
1305    fn heartbeat_on_a_lapsed_lease_returns_not_found() {
1306        let grace = Duration::from_millis(50);
1307        let dir = GearManager::new().with_lease_policy(Duration::from_millis(50), grace);
1308
1309        let instance = Arc::new(GearInstance::new("test_gear", Uuid::new_v4()));
1310        seed(&dir, Arc::clone(&instance));
1311
1312        // Within grace the record is still observable, so a heartbeat renews it.
1313        expire_lease(&instance, Duration::from_millis(10), grace);
1314        assert!(dir.heartbeat("test_gear", instance.instance_id, None));
1315
1316        // Past grace the record is unobservable: a heartbeat must return false
1317        // (NOT_FOUND) instead of reviving it, so the caller re-registers and
1318        // ownership is re-checked.
1319        expire_lease(&instance, grace + Duration::from_millis(10), grace);
1320        assert!(
1321            !dir.heartbeat("test_gear", instance.instance_id, None),
1322            "a heartbeat for a record whose lease lapsed past grace must not renew it"
1323        );
1324    }
1325
1326    #[test]
1327    fn a_lapsed_owner_cannot_reclaim_its_grpc_name_by_heartbeat() {
1328        // gear X owns a gRPC service name, then its lease lapses past grace.
1329        let grace = Duration::from_millis(50);
1330        let dir = GearManager::new().with_lease_policy(Duration::from_millis(50), grace);
1331        let service = "pkg.Svc";
1332
1333        let x = Arc::new(
1334            GearInstance::new("x", Uuid::new_v4())
1335                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
1336        );
1337        seed(&dir, Arc::clone(&x));
1338        expire_lease(&x, grace + Duration::from_millis(10), grace);
1339
1340        // A successor gear claims the now-free name.
1341        let y = Arc::new(
1342            GearInstance::new("y", Uuid::new_v4())
1343                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
1344        );
1345        dir.register_instance(y)
1346            .expect("the lapsed owner's gRPC name must be claimable by a successor");
1347
1348        // X's heartbeat must NOT revive it: that would leave two gears
1349        // advertising the same gRPC name.
1350        assert!(
1351            !dir.heartbeat("x", x.instance_id, None),
1352            "a lapsed owner must not reclaim its name via a bare heartbeat"
1353        );
1354        assert_eq!(
1355            dir.grpc_service_owner(service).as_deref(),
1356            Some("y"),
1357            "the successor keeps sole ownership of the name"
1358        );
1359    }
1360
1361    #[test]
1362    fn a_lapsed_owner_rest_reregister_does_not_restore_its_grpc_name() {
1363        // gear X owns a gRPC name, then its lease lapses past grace.
1364        let grace = Duration::from_millis(50);
1365        let dir = GearManager::new().with_lease_policy(Duration::from_millis(50), grace);
1366        let service = "pkg.Svc";
1367
1368        let x_id = Uuid::new_v4();
1369        let x = Arc::new(
1370            GearInstance::new("x", x_id)
1371                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
1372        );
1373        seed(&dir, Arc::clone(&x));
1374        expire_lease(&x, grace + Duration::from_millis(10), grace);
1375
1376        // A successor gear claims the now-free name.
1377        let y = Arc::new(
1378            GearInstance::new("y", Uuid::new_v4())
1379                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
1380        );
1381        dir.register_instance(y)
1382            .expect("the lapsed owner's gRPC name must be claimable by a successor");
1383
1384        // X re-registers a REST-only half (empty gRPC map), which passes the
1385        // ownership check. The merge must NOT restore X's old gRPC name from
1386        // the lapsed record — that would leave two gears advertising one name.
1387        dir.register_instance(Arc::new(
1388            GearInstance::new("x", x_id)
1389                .with_rest_endpoint(Endpoint::from_uri("http://127.0.0.1:8080")),
1390        ))
1391        .expect("a REST-only re-registration carries no conflicting gRPC name");
1392
1393        let registered = dir.instances_of("x");
1394        assert_eq!(registered.len(), 1);
1395        assert!(
1396            !registered[0].grpc_services.contains_key(service),
1397            "a lapsed owner's REST-only re-register must not restore its gRPC name"
1398        );
1399        assert_eq!(
1400            dir.grpc_service_owner(service).as_deref(),
1401            Some("y"),
1402            "the successor keeps sole ownership of the name"
1403        );
1404    }
1405
1406    #[test]
1407    fn test_all_instances() {
1408        let dir = GearManager::new();
1409
1410        let instance1 = Arc::new(GearInstance::new("gear_a", Uuid::new_v4()));
1411        let instance2 = Arc::new(GearInstance::new("gear_b", Uuid::new_v4()));
1412        let instance3 = Arc::new(GearInstance::new("gear_a", Uuid::new_v4()));
1413
1414        seed(&dir, instance1);
1415        seed(&dir, instance2);
1416        seed(&dir, instance3);
1417
1418        let all = dir.all_instances();
1419        assert_eq!(all.len(), 3);
1420
1421        let gears: Vec<_> = all.iter().map(|i| i.gear.as_str()).collect();
1422        assert_eq!(gears.iter().filter(|&m| *m == "gear_a").count(), 2);
1423        assert_eq!(gears.iter().filter(|&m| *m == "gear_b").count(), 1);
1424    }
1425
1426    #[test]
1427    fn test_pick_instance_round_robin() {
1428        let dir = GearManager::new();
1429
1430        let id1 = Uuid::new_v4();
1431        let id2 = Uuid::new_v4();
1432        let instance1 = Arc::new(GearInstance::new("test_gear", id1));
1433        let instance2 = Arc::new(GearInstance::new("test_gear", id2));
1434
1435        seed(&dir, instance1);
1436        seed(&dir, instance2);
1437
1438        // Pick three times to verify round-robin behavior
1439        let picked1 = dir.pick_instance_round_robin("test_gear").unwrap();
1440        let picked2 = dir.pick_instance_round_robin("test_gear").unwrap();
1441        let picked3 = dir.pick_instance_round_robin("test_gear").unwrap();
1442
1443        let ids = [
1444            picked1.instance_id,
1445            picked2.instance_id,
1446            picked3.instance_id,
1447        ];
1448
1449        // With 2 instances, we expect round-robin pattern like A, B, A
1450        // Check that both instance IDs appear and that at least one repeats
1451        assert!(ids.contains(&id1));
1452        assert!(ids.contains(&id2));
1453        // First and third pick should be the same (round-robin wraps)
1454        assert_eq!(picked1.instance_id, picked3.instance_id);
1455        // Second pick should be different from the first
1456        assert_ne!(picked1.instance_id, picked2.instance_id);
1457    }
1458
1459    #[test]
1460    fn test_pick_instance_none_available() {
1461        let dir = GearManager::new();
1462        let picked = dir.pick_instance_round_robin("nonexistent_gear");
1463        assert!(picked.is_none());
1464    }
1465
1466    #[test]
1467    fn test_endpoint_creation() {
1468        let plain_ep = Endpoint::http("localhost", 8080);
1469        assert_eq!(plain_ep.uri, "http://localhost:8080");
1470
1471        let secure_ep = Endpoint::https("localhost", 8443);
1472        assert_eq!(secure_ep.uri, "https://localhost:8443");
1473
1474        let uds_ep = Endpoint::uds("/tmp/socket.sock");
1475        assert!(uds_ep.uri.starts_with("unix://"));
1476        assert!(uds_ep.uri.contains("socket.sock"));
1477
1478        let custom_ep = Endpoint::from_uri("http://example.com");
1479        assert_eq!(custom_ep.uri, "http://example.com");
1480    }
1481
1482    #[test]
1483    fn test_endpoint_kind() {
1484        let plain_ep = Endpoint::http("127.0.0.1", 8080);
1485        match plain_ep.kind() {
1486            EndpointKind::Tcp(addr) => {
1487                assert_eq!(addr.ip().to_string(), "127.0.0.1");
1488                assert_eq!(addr.port(), 8080);
1489            }
1490            _ => panic!("Expected TCP endpoint for http"),
1491        }
1492
1493        let secure_ep = Endpoint::https("127.0.0.1", 8443);
1494        match secure_ep.kind() {
1495            EndpointKind::Tcp(addr) => {
1496                assert_eq!(addr.ip().to_string(), "127.0.0.1");
1497                assert_eq!(addr.port(), 8443);
1498            }
1499            _ => panic!("Expected TCP endpoint for https"),
1500        }
1501
1502        let uds_ep = Endpoint::uds("/tmp/test.sock");
1503        match uds_ep.kind() {
1504            EndpointKind::Uds(path) => {
1505                assert!(path.to_string_lossy().contains("test.sock"));
1506            }
1507            _ => panic!("Expected UDS endpoint"),
1508        }
1509
1510        let other_ep = Endpoint::from_uri("grpc://example.com");
1511        match other_ep.kind() {
1512            EndpointKind::Other(uri) => {
1513                assert_eq!(uri, "grpc://example.com");
1514            }
1515            _ => panic!("Expected Other endpoint"),
1516        }
1517    }
1518
1519    #[test]
1520    fn test_gear_instance_builder() {
1521        let instance_id = Uuid::new_v4();
1522        let instance = GearInstance::new("test_gear", instance_id)
1523            .with_control(Endpoint::http("localhost", 8080))
1524            .with_version("1.2.3")
1525            .with_grpc_service("service1", Endpoint::http("localhost", 8082))
1526            .with_grpc_service("service2", Endpoint::http("localhost", 8083));
1527
1528        assert_eq!(instance.gear, "test_gear");
1529        assert_eq!(instance.instance_id, instance_id);
1530        assert!(instance.control.is_some());
1531        assert_eq!(instance.version, Some("1.2.3".to_owned()));
1532        assert_eq!(instance.grpc_services.len(), 2);
1533        assert!(instance.grpc_services.contains_key("service1"));
1534        assert!(instance.grpc_services.contains_key("service2"));
1535        // The builder declares no reported state until a registration supplies
1536        // one; the observable state only exists once the directory stamps a
1537        // lease in `register_instance`.
1538        assert_eq!(instance.reported_state, None);
1539    }
1540
1541    #[test]
1542    fn test_quarantine_and_sweep() {
1543        let grace = Duration::from_millis(50);
1544        let dir = GearManager::new().with_lease_policy(Duration::from_millis(50), grace);
1545
1546        let instance = Arc::new(GearInstance::new("test_gear", Uuid::new_v4()));
1547        seed(&dir, Arc::clone(&instance));
1548
1549        // Lease expired 10ms ago, still within the 50ms grace -> Quarantined,
1550        // observable, so the sweeper keeps it.
1551        expire_lease(&instance, Duration::from_millis(10), grace);
1552        dir.sweep_expired(Instant::now());
1553        let instances = dir.instances_of("test_gear");
1554        assert_eq!(instances.len(), 1);
1555        assert!(matches!(instances[0].state(), InstanceState::Quarantined));
1556
1557        // Past grace: no longer observable, so the sweeper removes it.
1558        expire_lease(&instance, grace + Duration::from_millis(10), grace);
1559        dir.sweep_expired(Instant::now());
1560        assert!(dir.instances_of("test_gear").is_empty());
1561    }
1562
1563    #[test]
1564    fn test_instances_of_empty() {
1565        let dir = GearManager::new();
1566        let instances = dir.instances_of("nonexistent");
1567        assert!(instances.is_empty());
1568    }
1569
1570    #[test]
1571    fn test_rr_prefers_healthy() {
1572        let dir = GearManager::new();
1573
1574        // Create two instances: one healthy, one quarantined
1575        let healthy_id = Uuid::new_v4();
1576        let healthy = Arc::new(GearInstance::new("test_gear", healthy_id));
1577        seed(&dir, healthy);
1578        assert!(dir.heartbeat("test_gear", healthy_id, None));
1579
1580        let quarantined_id = Uuid::new_v4();
1581        let quarantined = Arc::new(GearInstance::new("test_gear", quarantined_id));
1582        seed(&dir, Arc::clone(&quarantined));
1583        // Lease expired but still within grace -> Quarantined (not serving).
1584        expire_lease(
1585            &quarantined,
1586            Duration::from_millis(10),
1587            Duration::from_secs(30),
1588        );
1589
1590        // RR should only pick the healthy instance
1591        for _ in 0..5 {
1592            let picked = dir.pick_instance_round_robin("test_gear").unwrap();
1593            assert_eq!(picked.instance_id, healthy_id);
1594        }
1595    }
1596
1597    #[test]
1598    fn test_pick_rest_endpoint_and_openapi() {
1599        let dir = GearManager::new();
1600        let id = Uuid::new_v4();
1601        let instance = Arc::new(
1602            GearInstance::new("billing", id)
1603                .with_rest_endpoint(Endpoint::http("billing", 8080))
1604                .with_openapi_spec("{\"openapi\":\"3.1.0\"}"),
1605        );
1606        seed(&dir, instance);
1607
1608        let rest = dir.pick_rest_endpoint_round_robin("billing").unwrap();
1609        assert_eq!(rest.uri, "http://billing:8080");
1610
1611        let spec = dir.openapi_spec_of("billing").unwrap();
1612        assert!(spec.contains("openapi"));
1613    }
1614
1615    #[test]
1616    fn test_pick_rest_endpoint_none_when_absent() {
1617        let dir = GearManager::new();
1618        let id = Uuid::new_v4();
1619        // Instance exposes only a gRPC service, no REST endpoint.
1620        let instance = Arc::new(
1621            GearInstance::new("grpc_only", id)
1622                .with_grpc_service("some.Service", Endpoint::http("127.0.0.1", 9000)),
1623        );
1624        seed(&dir, instance);
1625
1626        assert!(dir.pick_rest_endpoint_round_robin("grpc_only").is_none());
1627        assert!(dir.openapi_spec_of("grpc_only").is_none());
1628        assert!(dir.pick_rest_endpoint_round_robin("missing").is_none());
1629    }
1630
1631    #[test]
1632    fn test_pick_rest_endpoint_round_robin_rotates() {
1633        let dir = GearManager::new();
1634        let id1 = Uuid::new_v4();
1635        let id2 = Uuid::new_v4();
1636        let inst1 = Arc::new(
1637            GearInstance::new("web", id1).with_rest_endpoint(Endpoint::http("127.0.0.1", 8001)),
1638        );
1639        let inst2 = Arc::new(
1640            GearInstance::new("web", id2).with_rest_endpoint(Endpoint::http("127.0.0.1", 8002)),
1641        );
1642        seed(&dir, inst1);
1643        seed(&dir, inst2);
1644        assert!(dir.heartbeat("web", id1, None));
1645        assert!(dir.heartbeat("web", id2, None));
1646
1647        let ep1 = dir.pick_rest_endpoint_round_robin("web").unwrap();
1648        let ep2 = dir.pick_rest_endpoint_round_robin("web").unwrap();
1649        let ep3 = dir.pick_rest_endpoint_round_robin("web").unwrap();
1650
1651        assert_ne!(ep1, ep2);
1652        assert_eq!(ep1, ep3);
1653    }
1654
1655    #[test]
1656    fn test_pick_service_round_robin() {
1657        let dir = GearManager::new();
1658
1659        let id1 = Uuid::new_v4();
1660        let id2 = Uuid::new_v4();
1661        // Register two instances providing the same service
1662        let inst1 = Arc::new(
1663            GearInstance::new("test_gear", id1)
1664                .with_grpc_service("test.Service", Endpoint::http("127.0.0.1", 8001)),
1665        );
1666        let inst2 = Arc::new(
1667            GearInstance::new("test_gear", id2)
1668                .with_grpc_service("test.Service", Endpoint::http("127.0.0.1", 8002)),
1669        );
1670
1671        seed(&dir, inst1);
1672        seed(&dir, inst2);
1673
1674        // Mark both as healthy
1675        assert!(dir.heartbeat("test_gear", id1, None));
1676        assert!(dir.heartbeat("test_gear", id2, None));
1677
1678        // Pick should rotate between instances
1679        let pick1 = dir.pick_service_round_robin("test.Service");
1680        let pick2 = dir.pick_service_round_robin("test.Service");
1681        let pick3 = dir.pick_service_round_robin("test.Service");
1682
1683        assert!(pick1.is_some());
1684        assert!(pick2.is_some());
1685        assert!(pick3.is_some());
1686
1687        let (_, inst1, ep1) = pick1.unwrap();
1688        let (_, inst2, ep2) = pick2.unwrap();
1689        let (_, inst3, _) = pick3.unwrap();
1690
1691        // First and third should be the same (round-robin)
1692        assert_eq!(inst1.instance_id, inst3.instance_id);
1693        // First and second should be different
1694        assert_ne!(inst1.instance_id, inst2.instance_id);
1695        // Endpoints should differ
1696        assert_ne!(ep1, ep2);
1697    }
1698
1699    #[test]
1700    fn pick_service_falls_back_to_not_ready() {
1701        // A gear whose only service-providing instance is not yet serving
1702        // (Registered, no heartbeat) must still resolve, mirroring the REST and
1703        // instance pickers' not-ready fallback rather than failing closed.
1704        let dir = GearManager::new();
1705        let id = Uuid::new_v4();
1706        seed(
1707            &dir,
1708            Arc::new(
1709                GearInstance::new("worker", id)
1710                    .with_grpc_service("worker.Svc", Endpoint::http("127.0.0.1", 9000)),
1711            ),
1712        );
1713        // No heartbeat: the instance stays Registered (not serving).
1714        assert!(matches!(
1715            dir.instances_of("worker")[0].state(),
1716            InstanceState::Registered
1717        ));
1718
1719        let picked = dir.pick_service_round_robin("worker.Svc");
1720        assert!(
1721            picked.is_some(),
1722            "gRPC service resolution must fall back to the not-ready instance"
1723        );
1724        let (gear, _, ep) = picked.unwrap();
1725        assert_eq!(gear, "worker");
1726        assert_eq!(ep, Endpoint::http("127.0.0.1", 9000));
1727    }
1728
1729    #[test]
1730    fn pick_service_never_falls_back_to_a_draining_instance() {
1731        // A gear whose only instance is draining resolves to nothing: draining
1732        // means "stop routing new work", so it is not a fallback target.
1733        let dir = GearManager::new();
1734        let id = Uuid::new_v4();
1735        seed(
1736            &dir,
1737            Arc::new(
1738                GearInstance::new("worker", id)
1739                    .with_grpc_service("worker.Svc", Endpoint::http("127.0.0.1", 9000)),
1740            ),
1741        );
1742        assert!(dir.heartbeat("worker", id, Some(ReportedState::Draining)));
1743        assert!(matches!(
1744            dir.instances_of("worker")[0].state(),
1745            InstanceState::Draining
1746        ));
1747
1748        assert!(
1749            dir.pick_service_round_robin("worker.Svc").is_none(),
1750            "a draining-only gear must not be resolved, even as a fallback"
1751        );
1752    }
1753
1754    #[test]
1755    fn grpc_service_owner_reports_owning_gear_regardless_of_health() {
1756        let dir = GearManager::new();
1757
1758        // A freshly-registered (not-yet-serving) instance still owns its name.
1759        seed(
1760            &dir,
1761            Arc::new(
1762                GearInstance::new("authz-resolver", Uuid::new_v4()).with_grpc_service(
1763                    "cf.authz.v1.AuthzService",
1764                    Endpoint::http("127.0.0.1", 9000),
1765                ),
1766            ),
1767        );
1768
1769        assert_eq!(
1770            dir.grpc_service_owner("cf.authz.v1.AuthzService")
1771                .as_deref(),
1772            Some("authz-resolver"),
1773            "the advertising gear owns the name even while only Registered"
1774        );
1775        assert!(
1776            dir.grpc_service_owner("unowned.Service").is_none(),
1777            "an unadvertised name has no owner"
1778        );
1779    }
1780
1781    /// The production invariant behind the above: a `Registered`-but-not-healthy
1782    /// owner still blocks another gear's claim of the same name through
1783    /// `register_instance` (ownership does not wait on the owner becoming healthy).
1784    #[test]
1785    fn registered_but_unhealthy_owner_blocks_another_gears_claim() {
1786        let dir = GearManager::new();
1787        let owner_id = Uuid::new_v4();
1788
1789        // Owner claims the name and never heartbeats -> stays Registered.
1790        dir.register_instance(Arc::new(
1791            GearInstance::new("authz-resolver", owner_id).with_grpc_service(
1792                "cf.authz.v1.AuthzService",
1793                Endpoint::http("127.0.0.1", 9000),
1794            ),
1795        ))
1796        .expect("first claim of an unowned name succeeds");
1797        assert!(matches!(
1798            dir.instances_of("authz-resolver")[0].state(),
1799            InstanceState::Registered
1800        ));
1801
1802        // A different gear is rejected via the production path, health regardless.
1803        let conflict = dir
1804            .register_instance(Arc::new(
1805                GearInstance::new("impostor", Uuid::new_v4()).with_grpc_service(
1806                    "cf.authz.v1.AuthzService",
1807                    Endpoint::http("127.0.0.1", 9001),
1808                ),
1809            ))
1810            .unwrap_err();
1811        assert_eq!(conflict.owner, "authz-resolver");
1812    }
1813
1814    #[test]
1815    fn deregister_releases_grpc_service_name_to_another_gear() {
1816        let dir = GearManager::new();
1817        let service = "cf.authz.v1.AuthzService";
1818        let owner_id = Uuid::new_v4();
1819
1820        seed(
1821            &dir,
1822            Arc::new(
1823                GearInstance::new("authz-resolver", owner_id)
1824                    .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
1825            ),
1826        );
1827
1828        // While the owner is registered, a different gear cannot claim the name.
1829        dir.register_instance(Arc::new(
1830            GearInstance::new("successor", Uuid::new_v4())
1831                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
1832        ))
1833        .unwrap_err();
1834
1835        // Deregistering the owner releases the name...
1836        dir.deregister("authz-resolver", owner_id);
1837        assert!(
1838            dir.grpc_service_owner(service).is_none(),
1839            "the name is unowned once its owner deregisters"
1840        );
1841
1842        // ...so a different gear may now claim it.
1843        dir.register_instance(Arc::new(
1844            GearInstance::new("successor", Uuid::new_v4())
1845                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
1846        ))
1847        .expect("a released gRPC service name must be claimable by another gear");
1848        assert_eq!(
1849            dir.grpc_service_owner(service).as_deref(),
1850            Some("successor")
1851        );
1852    }
1853
1854    #[test]
1855    fn lease_releases_grpc_service_name_only_after_grace() {
1856        let grace = Duration::from_millis(50);
1857        let dir = GearManager::new().with_lease_policy(Duration::from_millis(50), grace);
1858        let service = "cf.authz.v1.AuthzService";
1859
1860        let owner = Arc::new(
1861            GearInstance::new("authz-resolver", Uuid::new_v4())
1862                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
1863        );
1864        seed(&dir, Arc::clone(&owner));
1865        // Expired but still within grace: the owner reads as Quarantined.
1866        expire_lease(&owner, Duration::from_millis(10), grace);
1867
1868        // A quarantined-but-still-observable owner keeps blocking its gRPC name,
1869        // so a successor is rejected (recoverable conflict).
1870        assert!(matches!(
1871            dir.instances_of("authz-resolver")[0].state(),
1872            InstanceState::Quarantined
1873        ));
1874        let conflict = dir
1875            .register_instance(Arc::new(
1876                GearInstance::new("successor", Uuid::new_v4())
1877                    .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
1878            ))
1879            .unwrap_err();
1880        assert_eq!(
1881            conflict.owner, "authz-resolver",
1882            "a quarantined-but-observable owner still holds the name"
1883        );
1884
1885        // Past the grace window the owner is unobservable and releases the name,
1886        // so another gear may take it over — even before the sweeper runs.
1887        expire_lease(&owner, grace + Duration::from_millis(10), grace);
1888        assert!(
1889            dir.grpc_service_owner(service).is_none(),
1890            "an expired owner hands the name back once the grace period lapses"
1891        );
1892        dir.register_instance(Arc::new(
1893            GearInstance::new("successor", Uuid::new_v4())
1894                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9002)),
1895        ))
1896        .expect("an expired owner's gRPC name must be claimable by another gear");
1897        assert_eq!(
1898            dir.grpc_service_owner(service).as_deref(),
1899            Some("successor")
1900        );
1901    }
1902
1903    #[test]
1904    fn test_deregister_clears_rr_counters() {
1905        let dir = GearManager::new();
1906        let id = Uuid::new_v4();
1907        let instance = Arc::new(
1908            GearInstance::new("web", id).with_rest_endpoint(Endpoint::http("127.0.0.1", 8001)),
1909        );
1910        seed(&dir, instance);
1911        assert!(dir.heartbeat("web", id, None));
1912
1913        // Exercise both round-robin counters so the keys are created.
1914        assert!(dir.pick_instance_round_robin("web").is_some());
1915        assert!(dir.pick_rest_endpoint_round_robin("web").is_some());
1916
1917        assert!(dir.rr_counters.contains_key("web"));
1918        assert!(dir.rr_counters.contains_key("rest:web"));
1919
1920        dir.deregister("web", id);
1921
1922        assert!(!dir.rr_counters.contains_key("web"));
1923        assert!(!dir.rr_counters.contains_key("rest:web"));
1924    }
1925
1926    #[test]
1927    fn test_sweep_expired_clears_rr_counters() {
1928        let grace = Duration::from_millis(50);
1929        let dir = GearManager::new().with_lease_policy(Duration::from_millis(50), grace);
1930
1931        let id = Uuid::new_v4();
1932        let instance = Arc::new(
1933            GearInstance::new("web", id).with_rest_endpoint(Endpoint::http("127.0.0.1", 8001)),
1934        );
1935        seed(&dir, Arc::clone(&instance));
1936        assert!(dir.pick_rest_endpoint_round_robin("web").is_some());
1937        assert!(dir.rr_counters.contains_key("rest:web"));
1938
1939        // Expired but within grace: still observable, sweep keeps it.
1940        expire_lease(&instance, Duration::from_millis(10), grace);
1941        dir.sweep_expired(Instant::now());
1942        let instances = dir.instances_of("web");
1943        assert_eq!(instances.len(), 1);
1944        assert!(matches!(instances[0].state(), InstanceState::Quarantined));
1945
1946        // Past grace: sweep removes it and frees the round-robin counters.
1947        expire_lease(&instance, grace + Duration::from_millis(10), grace);
1948        dir.sweep_expired(Instant::now());
1949
1950        assert!(dir.instances_of("web").is_empty());
1951        assert!(!dir.rr_counters.contains_key("web"));
1952        assert!(!dir.rr_counters.contains_key("rest:web"));
1953    }
1954
1955    #[test]
1956    fn register_instance_rejects_cross_gear_grpc_name() {
1957        let mgr = GearManager::new();
1958        let service = "cf.authz.v1.AuthzService";
1959
1960        mgr.register_instance(Arc::new(
1961            GearInstance::new("authz-resolver", Uuid::new_v4())
1962                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
1963        ))
1964        .expect("claiming an unowned service name must succeed");
1965
1966        // A different gear claiming the same name is rejected, store untouched.
1967        let conflict = mgr
1968            .register_instance(Arc::new(
1969                GearInstance::new("evil", Uuid::new_v4())
1970                    .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
1971            ))
1972            .unwrap_err();
1973        assert_eq!(conflict.service_name, service);
1974        assert_eq!(conflict.owner, "authz-resolver");
1975        assert!(mgr.instances_of("evil").is_empty());
1976
1977        // The owning gear may add another instance under the same name.
1978        mgr.register_instance(Arc::new(
1979            GearInstance::new("authz-resolver", Uuid::new_v4())
1980                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9002)),
1981        ))
1982        .expect("the owning gear may add another instance for its own service");
1983    }
1984
1985    #[test]
1986    fn declared_ownership_beats_registration_order() {
1987        let mgr = GearManager::new();
1988        let service = "cf.authz.v1.AuthzService";
1989
1990        // Config declares the name is owned by `authz`.
1991        mgr.set_grpc_service_owners(HashMap::from([(service.to_owned(), "authz".to_owned())]));
1992
1993        // A squatter registering *first* cannot claim a declared name; it is
1994        // rejected with the declared owner, and the store is untouched.
1995        let conflict = mgr
1996            .register_instance(Arc::new(
1997                GearInstance::new("evil", Uuid::new_v4())
1998                    .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
1999            ))
2000            .unwrap_err();
2001        assert_eq!(conflict.service_name, service);
2002        assert_eq!(conflict.owner, "authz");
2003        assert!(
2004            !conflict.recoverable,
2005            "a declared-owner conflict is pinned by config (permanent)"
2006        );
2007        assert!(mgr.instances_of("evil").is_empty());
2008
2009        // The declared owner is always admitted, even coming in second.
2010        mgr.register_instance(Arc::new(
2011            GearInstance::new("authz", Uuid::new_v4())
2012                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
2013        ))
2014        .expect("the declared owner must be admitted");
2015        assert_eq!(mgr.grpc_service_owner(service).as_deref(), Some("authz"));
2016    }
2017
2018    /// A gear can own an undeclared name via first-registration, after which a
2019    /// `set_grpc_service_owners` call reassigns that name to a different declared
2020    /// owner. The declared owner is authorized, but must not begin advertising
2021    /// the name while the original holder is still serving it — that would split
2022    /// ownership between two advertisers. It is refused until the stale holder is
2023    /// gone, then admitted.
2024    #[test]
2025    fn declared_owner_refused_while_a_stale_advertiser_still_holds_the_name() {
2026        let mgr = GearManager::new();
2027        let service = "cf.authz.v1.AuthzService";
2028        let holder = Uuid::new_v4();
2029
2030        // `first` claims the name via first-registration (not yet declared).
2031        mgr.register_instance(Arc::new(
2032            GearInstance::new("first", holder)
2033                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
2034        ))
2035        .expect("claiming an undeclared, unowned name must succeed");
2036
2037        // The map is (re)installed, declaring the name is owned by `authz`.
2038        mgr.set_grpc_service_owners(HashMap::from([(service.to_owned(), "authz".to_owned())]));
2039
2040        // The declared owner is authorized, but `first` is still advertising the
2041        // name: admitting `authz` now would split ownership, so it is rejected.
2042        let conflict = mgr
2043            .register_instance(Arc::new(
2044                GearInstance::new("authz", Uuid::new_v4())
2045                    .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
2046            ))
2047            .unwrap_err();
2048        assert_eq!(conflict.service_name, service);
2049        assert_eq!(
2050            conflict.owner, "first",
2051            "the current holder is the conflicting owner"
2052        );
2053        assert!(
2054            conflict.recoverable,
2055            "a stale-advertiser conflict clears once the holder deregisters"
2056        );
2057        assert!(mgr.instances_of("authz").is_empty());
2058
2059        // Once the stale holder is gone, the declared owner is admitted and owns
2060        // the name outright — no split.
2061        mgr.deregister("first", holder);
2062        mgr.register_instance(Arc::new(
2063            GearInstance::new("authz", Uuid::new_v4())
2064                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9002)),
2065        ))
2066        .expect("the declared owner must be admitted once the stale holder is gone");
2067        assert_eq!(mgr.grpc_service_owner(service).as_deref(), Some("authz"));
2068    }
2069
2070    /// The compiled-in (authoritative) map overrides a conflicting operator
2071    /// entry — the binary that *provides* a service name wins over config that
2072    /// tries to reassign it — while operator entries for names the binary does
2073    /// not know about are preserved. A subsequent registration is governed by
2074    /// the merged result.
2075    #[test]
2076    fn authoritative_owners_override_conflicting_config_and_keep_the_rest() {
2077        let mgr = GearManager::new();
2078
2079        // Operator config: one name that a compiled gear also provides (a
2080        // reassignment attempt), and one the binary does not compile in.
2081        mgr.set_grpc_service_owners(HashMap::from([
2082            ("cf.authz.v1.AuthzService".to_owned(), "impostor".to_owned()),
2083            ("remote.only.Service".to_owned(), "remote-gear".to_owned()),
2084        ]));
2085
2086        // Compiled registry says authz-resolver provides the authz service.
2087        mgr.merge_authoritative_grpc_service_owners(HashMap::from([(
2088            "cf.authz.v1.AuthzService".to_owned(),
2089            "authz-resolver".to_owned(),
2090        )]));
2091
2092        // Compiled-in provider wins the conflict; the remote-only entry stays.
2093        let conflict = mgr
2094            .register_instance(Arc::new(
2095                GearInstance::new("impostor", Uuid::new_v4()).with_grpc_service(
2096                    "cf.authz.v1.AuthzService",
2097                    Endpoint::http("127.0.0.1", 9000),
2098                ),
2099            ))
2100            .unwrap_err();
2101        assert_eq!(conflict.owner, "authz-resolver");
2102        assert!(
2103            !conflict.recoverable,
2104            "a pinned compiled-in owner is permanent"
2105        );
2106
2107        mgr.register_instance(Arc::new(
2108            GearInstance::new("authz-resolver", Uuid::new_v4()).with_grpc_service(
2109                "cf.authz.v1.AuthzService",
2110                Endpoint::http("127.0.0.1", 9001),
2111            ),
2112        ))
2113        .expect("the compiled-in provider owns its service name");
2114
2115        // The operator entry for the name absent from the compiled map is intact.
2116        let remote_conflict = mgr
2117            .register_instance(Arc::new(
2118                GearInstance::new("squatter", Uuid::new_v4())
2119                    .with_grpc_service("remote.only.Service", Endpoint::http("127.0.0.1", 9002)),
2120            ))
2121            .unwrap_err();
2122        assert_eq!(remote_conflict.owner, "remote-gear");
2123    }
2124
2125    #[test]
2126    fn names_absent_from_declared_map_keep_first_registration_ownership() {
2127        let mgr = GearManager::new();
2128        // The map declares one name but says nothing about `worker.Svc`.
2129        mgr.set_grpc_service_owners(HashMap::from([(
2130            "cf.authz.v1.AuthzService".to_owned(),
2131            "authz".to_owned(),
2132        )]));
2133        let service = "worker.Svc";
2134
2135        mgr.register_instance(Arc::new(
2136            GearInstance::new("worker-a", Uuid::new_v4())
2137                .with_grpc_service(service, Endpoint::http("127.0.0.1", 9000)),
2138        ))
2139        .expect("claiming an undeclared, unowned name must succeed");
2140
2141        let conflict = mgr
2142            .register_instance(Arc::new(
2143                GearInstance::new("worker-b", Uuid::new_v4())
2144                    .with_grpc_service(service, Endpoint::http("127.0.0.1", 9001)),
2145            ))
2146            .unwrap_err();
2147        assert_eq!(conflict.owner, "worker-a");
2148        assert!(
2149            conflict.recoverable,
2150            "a first-registration conflict clears if the holder leaves"
2151        );
2152    }
2153
2154    /// Under contention, the atomic check+insert admits exactly one owner for a
2155    /// gRPC service name: N gears race to claim the same unowned name and only
2156    /// one commits, closing the check-then-write race the per-entry `DashMap`
2157    /// locks leave open.
2158    #[test]
2159    fn concurrent_register_admits_exactly_one_owner() {
2160        use std::sync::Barrier;
2161
2162        let mgr = Arc::new(GearManager::new());
2163        let service = "cf.authz.v1.AuthzService";
2164        let racers = 16;
2165        let barrier = Arc::new(Barrier::new(racers));
2166
2167        #[expect(
2168            clippy::needless_collect,
2169            reason = "a lazy iterator would join before all racers spawn, deadlocking the Barrier"
2170        )]
2171        let handles: Vec<_> = (0..racers)
2172            .map(|i| {
2173                let mgr = Arc::clone(&mgr);
2174                let barrier = Arc::clone(&barrier);
2175                std::thread::spawn(move || {
2176                    let gear = format!("gear-{i}");
2177                    let instance = Arc::new(
2178                        GearInstance::new(gear.clone(), Uuid::new_v4()).with_grpc_service(
2179                            service,
2180                            Endpoint::http("127.0.0.1", 9000 + u16::try_from(i).unwrap()),
2181                        ),
2182                    );
2183                    // Release all threads at once to maximise contention.
2184                    barrier.wait();
2185                    (gear, mgr.register_instance(instance))
2186                })
2187            })
2188            .collect();
2189
2190        let results: Vec<(String, Result<(), GrpcServiceNameConflict>)> = handles
2191            .into_iter()
2192            .map(|h| h.join().expect("registration thread must not panic"))
2193            .collect();
2194
2195        // Exactly one gear wins the race.
2196        let winners: Vec<&str> = results
2197            .iter()
2198            .filter(|(_, r)| r.is_ok())
2199            .map(|(gear, _)| gear.as_str())
2200            .collect();
2201        assert_eq!(
2202            winners.len(),
2203            1,
2204            "exactly one competing registration must win"
2205        );
2206        let winner = winners[0];
2207
2208        // Every loser is rejected with a conflict naming the winning gear — the
2209        // `owner` surfaced in the server-side warn log and the operator's
2210        // remediation hint, so it must be the gear that actually committed, not
2211        // just any error.
2212        for (gear, result) in &results {
2213            if gear == winner {
2214                continue;
2215            }
2216            let conflict = result
2217                .as_ref()
2218                .expect_err("a losing registration must be rejected, not silently dropped");
2219            assert_eq!(conflict.service_name, service);
2220            assert_eq!(
2221                conflict.owner.as_str(),
2222                winner,
2223                "every loser's conflict must name the single winning gear as owner"
2224            );
2225        }
2226
2227        // ...and the store resolves the contested name to exactly that winner.
2228        assert_eq!(
2229            mgr.grpc_service_owner(service).as_deref(),
2230            Some(winner),
2231            "the contested name must resolve to the one gear that won"
2232        );
2233    }
2234}