Skip to main content

toolkit/
directory.rs

1//! Directory API - contract for service discovery and instance resolution
2
3use anyhow::Result;
4use async_trait::async_trait;
5use std::hash::{Hash, Hasher};
6use std::sync::Arc;
7use uuid::Uuid;
8
9use crate::runtime::{
10    Endpoint, GearInstance, GearManager, GrpcServiceNameConflict, ReportedState as RtReportedState,
11};
12
13/// Compute a content token for an `OpenAPI` document, used to detect changes.
14///
15/// This is a change-detection token (like a k8s `resourceVersion`), **not** a
16/// security digest: the edge only ever compares it against the token from the
17/// previous poll of the *same* directory to decide whether the document
18/// changed. A non-cryptographic `std` hash is therefore sufficient and avoids a
19/// dependency.
20///
21/// Determinism is scoped to a single binary: `DefaultHasher::new()` uses fixed
22/// keys, so identical input yields the same token for the lifetime of one
23/// directory process. `std` does **not** guarantee the algorithm across Rust
24/// toolchain versions, so a rebuilt/upgraded directory may emit a different
25/// token for the same spec — which is benign here, because tokens are only ever
26/// compared within one directory's poll stream (at worst an upgrade triggers a
27/// single spurious refresh). The token must therefore not be persisted or
28/// compared across binaries.
29fn openapi_spec_hash(spec: &str) -> String {
30    let mut hasher = std::collections::hash_map::DefaultHasher::new();
31    spec.hash(&mut hasher);
32    format!("{:016x}", hasher.finish())
33}
34
35// Re-export all types from contracts - this is the single source of truth
36pub use cf_system_sdks::directory::{
37    DirectoryClient, DirectoryInvalidArgument, DirectoryNotFound, DirectoryPermissionDenied,
38    DirectoryServiceNameConflict, GrpcServiceInfo, InstanceState, LabelSelector, RegisterAck,
39    RegisterInstanceInfo, ReportedState, ServiceEndpoint, ServiceInstanceInfo,
40};
41
42/// Map the SDK's domain [`ReportedState`] onto the runtime one carried on a
43/// [`GearInstance`]'s lease.
44fn domain_reported_to_runtime(reported: ReportedState) -> RtReportedState {
45    match reported {
46        ReportedState::Starting => RtReportedState::Starting,
47        ReportedState::Serving => RtReportedState::Serving,
48        ReportedState::Draining => RtReportedState::Draining,
49    }
50}
51
52/// Project the live runtime [`crate::runtime::InstanceState`] onto the domain
53/// [`InstanceState`] carried on `ServiceInstanceInfo`, so `resolve_by_labels`
54/// callers can apply their own health policy from a single resolve.
55fn runtime_state_to_domain(state: crate::runtime::InstanceState) -> InstanceState {
56    use crate::runtime::InstanceState as Rt;
57    match state {
58        Rt::Registered => InstanceState::Registered,
59        Rt::Ready => InstanceState::Ready,
60        Rt::Healthy => InstanceState::Healthy,
61        Rt::Quarantined => InstanceState::Quarantined,
62        Rt::Draining => InstanceState::Draining,
63    }
64}
65
66/// Project a live [`GearInstance`] into a [`ServiceInstanceInfo`].
67///
68/// `endpoint` prefers gRPC and falls back to REST; an instance advertising
69/// neither yields `endpoint: None` (never an empty-URI sentinel), which the
70/// label paths surface as *no-endpoint, not an error*. Always **spec-free**:
71/// only the `OpenAPI` spec *hash* rides along, never the document (fetched via
72/// `get_openapi_spec`).
73fn project_instance(gear: &str, inst: &GearInstance) -> ServiceInstanceInfo {
74    let endpoint = inst
75        .grpc_services
76        .values()
77        .next()
78        .or(inst.rest_endpoint.as_ref())
79        .map(|ep| ServiceEndpoint::new(ep.uri.clone()));
80
81    ServiceInstanceInfo::new(gear, inst.instance_id.to_string())
82        .with_endpoint(endpoint)
83        .with_version(inst.version.clone())
84        .with_rest_endpoint(
85            inst.rest_endpoint
86                .as_ref()
87                .map(|ep| ServiceEndpoint::new(ep.uri.clone())),
88        )
89        .with_openapi_spec_hash(inst.openapi_spec.as_deref().map(openapi_spec_hash))
90        // Carry every published gRPC service back so the directory-register
91        // phase can augment (not clobber) this instance when it adds a REST
92        // endpoint.
93        .with_grpc_services(
94            inst.grpc_services
95                .iter()
96                .map(|(name, e)| (name.clone(), ServiceEndpoint::new(e.uri.clone())))
97                .collect(),
98        )
99        .with_labels(inst.labels.clone())
100        .with_state(runtime_state_to_domain(inst.state()))
101}
102
103/// Local implementation of `DirectoryClient` that delegates to `GearManager`
104///
105/// This is the in-process implementation used by gears running in the same
106/// process as the gear orchestrator.
107pub struct LocalDirectoryClient {
108    mgr: Arc<GearManager>,
109}
110
111impl LocalDirectoryClient {
112    #[must_use]
113    pub fn new(mgr: Arc<GearManager>) -> Self {
114        Self { mgr }
115    }
116}
117
118#[async_trait]
119impl DirectoryClient for LocalDirectoryClient {
120    // Every lookup below is an in-memory `GearManager` map read, so `None` can
121    // only ever mean "nothing registered under that name" — this client has no
122    // backend and therefore no failure mode. Returning the typed
123    // `DirectoryNotFound` sentinel rather than a bare `anyhow` is what lets
124    // `DirectoryEndpointResolver` report `Ok(None)` ("provider not up yet")
125    // instead of `Err` ("the directory is broken"); the difference decides
126    // whether a routine startup race is logged at `debug` or `warn`.
127    async fn resolve_grpc_service(&self, service_name: &str) -> Result<ServiceEndpoint> {
128        if let Some((_gear, _inst, ep)) = self.mgr.pick_service_round_robin(service_name) {
129            return Ok(ServiceEndpoint::new(ep.uri));
130        }
131
132        Err(DirectoryNotFound::new(format!("service {service_name}")).into())
133    }
134
135    async fn resolve_rest_service(&self, gear_name: &str) -> Result<ServiceEndpoint> {
136        if let Some(ep) = self.mgr.pick_rest_endpoint_round_robin(gear_name) {
137            return Ok(ServiceEndpoint::new(ep.uri));
138        }
139
140        Err(DirectoryNotFound::new(format!("gear {gear_name}")).into())
141    }
142
143    async fn get_openapi_spec(&self, gear_name: &str) -> Result<String> {
144        self.mgr.openapi_spec_of(gear_name).ok_or_else(|| {
145            DirectoryNotFound::new(format!("openapi spec for gear {gear_name}")).into()
146        })
147    }
148
149    async fn list_instances(&self, gear: &str) -> Result<Vec<ServiceInstanceInfo>> {
150        // Base label-targeting enumeration: project every instance, including
151        // endpoint-less ones (no-endpoint contract; see `project_instance`).
152        Ok(self
153            .mgr
154            .instances_of(gear)
155            .iter()
156            .map(|inst| project_instance(gear, inst))
157            .collect())
158    }
159
160    async fn resolve_by_labels(
161        &self,
162        gear: &str,
163        selector: &LabelSelector,
164    ) -> Result<Vec<ServiceInstanceInfo>> {
165        // Filter by selector only: no health/endpoint filtering, so a matched
166        // endpoint-less instance is still returned for the caller to fall back on.
167        Ok(self
168            .mgr
169            .instances_of(gear)
170            .iter()
171            .map(|inst| project_instance(gear, inst))
172            .filter(|i| selector.matches(&i.labels))
173            .collect())
174    }
175
176    async fn list_all_instances(&self) -> Result<Vec<ServiceInstanceInfo>> {
177        // Edge snapshot: drop labels (shared `without_labels`) and, unlike the
178        // label paths, skip endpoint-less instances — the edge needs a dialable
179        // URI — with a `debug!` so the omission is observable.
180        Ok(self
181            .mgr
182            .all_instances()
183            .iter()
184            .filter_map(|inst| {
185                let info = project_instance(&inst.gear, inst);
186                if info.endpoint.is_none() {
187                    tracing::debug!(
188                        gear = %inst.gear,
189                        instance_id = %inst.instance_id,
190                        "skipping instance with no gRPC or REST endpoint from cross-gear snapshot"
191                    );
192                    return None;
193                }
194                Some(info.without_labels())
195            })
196            .collect())
197    }
198
199    async fn register_instance(&self, info: RegisterInstanceInfo) -> Result<()> {
200        // Parse instance_id from string to Uuid
201        let instance_id = Uuid::parse_str(&info.instance_id).map_err(|e| {
202            // A malformed instance_id is a client error, not a server fault:
203            // return the typed `DirectoryInvalidArgument` so a gRPC front-end
204            // maps it to `InvalidArgument` (and the caller stops retrying)
205            // rather than a bare `anyhow!` reported as `Internal`.
206            anyhow::Error::from(DirectoryInvalidArgument::new(format!(
207                "invalid instance_id '{}': {e}",
208                info.instance_id
209            )))
210        })?;
211
212        // Validate labels at the store boundary, not just at the gRPC
213        // front-end: this is the single point every registration path (remote
214        // gRPC, in-process, or a future transport) funnels through, so
215        // enforcing the shared rules here means an invalid label can never be
216        // stored regardless of how it arrived. The typed error maps to
217        // `InvalidArgument` at the wire boundary.
218        cf_system_sdks::directory::validate_labels(&info.labels)
219            .map_err(|e| anyhow::Error::from(DirectoryInvalidArgument::new(e.to_string())))?;
220
221        // Build a GearInstance from RegisterInstanceInfo
222        let mut instance = GearInstance::new(info.gear.clone(), instance_id);
223
224        // Apply version if provided
225        if let Some(version) = info.version {
226            instance = instance.with_version(version);
227        }
228
229        // Add all gRPC services
230        for (service_name, endpoint) in info.grpc_services {
231            instance = instance.with_grpc_service(service_name, Endpoint::from_uri(endpoint.uri));
232        }
233
234        // Apply REST endpoint if provided
235        if let Some(rest) = info.rest_endpoint {
236            instance = instance.with_rest_endpoint(Endpoint::from_uri(rest.uri));
237        }
238
239        // Apply OpenAPI spec if provided
240        if let Some(spec) = info.openapi_spec {
241            instance = instance.with_openapi_spec(spec);
242        }
243
244        // Apply stable addressing labels if provided
245        if !info.labels.is_empty() {
246            instance = instance.with_labels(info.labels);
247        }
248
249        // Carry the declared reported state onto the record, so
250        // registration sets the lease's reported state accordingly.
251        if let Some(reported) = info.reported_state {
252            instance = instance.with_reported_state(domain_reported_to_runtime(reported));
253        }
254
255        // Register the instance, enforcing single-gear ownership of every gRPC
256        // service name it advertises atomically (check + insert under one lock)
257        // so two gears cannot race to claim the same name. A conflict is a typed
258        // sentinel the gRPC boundary maps to a status whose code reflects whether
259        // the conflict is recoverable (`recoverable` is carried across).
260        self.mgr.register_instance(Arc::new(instance)).map_err(
261            |GrpcServiceNameConflict {
262                 service_name,
263                 owner,
264                 recoverable,
265             }| {
266                anyhow::Error::from(DirectoryServiceNameConflict {
267                    service_name,
268                    owner,
269                    recoverable,
270                })
271            },
272        )?;
273
274        Ok(())
275    }
276
277    async fn register_with_lease(&self, info: RegisterInstanceInfo) -> Result<RegisterAck> {
278        self.register_instance(info).await?;
279        // In-process registration always gets the directory's configured lease
280        // TTL, so an in-process registrar (e.g. Flight Control's own gears) can
281        // pace its renewals the same way an OoP worker does.
282        Ok(RegisterAck {
283            lease_ttl: Some(self.mgr.lease_ttl()),
284        })
285    }
286
287    async fn deregister_instance(&self, gear: &str, instance_id: &str) -> Result<()> {
288        let instance_id = Uuid::parse_str(instance_id)
289            .map_err(|e| anyhow::anyhow!("Invalid instance_id '{instance_id}': {e}"))?;
290        self.mgr.deregister(gear, instance_id);
291        Ok(())
292    }
293
294    async fn send_heartbeat(&self, gear: &str, instance_id: &str) -> Result<()> {
295        self.heartbeat(gear, instance_id, None).await
296    }
297
298    async fn heartbeat(
299        &self,
300        gear: &str,
301        instance_id: &str,
302        reported: Option<ReportedState>,
303    ) -> Result<()> {
304        let id = Uuid::parse_str(instance_id)
305            .map_err(|e| anyhow::anyhow!("Invalid instance_id '{instance_id}': {e}"))?;
306        // A heartbeat for an instance the directory does not know returns
307        // NOT_FOUND, so the presence loop re-registers after one
308        // heartbeat instead of waiting on a self-heal timer. A `None` reported
309        // state counts as Serving, preserving today's behaviour for callers
310        // that only heartbeat.
311        let reported = reported.map(domain_reported_to_runtime);
312        if self.mgr.heartbeat(gear, id, reported) {
313            Ok(())
314        } else {
315            Err(DirectoryNotFound::new(format!("instance {gear}/{instance_id}")).into())
316        }
317    }
318}
319
320#[cfg(test)]
321#[cfg_attr(coverage_nightly, coverage(off))]
322mod tests {
323    use super::*;
324
325    #[tokio::test]
326    async fn test_resolve_grpc_service_not_found() {
327        let dir = Arc::new(GearManager::new());
328        let api = LocalDirectoryClient::new(dir);
329
330        let err = api
331            .resolve_grpc_service("nonexistent.Service")
332            .await
333            .unwrap_err();
334        // Asserting `is_err()` alone would pass for a bare `anyhow` too, which
335        // is what this client used to return — and which
336        // `DirectoryEndpointResolver` reads as "the directory is broken".
337        assert!(
338            err.downcast_ref::<DirectoryNotFound>().is_some(),
339            "expected the typed not-found sentinel, got: {err:?}"
340        );
341    }
342
343    #[tokio::test]
344    async fn test_register_instance_via_api() {
345        let dir = Arc::new(GearManager::new());
346        let api = LocalDirectoryClient::new(dir.clone());
347
348        let instance_id = Uuid::new_v4();
349        // Register an instance through the API
350        let register_info = RegisterInstanceInfo::new("test_gear", instance_id.to_string())
351            .with_grpc_services(vec![(
352                "test.Service".to_owned(),
353                ServiceEndpoint::http("127.0.0.1", 8001),
354            )])
355            .with_version("1.0.0");
356
357        api.register_instance(register_info).await.unwrap();
358
359        // Verify the instance was registered
360        let instances = dir.instances_of("test_gear");
361        assert_eq!(instances.len(), 1);
362        assert_eq!(instances[0].instance_id, instance_id);
363        assert_eq!(instances[0].version, Some("1.0.0".to_owned()));
364        assert!(instances[0].grpc_services.contains_key("test.Service"));
365    }
366
367    /// A worker's presence loop and the hub register the same instance, each
368    /// with its own half, in any order and again on every self-heal or
369    /// retry: neither erases the other's gRPC services or `OpenAPI` spec.
370    #[tokio::test]
371    async fn presence_and_hub_registrations_keep_each_others_half() {
372        for hub_first in [true, false] {
373            // A fresh directory per order, so each starts from nothing.
374            let api = LocalDirectoryClient::new(Arc::new(GearManager::new()));
375            let id = Uuid::new_v4().to_string();
376            // What `OopServer`'s presence loop sends.
377            let presence = RegisterInstanceInfo::new("worker", &id)
378                .with_rest_endpoint(ServiceEndpoint::http("127.0.0.1", 8080))
379                .with_openapi_spec(r#"{"openapi":"3.1.0"}"#);
380            // What grpc-hub sends.
381            let hub = RegisterInstanceInfo::new("worker", &id)
382                .with_grpc_services(vec![(
383                    "worker.Svc".to_owned(),
384                    ServiceEndpoint::http("127.0.0.1", 50051),
385                )])
386                .with_version("1.0.0");
387            let order = if hub_first {
388                [&hub, &presence, &presence, &hub]
389            } else {
390                [&presence, &hub, &hub, &presence]
391            };
392            for info in order {
393                api.register_instance(info.clone()).await.unwrap();
394            }
395            let instances = api.list_instances("worker").await.unwrap();
396            assert_eq!(instances.len(), 1);
397            assert_eq!(instances[0].grpc_services.len(), 1, "gRPC services kept");
398            assert!(instances[0].rest_endpoint.is_some(), "REST endpoint kept");
399            assert_eq!(
400                api.get_openapi_spec("worker").await.unwrap(),
401                r#"{"openapi":"3.1.0"}"#,
402                "OpenAPI spec kept"
403            );
404        }
405    }
406
407    #[tokio::test]
408    async fn register_rejects_invalid_labels_at_store_boundary() {
409        // Validation is enforced at the store, not only at the gRPC front-end:
410        // an invalid label registered in-process must be rejected here (typed
411        // as DirectoryInvalidArgument) and never reach the manager.
412        let dir = Arc::new(GearManager::new());
413        let api = LocalDirectoryClient::new(Arc::clone(&dir));
414
415        let err = api
416            .register_instance(
417                RegisterInstanceInfo::new("worker", Uuid::new_v4().to_string())
418                    .with_rest_endpoint(ServiceEndpoint::new("http://worker:8080"))
419                    .with_labels(labels(&[("bad key", "7")])),
420            )
421            .await
422            .expect_err("an invalid label must be rejected at the store boundary");
423        assert!(
424            err.downcast_ref::<DirectoryInvalidArgument>().is_some(),
425            "store-boundary label rejection must be typed InvalidArgument, got: {err}"
426        );
427        assert!(
428            dir.instances_of("worker").is_empty(),
429            "a rejected registration must not be stored"
430        );
431    }
432
433    #[tokio::test]
434    async fn test_register_and_resolve_rest_and_openapi() {
435        let dir = Arc::new(GearManager::new());
436        let api = LocalDirectoryClient::new(dir.clone());
437
438        let instance_id = Uuid::new_v4();
439        let register_info = RegisterInstanceInfo::new("billing", instance_id.to_string())
440            .with_version("1.0.0")
441            .with_rest_endpoint(ServiceEndpoint::http("billing", 8080))
442            .with_openapi_spec("{\"openapi\":\"3.1.0\"}");
443
444        api.register_instance(register_info).await.unwrap();
445
446        // REST endpoint resolves to the registered base URL.
447        let resolved = api.resolve_rest_service("billing").await.unwrap();
448        assert_eq!(resolved.uri, concat!("http", "://billing:8080"));
449
450        // OpenAPI spec can be retrieved.
451        let spec = api.get_openapi_spec("billing").await.unwrap();
452        assert!(spec.contains("openapi"));
453    }
454
455    #[tokio::test]
456    async fn test_resolve_rest_and_openapi_not_found() {
457        let dir = Arc::new(GearManager::new());
458        let api = LocalDirectoryClient::new(dir);
459
460        // The typed sentinel is what distinguishes "provider not up yet" from
461        // a directory failure — see `DirectoryEndpointResolver`.
462        let rest_err = api.resolve_rest_service("missing").await.unwrap_err();
463        assert!(
464            rest_err.downcast_ref::<DirectoryNotFound>().is_some(),
465            "expected the typed not-found sentinel, got: {rest_err:?}"
466        );
467
468        let spec_err = api.get_openapi_spec("missing").await.unwrap_err();
469        assert!(
470            spec_err.downcast_ref::<DirectoryNotFound>().is_some(),
471            "expected the typed not-found sentinel, got: {spec_err:?}"
472        );
473    }
474
475    #[tokio::test]
476    async fn test_deregister_instance_via_api() {
477        let dir = Arc::new(GearManager::new());
478        let api = LocalDirectoryClient::new(dir.clone());
479
480        let instance_id = Uuid::new_v4();
481        // Register an instance first
482        let inst = Arc::new(GearInstance::new("test_gear", instance_id));
483        dir.register_instance(inst).unwrap();
484
485        // Verify it exists
486        assert_eq!(dir.instances_of("test_gear").len(), 1);
487
488        // Deregister via API
489        api.deregister_instance("test_gear", &instance_id.to_string())
490            .await
491            .unwrap();
492
493        // Verify it's gone
494        assert_eq!(dir.instances_of("test_gear").len(), 0);
495    }
496
497    #[tokio::test]
498    async fn test_send_heartbeat_via_api() {
499        use crate::runtime::InstanceState;
500
501        let dir = Arc::new(GearManager::new());
502        let api = LocalDirectoryClient::new(dir.clone());
503
504        let instance_id = Uuid::new_v4();
505        // Register an instance first
506        let inst = Arc::new(GearInstance::new("test_gear", instance_id));
507        dir.register_instance(inst).unwrap();
508
509        // Verify initial state is Registered
510        let instances = dir.instances_of("test_gear");
511        assert_eq!(instances[0].state(), InstanceState::Registered);
512
513        // Send heartbeat via API
514        api.send_heartbeat("test_gear", &instance_id.to_string())
515            .await
516            .unwrap();
517
518        // Verify state transitioned to Healthy
519        let instances = dir.instances_of("test_gear");
520        assert_eq!(instances[0].state(), InstanceState::Healthy);
521    }
522
523    #[tokio::test]
524    async fn test_list_all_instances_across_gears() {
525        let dir = Arc::new(GearManager::new());
526        let api = LocalDirectoryClient::new(Arc::clone(&dir));
527
528        // Two REST-only OoP gears (no gRPC services) + one gRPC-only gear.
529        for (gear, port) in [("billing", 8080u16), ("catalog", 8081u16)] {
530            api.register_instance(
531                RegisterInstanceInfo::new(gear, Uuid::new_v4().to_string())
532                    .with_version("1.0.0")
533                    .with_rest_endpoint(ServiceEndpoint::http(gear, port))
534                    .with_openapi_spec(format!("{{\"openapi\":\"3.1.0\",\"x\":\"{gear}\"}}")),
535            )
536            .await
537            .unwrap();
538        }
539
540        // gRPC-only gear: gRPC service metadata and no REST endpoint / spec. This
541        // exercises gRPC endpoint selection in `list_all_instances` (which prefers
542        // a gRPC endpoint for the primary `endpoint`).
543        api.register_instance(
544            RegisterInstanceInfo::new("reporting", Uuid::new_v4().to_string())
545                .with_grpc_services(vec![(
546                    "reporting.Service".to_owned(),
547                    ServiceEndpoint::new("http://reporting:7000"),
548                )])
549                .with_version("1.0.0"),
550        )
551        .await
552        .unwrap();
553
554        let all = api.list_all_instances().await.unwrap();
555        assert_eq!(all.len(), 3);
556
557        let billing = all.iter().find(|i| i.gear == "billing").expect("billing");
558        assert_eq!(
559            billing.rest_endpoint.as_ref().map(|e| e.uri.as_str()),
560            Some("http://billing:8080")
561        );
562        // The cross-gear snapshot never inlines the OpenAPI document; it carries
563        // only the hash, and consumers fetch the document per gear via
564        // `get_openapi_spec`.
565        assert!(billing.openapi_spec_hash.is_some());
566        assert!(
567            api.get_openapi_spec("billing")
568                .await
569                .expect("billing spec")
570                .contains("billing")
571        );
572
573        // The gRPC-only gear resolves its primary endpoint from gRPC metadata and
574        // carries no REST endpoint or OpenAPI spec.
575        let reporting = all
576            .iter()
577            .find(|i| i.gear == "reporting")
578            .expect("reporting");
579        assert_eq!(
580            reporting.endpoint.as_ref().map(|e| e.uri.as_str()),
581            Some("http://reporting:7000")
582        );
583        assert!(reporting.rest_endpoint.is_none());
584        assert!(reporting.openapi_spec_hash.is_none());
585    }
586
587    fn labels(pairs: &[(&str, &str)]) -> std::collections::BTreeMap<String, String> {
588        pairs
589            .iter()
590            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
591            .collect()
592    }
593
594    #[tokio::test]
595    async fn register_carries_labels_into_list_instances() {
596        let dir = Arc::new(GearManager::new());
597        let api = LocalDirectoryClient::new(Arc::clone(&dir));
598
599        api.register_instance(
600            RegisterInstanceInfo::new("worker", Uuid::new_v4().to_string())
601                .with_grpc_services(vec![(
602                    "worker.Svc".to_owned(),
603                    ServiceEndpoint::new("http://worker:7000"),
604                )])
605                .with_labels(labels(&[("shard", "7")])),
606        )
607        .await
608        .unwrap();
609
610        let listed = api.list_instances("worker").await.unwrap();
611        assert_eq!(listed.len(), 1);
612        assert_eq!(listed[0].labels.get("shard"), Some(&"7".to_owned()));
613    }
614
615    #[tokio::test]
616    async fn resolve_by_labels_selects_matching_instances() {
617        let dir = Arc::new(GearManager::new());
618        let api = LocalDirectoryClient::new(Arc::clone(&dir));
619
620        for (id, shard) in [("a", "7"), ("b", "8"), ("c", "7")] {
621            api.register_instance(
622                RegisterInstanceInfo::new("worker", Uuid::new_v4().to_string())
623                    .with_grpc_services(vec![(
624                        format!("worker.{id}"),
625                        ServiceEndpoint::new(format!("http://worker-{id}:7000")),
626                    )])
627                    .with_labels(labels(&[("shard", shard)])),
628            )
629            .await
630            .unwrap();
631        }
632
633        let matched = api
634            .resolve_by_labels("worker", &LabelSelector::new().with("shard", "7"))
635            .await
636            .unwrap();
637        assert_eq!(matched.len(), 2, "two instances carry shard=7");
638        assert!(
639            matched
640                .iter()
641                .all(|i| i.labels.get("shard") == Some(&"7".to_owned()))
642        );
643    }
644
645    #[tokio::test]
646    async fn labelless_reregister_preserves_labels_through_api() {
647        let dir = Arc::new(GearManager::new());
648        let api = LocalDirectoryClient::new(Arc::clone(&dir));
649
650        let instance_id = Uuid::new_v4().to_string();
651        api.register_instance(
652            RegisterInstanceInfo::new("worker", instance_id.clone())
653                .with_rest_endpoint(ServiceEndpoint::new("http://worker:8080"))
654                .with_labels(labels(&[("shard", "7")])),
655        )
656        .await
657        .unwrap();
658
659        // A label-less re-registration (e.g. self-heal) must not wipe the shard.
660        api.register_instance(
661            RegisterInstanceInfo::new("worker", instance_id)
662                .with_rest_endpoint(ServiceEndpoint::new("http://worker:8080"))
663                .with_version("2.0.0"),
664        )
665        .await
666        .unwrap();
667
668        let listed = api.list_instances("worker").await.unwrap();
669        assert_eq!(listed.len(), 1);
670        assert_eq!(
671            listed[0].labels.get("shard"),
672            Some(&"7".to_owned()),
673            "label-less re-registration must not wipe stored labels"
674        );
675
676        // And it is still selectable by the shard label.
677        let matched = api
678            .resolve_by_labels("worker", &LabelSelector::new().with("shard", "7"))
679            .await
680            .unwrap();
681        assert_eq!(matched.len(), 1);
682    }
683
684    #[tokio::test]
685    async fn resolve_by_labels_carries_live_serving_state() {
686        let dir = Arc::new(GearManager::new());
687        let api = LocalDirectoryClient::new(Arc::clone(&dir));
688
689        let instance_id = Uuid::new_v4();
690        api.register_instance(
691            RegisterInstanceInfo::new("worker", instance_id.to_string())
692                .with_grpc_services(vec![(
693                    "worker.Svc".to_owned(),
694                    ServiceEndpoint::new("http://worker:7000"),
695                )])
696                .with_labels(labels(&[("shard", "7")])),
697        )
698        .await
699        .unwrap();
700
701        // A freshly-registered instance is not yet serving.
702        let matched = api
703            .resolve_by_labels("worker", &LabelSelector::new().with("shard", "7"))
704            .await
705            .unwrap();
706        assert_eq!(matched.len(), 1);
707        assert_eq!(matched[0].state, InstanceState::Registered);
708        assert!(!matched[0].state.is_serving());
709
710        // A heartbeat transitions it to Healthy; the state must be projected
711        // onto the resolve result so a caller can filter on it.
712        assert!(dir.heartbeat("worker", instance_id, None));
713        let matched = api
714            .resolve_by_labels("worker", &LabelSelector::new().with("shard", "7"))
715            .await
716            .unwrap();
717        assert_eq!(matched[0].state, InstanceState::Healthy);
718        assert!(matched[0].state.is_serving());
719    }
720
721    #[tokio::test]
722    async fn resolve_by_labels_omits_openapi_spec() {
723        let dir = Arc::new(GearManager::new());
724        let api = LocalDirectoryClient::new(Arc::clone(&dir));
725
726        api.register_instance(
727            RegisterInstanceInfo::new("worker", Uuid::new_v4().to_string())
728                .with_rest_endpoint(ServiceEndpoint::new("http://worker:8080"))
729                .with_openapi_spec("{\"openapi\":\"3.1.0\"}")
730                .with_labels(labels(&[("shard", "7")])),
731        )
732        .await
733        .unwrap();
734
735        // The in-process label path is spec-free, matching the gRPC client.
736        let matched = api
737            .resolve_by_labels("worker", &LabelSelector::new().with("shard", "7"))
738            .await
739            .unwrap();
740        assert_eq!(matched.len(), 1);
741        assert!(
742            matched[0].openapi_spec_hash.is_some(),
743            "in-process resolve_by_labels carries only the spec hash, never the document"
744        );
745
746        // The plain enumeration path is spec-free too: only the hash rides
747        // along, the document is fetched via `get_openapi_spec`.
748        let listed = api.list_instances("worker").await.unwrap();
749        assert!(
750            listed[0].openapi_spec_hash.is_some(),
751            "list_instances must carry the spec hash, never the document"
752        );
753    }
754
755    #[tokio::test]
756    async fn list_all_instances_skips_endpoint_less() {
757        let dir = Arc::new(GearManager::new());
758        let api = LocalDirectoryClient::new(Arc::clone(&dir));
759
760        // One instance advertises a REST endpoint; the other advertises neither
761        // gRPC nor REST and must be skipped (no empty-URI sentinel).
762        api.register_instance(
763            RegisterInstanceInfo::new("worker", Uuid::new_v4().to_string())
764                .with_rest_endpoint(ServiceEndpoint::new("http://worker:8080")),
765        )
766        .await
767        .unwrap();
768        api.register_instance(RegisterInstanceInfo::new(
769            "placeholder",
770            Uuid::new_v4().to_string(),
771        ))
772        .await
773        .unwrap();
774
775        let all = api.list_all_instances().await.unwrap();
776        assert_eq!(all.len(), 1, "the endpoint-less instance is skipped");
777        assert_eq!(all[0].gear, "worker");
778        assert!(
779            all.iter()
780                .all(|i| i.endpoint.as_ref().is_some_and(|e| !e.uri.is_empty())),
781            "no instance may carry an absent or empty-URI endpoint"
782        );
783    }
784
785    #[tokio::test]
786    async fn label_path_returns_endpoint_less_match() {
787        let dir = Arc::new(GearManager::new());
788        let api = LocalDirectoryClient::new(Arc::clone(&dir));
789
790        // A matched instance that has not advertised any endpoint yet: treated
791        // as no-endpoint (not an error), so the label-targeting paths must still
792        // return the match (endpoint absent) rather than dropping it — the
793        // caller owns the fall-back decision.
794        api.register_instance(
795            RegisterInstanceInfo::new("worker", Uuid::new_v4().to_string())
796                .with_labels(labels(&[("shard", "7")])),
797        )
798        .await
799        .unwrap();
800
801        let matched = api
802            .resolve_by_labels("worker", &LabelSelector::new().with("shard", "7"))
803            .await
804            .unwrap();
805        assert_eq!(
806            matched.len(),
807            1,
808            "resolve_by_labels must return a matched instance even with no endpoint"
809        );
810        assert!(
811            matched[0].endpoint.is_none(),
812            "a no-endpoint match carries endpoint = None, not an empty-URI sentinel"
813        );
814        assert!(matched[0].rest_endpoint.is_none());
815        assert_eq!(matched[0].labels.get("shard"), Some(&"7".to_owned()));
816
817        // The base per-gear enumeration upholds the same contract.
818        let listed = api.list_instances("worker").await.unwrap();
819        assert_eq!(
820            listed.len(),
821            1,
822            "list_instances must not drop endpoint-less instances"
823        );
824        assert!(listed[0].endpoint.is_none());
825    }
826}