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