Skip to main content

cf_system_sdk_directory/grpc/
client.rs

1//! gRPC client implementation of Directory API
2//!
3//! This client allows remote gears to discover and resolve services via gRPC.
4
5use anyhow::Result;
6use async_trait::async_trait;
7use tonic::service::interceptor::InterceptedService;
8use tonic::transport::Channel;
9
10use std::time::Duration;
11
12use crate::api::{
13    DirectoryClient, DirectoryInvalidArgument, DirectoryNotFound, DirectoryPermissionDenied,
14    InstanceState, LabelSelector, RegisterAck, RegisterInstanceInfo, ReportedState,
15    ServiceEndpoint, ServiceInstanceInfo,
16};
17use crate::{ProtoInstanceState, ProtoReportedState};
18use std::collections::BTreeMap;
19use toolkit_transport_grpc::InternalAuthInterceptor;
20use toolkit_transport_grpc::client::{GrpcClientConfig, connect_lazy, connect_with_retry};
21
22use crate::{
23    DeregisterInstanceRequest, DirectoryServiceClient, GetOpenApiSpecRequest, GrpcServiceEndpoint,
24    HeartbeatRequest, InstanceInfo, ListAllInstancesRequest, ListInstancesRequest,
25    RegisterInstanceRequest, ResolveGrpcServiceRequest, ResolveRestServiceRequest,
26};
27
28/// Map a domain [`ReportedState`] onto the proto discriminant for the wire.
29fn reported_to_proto(reported: ReportedState) -> i32 {
30    match reported {
31        ReportedState::Starting => ProtoReportedState::Starting as i32,
32        ReportedState::Serving => ProtoReportedState::Serving as i32,
33        ReportedState::Draining => ProtoReportedState::Draining as i32,
34    }
35}
36
37/// The directory channel wrapped with the platform-plane
38/// [`InternalAuthInterceptor`], which attaches the gear's internal token
39/// (`x-toolkit-internal-token`) to every outbound system call. A
40/// [`disabled`](InternalAuthInterceptor::disabled) interceptor attaches
41/// nothing (Profile 1 / no platform-plane credential).
42type AuthedChannel = InterceptedService<Channel, InternalAuthInterceptor>;
43
44/// Map a lookup RPC's `tonic::Status` onto the directory's typed sentinels.
45///
46/// The status code is the only thing distinguishing "this name is not
47/// registered" from "the directory is unreachable", and stringifying the status
48/// throws it away. Callers downcast the result: `DirectoryEndpointResolver`
49/// turns `DirectoryNotFound` into `Ok(None)` (a provider that has not come up
50/// yet — routine during startup) and anything else into a real error.
51fn lookup_error(resource: &str, status: &tonic::Status) -> anyhow::Error {
52    match status.code() {
53        tonic::Code::NotFound => DirectoryNotFound::new(resource.to_owned()).into(),
54        tonic::Code::InvalidArgument => {
55            DirectoryInvalidArgument::new(status.message().to_owned()).into()
56        }
57        code => anyhow::anyhow!(
58            "directory lookup for {resource} failed: gRPC {code:?}: {}",
59            status.message()
60        ),
61    }
62}
63
64/// Map a mutating RPC's `tonic::Status`, preserving the code in the message.
65///
66/// A bare `"gRPC call failed"` hides whether the directory was unreachable
67/// (transient) or rejected the request permanently. The two permanent classes
68/// are typed so a caller retrying a mutation (e.g. the presence loop) can stop
69/// rather than spin forever:
70/// - `InvalidArgument` → [`DirectoryInvalidArgument`] (malformed request);
71/// - `PermissionDenied` → [`DirectoryPermissionDenied`] (a permanent decision:
72///   peer not authorized, namespace / trust domain not allowlisted, or a gRPC
73///   service name *pinned* to another gear by the ownership map).
74///
75/// Every other code stays an opaque, transient-by-default error (code kept in
76/// the message) and is retried:
77/// - `Unauthenticated` — a stale or rotated token is valid again on the next
78///   attempt, so a retry recovers what the permanent sentinel would strand;
79/// - `FailedPrecondition` — a *recoverable* gRPC service-name conflict (the name
80///   is merely currently advertised by another gear and frees up when it
81///   deregisters), retried rather than mislabeled as a permanent denial;
82/// - the transport-level transient codes (`Unavailable`, …).
83fn call_error(op: &str, status: &tonic::Status) -> anyhow::Error {
84    match status.code() {
85        tonic::Code::InvalidArgument => {
86            DirectoryInvalidArgument::new(status.message().to_owned()).into()
87        }
88        tonic::Code::PermissionDenied => {
89            DirectoryPermissionDenied::new(status.message().to_owned()).into()
90        }
91        code => anyhow::anyhow!("directory {op} failed: gRPC {code:?}: {}", status.message()),
92    }
93}
94
95/// gRPC client for Directory API
96///
97/// This client connects to a remote `DirectoryService` via gRPC and provides
98/// typed access to service discovery functionality. It includes:
99/// - Configurable timeouts and retries via transport stack
100/// - Automatic proto ↔ domain type conversions
101/// - Distributed tracing and metrics
102/// - Platform-plane credential attachment via an [`InternalAuthInterceptor`]
103///   (defaults to attaching nothing; supply one via the `*_with_interceptor`
104///   constructors for Profile-3 / shared-secret deployments)
105pub struct DirectoryGrpcClient {
106    inner: DirectoryServiceClient<AuthedChannel>,
107}
108
109impl DirectoryGrpcClient {
110    /// Connect to a directory service using default configuration with retries.
111    ///
112    /// Uses exponential backoff retry logic for reliable connection establishment.
113    /// This is the recommended method for `OoP` gears connecting to the master host.
114    ///
115    /// # Errors
116    /// It will return an error when it fails
117    pub async fn connect(uri: impl Into<String>) -> Result<Self> {
118        let cfg = GrpcClientConfig::new("directory");
119        Self::connect_with_retry(uri, &cfg).await
120    }
121
122    /// Connect with default configuration + retries, attaching `interceptor`'s
123    /// platform-plane credential to every outbound call.
124    ///
125    /// This is the Profile-3 / shared-secret entry point: the interceptor is
126    /// typically built from a
127    /// [`ServiceAccountTokenReader`](toolkit_transport_grpc::ServiceAccountTokenReader)
128    /// (rotating SA token) or
129    /// [`InternalAuthInterceptor::from_token`] (static shared secret).
130    ///
131    /// # Errors
132    /// It will return an error when it fails
133    pub async fn connect_with_interceptor(
134        uri: impl Into<String>,
135        interceptor: InternalAuthInterceptor,
136    ) -> Result<Self> {
137        let cfg = GrpcClientConfig::new("directory");
138        let channel: Channel = connect_with_retry(uri, &cfg).await?;
139        Ok(Self::from_channel_with_interceptor(channel, interceptor))
140    }
141
142    /// Create a directory client with a **lazily-connecting** channel.
143    ///
144    /// Performs **no** eager connection: the channel connects on the first RPC
145    /// and transparently reconnects on failure. This is the eventual-readiness
146    /// entry point (`cpt-cf-adr-eventual-readiness`) for `OoP` bootstrap — the
147    /// process starts even when the `DirectoryService` is not yet reachable, and
148    /// the presence loop's backoff retry absorbs the startup window instead of
149    /// the process crashing (which would offload retries onto a k8s
150    /// `CrashLoopBackOff`).
151    ///
152    /// # Runtime context
153    /// Must be called from within a Tokio runtime context: building the lazy
154    /// channel initialises the hyper reactor. Calling it outside a runtime
155    /// returns an error rather than panicking (it still does not connect).
156    ///
157    /// # Errors
158    /// Returns an error if called outside a Tokio runtime context, or if `uri`
159    /// is malformed — never for an unreachable peer.
160    pub fn connect_lazy(uri: impl Into<String>) -> Result<Self> {
161        let cfg = GrpcClientConfig::new("directory");
162        let channel: Channel = connect_lazy(uri, &cfg)?;
163        Ok(Self::from_channel(channel))
164    }
165
166    /// Create a directory client with a **lazily-connecting** channel, attaching
167    /// `interceptor`'s platform-plane credential to every outbound call.
168    ///
169    /// The lazy counterpart of [`connect_with_interceptor`](Self::connect_with_interceptor);
170    /// see [`connect_lazy`](Self::connect_lazy) for the connection semantics.
171    /// The URI is validated before `interceptor` is consumed, so the credential
172    /// is only moved into the client on success.
173    ///
174    /// # Errors
175    /// Returns an error only if `uri` is malformed — never for an unreachable
176    /// peer.
177    pub fn connect_lazy_with_interceptor(
178        uri: impl Into<String>,
179        interceptor: InternalAuthInterceptor,
180    ) -> Result<Self> {
181        let cfg = GrpcClientConfig::new("directory");
182        // Validate the URI (build the channel) before consuming `interceptor`.
183        let channel: Channel = connect_lazy(uri, &cfg)?;
184        Ok(Self::from_channel_with_interceptor(channel, interceptor))
185    }
186
187    /// Connect to a directory service with custom configuration and retry logic.
188    ///
189    /// Uses exponential backoff based on `cfg.max_retries`, `cfg.base_backoff`,
190    /// and `cfg.max_backoff` settings.
191    ///
192    /// # Errors
193    /// It will return an error when it fails
194    pub async fn connect_with_retry(
195        uri: impl Into<String>,
196        cfg: &GrpcClientConfig,
197    ) -> Result<Self> {
198        let channel: Channel = connect_with_retry(uri, cfg).await?;
199        Ok(Self::from_channel(channel))
200    }
201
202    /// Connect to a directory service without retry logic.
203    ///
204    /// This method attempts a single connection. Use `connect` or `connect_with_retry`
205    /// for production scenarios where the directory service may not be immediately available.
206    ///
207    /// # Errors
208    /// It will return an error when it fails
209    pub async fn connect_no_retry(uri: impl Into<String>, cfg: &GrpcClientConfig) -> Result<Self> {
210        let uri_string = uri.into();
211
212        // Create endpoint with timeouts from config
213        let endpoint = tonic::transport::Endpoint::from_shared(uri_string)?
214            .connect_timeout(cfg.connect_timeout)
215            .timeout(cfg.rpc_timeout);
216
217        // Connect to the service
218        let channel = endpoint.connect().await?;
219
220        if cfg.enable_tracing {
221            tracing::debug!(
222                service_name = cfg.service_name,
223                connect_timeout_ms = cfg.connect_timeout.as_millis(),
224                rpc_timeout_ms = cfg.rpc_timeout.as_millis(),
225                "directory gRPC client connected"
226            );
227        }
228
229        Ok(Self::from_channel(channel))
230    }
231
232    /// Create from an existing channel (useful for testing or custom setup).
233    ///
234    /// Attaches no platform-plane credential; use
235    /// [`from_channel_with_interceptor`](Self::from_channel_with_interceptor)
236    /// to attach one.
237    #[must_use]
238    pub fn from_channel(channel: Channel) -> Self {
239        Self::from_channel_with_interceptor(channel, InternalAuthInterceptor::disabled())
240    }
241
242    /// Create from an existing channel, attaching `interceptor`'s platform-plane
243    /// credential to every outbound call.
244    #[must_use]
245    pub fn from_channel_with_interceptor(
246        channel: Channel,
247        interceptor: InternalAuthInterceptor,
248    ) -> Self {
249        Self {
250            inner: DirectoryServiceClient::with_interceptor(channel, interceptor),
251        }
252    }
253}
254
255#[async_trait]
256impl DirectoryClient for DirectoryGrpcClient {
257    async fn resolve_grpc_service(&self, service_name: &str) -> Result<ServiceEndpoint> {
258        let mut client = self.inner.clone();
259        let request = tonic::Request::new(ResolveGrpcServiceRequest {
260            service_name: service_name.to_owned(),
261        });
262
263        let response = client
264            .resolve_grpc_service(request)
265            .await
266            .map_err(|e| lookup_error(&format!("service {service_name}"), &e))?;
267
268        let proto_response = response.into_inner();
269        Ok(ServiceEndpoint::new(proto_response.endpoint_uri))
270    }
271
272    async fn resolve_rest_service(&self, gear_name: &str) -> Result<ServiceEndpoint> {
273        let mut client = self.inner.clone();
274        let request = tonic::Request::new(ResolveRestServiceRequest {
275            gear_name: gear_name.to_owned(),
276        });
277
278        let response = client
279            .resolve_rest_service(request)
280            .await
281            .map_err(|e| lookup_error(&format!("gear {gear_name}"), &e))?;
282
283        let proto_response = response.into_inner();
284        Ok(ServiceEndpoint::new(proto_response.endpoint_uri))
285    }
286
287    async fn get_openapi_spec(&self, gear_name: &str) -> Result<String> {
288        let mut client = self.inner.clone();
289        let request = tonic::Request::new(GetOpenApiSpecRequest {
290            gear_name: gear_name.to_owned(),
291        });
292
293        let response = client
294            .get_open_api_spec(request)
295            .await
296            .map_err(|e| lookup_error(&format!("openapi spec for gear {gear_name}"), &e))?;
297
298        Ok(response.into_inner().openapi_spec)
299    }
300
301    async fn list_instances(&self, gear: &str) -> Result<Vec<ServiceInstanceInfo>> {
302        let mut client = self.inner.clone();
303        let request = tonic::Request::new(ListInstancesRequest {
304            gear_name: gear.to_owned(),
305            match_labels: std::collections::HashMap::new(),
306        });
307
308        let response = client
309            .list_instances(request)
310            .await
311            .map_err(|e| lookup_error(&format!("instances of gear {gear}"), &e))?;
312
313        let instances = response
314            .into_inner()
315            .instances
316            .into_iter()
317            .map(proto_instance_to_domain)
318            .collect();
319
320        Ok(instances)
321    }
322
323    async fn resolve_by_labels(
324        &self,
325        gear: &str,
326        selector: &LabelSelector,
327    ) -> Result<Vec<ServiceInstanceInfo>> {
328        // Push the selector server-side so the directory returns only matching
329        // instances. Every `list_instances` response is spec-free (only the
330        // `openapi_spec_hash` rides along; the document is fetched via
331        // `GetOpenApiSpec`), so an empty (match-all) selector never leaks a full
332        // OpenAPI document over the wire.
333        //
334        // cancel-safe: the single await is the unary `list_instances` RPC, which
335        // precedes any local state change; cancelling it just drops the in-flight
336        // response and leaves nothing partially applied.
337        let mut client = self.inner.clone();
338        let match_labels = selector
339            .match_labels
340            .iter()
341            .map(|(k, v)| (k.clone(), v.clone()))
342            .collect();
343        let request = tonic::Request::new(ListInstancesRequest {
344            gear_name: gear.to_owned(),
345            match_labels,
346        });
347
348        let response = client
349            .list_instances(request)
350            .await
351            .map_err(|e| lookup_error(&format!("instances of gear {gear}"), &e))?;
352
353        let instances = response
354            .into_inner()
355            .instances
356            .into_iter()
357            .map(proto_instance_to_domain)
358            .filter(|i| selector.matches(&i.labels))
359            .collect();
360
361        Ok(instances)
362    }
363
364    async fn list_all_instances(&self) -> Result<Vec<ServiceInstanceInfo>> {
365        let mut client = self.inner.clone();
366        let response = client
367            .list_all_instances(tonic::Request::new(ListAllInstancesRequest {}))
368            .await
369            .map_err(|e| lookup_error("all instances", &e))?;
370
371        let instances = response
372            .into_inner()
373            .instances
374            .into_iter()
375            .map(|proto| proto_instance_to_domain(proto).without_labels())
376            .collect();
377
378        Ok(instances)
379    }
380
381    async fn register_instance(&self, info: RegisterInstanceInfo) -> Result<()> {
382        self.register_with_lease(info).await.map(|_| ())
383    }
384
385    async fn register_with_lease(&self, info: RegisterInstanceInfo) -> Result<RegisterAck> {
386        let mut client = self.inner.clone();
387
388        // Convert gRPC service endpoints
389        let grpc_services = info
390            .grpc_services
391            .into_iter()
392            .map(|(name, ep)| GrpcServiceEndpoint {
393                service_name: name,
394                endpoint_uri: ep.uri,
395            })
396            .collect();
397
398        let req = RegisterInstanceRequest {
399            gear_name: info.gear,
400            instance_id: info.instance_id,
401            grpc_services,
402            version: info.version.unwrap_or_default(),
403            rest_endpoint_uri: info.rest_endpoint.map(|ep| ep.uri),
404            openapi_spec: info.openapi_spec,
405            labels: info.labels.into_iter().collect(),
406            reported_state: info.reported_state.map(reported_to_proto),
407        };
408
409        let gear_for_log = req.gear_name.clone();
410        let response = client
411            .register_instance(tonic::Request::new(req))
412            .await
413            .map_err(|e| call_error("register_instance", &e))?;
414
415        // A zero TTL means the directory returned none (e.g. an older server
416        // that answered Empty, which decodes as lease_ttl_ms = 0): the caller
417        // falls back to its configured heartbeat interval.
418        let lease_ttl_ms = response.into_inner().lease_ttl_ms;
419        if lease_ttl_ms == 0 {
420            // Unexpected in a co-versioned deployment; flag it rather than
421            // silently flapping on the fallback cadence.
422            tracing::warn!(
423                gear = %gear_for_log,
424                "directory granted no lease TTL on registration; using the fallback \
425                 heartbeat interval (expected only against a pre-lease DirectoryService)"
426            );
427        }
428        Ok(RegisterAck {
429            lease_ttl: (lease_ttl_ms > 0).then(|| Duration::from_millis(lease_ttl_ms)),
430        })
431    }
432
433    async fn deregister_instance(&self, gear: &str, instance_id: &str) -> Result<()> {
434        let mut client = self.inner.clone();
435
436        let req = DeregisterInstanceRequest {
437            gear_name: gear.to_owned(),
438            instance_id: instance_id.to_owned(),
439        };
440
441        client
442            .deregister_instance(tonic::Request::new(req))
443            .await
444            .map_err(|e| call_error("deregister_instance", &e))?;
445
446        Ok(())
447    }
448
449    async fn send_heartbeat(&self, gear: &str, instance_id: &str) -> Result<()> {
450        self.heartbeat(gear, instance_id, None).await
451    }
452
453    async fn heartbeat(
454        &self,
455        gear: &str,
456        instance_id: &str,
457        reported: Option<ReportedState>,
458    ) -> Result<()> {
459        let mut client = self.inner.clone();
460
461        let req = HeartbeatRequest {
462            gear_name: gear.to_owned(),
463            instance_id: instance_id.to_owned(),
464            reported_state: reported.map(reported_to_proto),
465        };
466
467        client
468            .heartbeat(tonic::Request::new(req))
469            .await
470            .map_err(|e| heartbeat_error(gear, instance_id, &e))?;
471
472        Ok(())
473    }
474}
475
476/// Map a `Heartbeat` RPC's `tonic::Status` onto the typed sentinels.
477///
478/// A heartbeat for an instance the directory does not know returns `NotFound`;
479/// the client surfaces it as [`DirectoryNotFound`] so the presence
480/// loop re-registers after one heartbeat instead of waiting on a self-heal
481/// timer. Every other status falls through to [`call_error`].
482fn heartbeat_error(gear: &str, instance_id: &str, status: &tonic::Status) -> anyhow::Error {
483    if status.code() == tonic::Code::NotFound {
484        return DirectoryNotFound::new(format!("instance {gear}/{instance_id}")).into();
485    }
486    call_error("heartbeat", status)
487}
488
489/// Convert a proto `InstanceInfo` into the domain [`ServiceInstanceInfo`].
490fn proto_instance_to_domain(proto: InstanceInfo) -> ServiceInstanceInfo {
491    ServiceInstanceInfo {
492        gear: proto.gear_name,
493        instance_id: proto.instance_id,
494        endpoint: if proto.endpoint_uri.is_empty() {
495            None
496        } else {
497            Some(ServiceEndpoint::new(proto.endpoint_uri))
498        },
499        version: if proto.version.is_empty() {
500            None
501        } else {
502            Some(proto.version)
503        },
504        rest_endpoint: proto.rest_endpoint_uri.map(ServiceEndpoint::new),
505        openapi_spec_hash: proto.openapi_spec_hash,
506        // The `InstanceInfo` proto message carries no per-service gRPC
507        // breakdown, so nothing to reconstruct over the OoP directory transport;
508        // only the in-process `LocalDirectoryClient` populates this (from the
509        // live `GearInstance`). No consumer reads `grpc_services` off a
510        // gRPC-obtained instance today — a single gRPC endpoint is available via
511        // the primary `endpoint`. When a label-targeted gRPC client needs the
512        // full per-service map remotely (the TopologyView work), add a
513        // `repeated GrpcServiceEndpoint grpc_services` field to `InstanceInfo`.
514        grpc_services: Vec::new(),
515        // Stable addressing labels cross the wire (ordering is normalized into a
516        // BTreeMap for deterministic selector matching).
517        labels: proto.labels.into_iter().collect::<BTreeMap<_, _>>(),
518        // Live serving state so label-targeted callers can filter on health.
519        state: proto_state_to_domain(proto.state),
520    }
521}
522
523/// Map the proto `InstanceState` (an open enum carried as `i32`) onto the
524/// domain [`InstanceState`].
525///
526/// `UNSPECIFIED` (a peer that never set the field, e.g. an older server) and
527/// any discriminant this build does not recognise map to the non-serving
528/// [`InstanceState::Unknown`] — kept distinct from
529/// [`InstanceState::Registered`] so "the state is unknown" is not silently read
530/// as a known pre-serving baseline. An unrecognised discriminant is logged so
531/// the version skew is observable rather than swallowed.
532fn proto_state_to_domain(state: i32) -> InstanceState {
533    match ProtoInstanceState::try_from(state) {
534        Ok(ProtoInstanceState::Ready) => InstanceState::Ready,
535        Ok(ProtoInstanceState::Healthy) => InstanceState::Healthy,
536        Ok(ProtoInstanceState::Quarantined) => InstanceState::Quarantined,
537        Ok(ProtoInstanceState::Draining) => InstanceState::Draining,
538        Ok(ProtoInstanceState::Registered) => InstanceState::Registered,
539        Ok(ProtoInstanceState::Unspecified) => InstanceState::Unknown,
540        Err(_) => {
541            tracing::warn!(
542                raw_state = state,
543                "directory returned an unrecognised InstanceState discriminant; \
544                 treating as Unknown (non-serving)"
545            );
546            InstanceState::Unknown
547        }
548    }
549}
550
551#[cfg(test)]
552#[cfg_attr(coverage_nightly, coverage(off))]
553mod tests {
554    use super::*;
555
556    #[tokio::test]
557    async fn test_grpc_client_can_be_constructed() {
558        // Smoke test to ensure types compile and connect
559        let endpoint = tonic::transport::Endpoint::from_static("http://[::1]:50051");
560
561        // We can't actually connect without a server, but we can construct the client type
562        // This ensures the API is correct
563        let channel_result = endpoint.connect().await;
564
565        // It's expected to fail since there's no server, but if it does somehow succeed:
566        if let Ok(channel) = channel_result {
567            let _client = DirectoryGrpcClient::from_channel(channel);
568        }
569    }
570
571    #[tokio::test]
572    async fn from_channel_constructs_without_connecting() {
573        // `connect_lazy` yields a Channel without a live server, so both the
574        // default (no-credential) and interceptor-bearing constructors can be
575        // exercised offline.
576        let channel = Channel::from_static("http://[::1]:50051").connect_lazy();
577        let _default = DirectoryGrpcClient::from_channel(channel.clone());
578        let _authed = DirectoryGrpcClient::from_channel_with_interceptor(
579            channel,
580            InternalAuthInterceptor::disabled(),
581        );
582    }
583
584    #[tokio::test]
585    async fn connect_lazy_succeeds_against_unreachable_peer() {
586        // The lazy constructor performs no eager connect, so an OoP gear can
587        // build its directory client before the `DirectoryService` is up
588        // (`cpt-cf-adr-eventual-readiness`). Nothing is listening on port 1, yet
589        // both the plain and interceptor-bearing constructors return `Ok`.
590        let plain = DirectoryGrpcClient::connect_lazy("http://127.0.0.1:1");
591        assert!(
592            plain.is_ok(),
593            "connect_lazy must not eagerly connect (unreachable peer -> Ok)"
594        );
595
596        let authed = DirectoryGrpcClient::connect_lazy_with_interceptor(
597            "http://127.0.0.1:1",
598            InternalAuthInterceptor::disabled(),
599        );
600        assert!(
601            authed.is_ok(),
602            "connect_lazy_with_interceptor must not eagerly connect (unreachable peer -> Ok)"
603        );
604    }
605
606    #[tokio::test]
607    async fn connect_lazy_rejects_malformed_uri() {
608        // A malformed endpoint is a static misconfiguration worth failing fast
609        // on — the only error path of the lazy constructors.
610        assert!(
611            DirectoryGrpcClient::connect_lazy(String::new()).is_err(),
612            "connect_lazy should fail on a malformed URI"
613        );
614        assert!(
615            DirectoryGrpcClient::connect_lazy_with_interceptor(
616                String::new(),
617                InternalAuthInterceptor::disabled(),
618            )
619            .is_err(),
620            "connect_lazy_with_interceptor should fail on a malformed URI"
621        );
622    }
623
624    #[tokio::test]
625    async fn resolve_grpc_service_through_lazy_client_errors_not_hangs() {
626        // A lazy client builds against an unreachable directory; the first RPC
627        // returns a lookup/call error rather than hanging (outer timeout proves
628        // non-hang; nothing is listening on port 1).
629        let client =
630            DirectoryGrpcClient::connect_lazy("http://127.0.0.1:1").expect("lazy build ok");
631        let outcome = tokio::time::timeout(
632            std::time::Duration::from_secs(5),
633            client.resolve_grpc_service(crate::DIRECTORY_SERVICE_NAME),
634        )
635        .await;
636        assert!(
637            outcome.is_ok(),
638            "resolve_grpc_service through a lazy client must not hang against an unreachable peer"
639        );
640        assert!(
641            outcome.unwrap().is_err(),
642            "resolve_grpc_service against an unreachable directory must return Err"
643        );
644    }
645
646    #[test]
647    fn proto_instance_maps_all_fields_to_domain() {
648        let proto = InstanceInfo {
649            gear_name: "calc".to_owned(),
650            instance_id: "calc-1".to_owned(),
651            endpoint_uri: "http://calc:8080".to_owned(),
652            version: "1.2.3".to_owned(),
653            rest_endpoint_uri: Some("http://calc:8080".to_owned()),
654            openapi_spec_hash: Some("1a2b3c4d5e6f7a8b".to_owned()),
655            labels: [("shard".to_owned(), "7".to_owned())].into_iter().collect(),
656            state: ProtoInstanceState::Healthy as i32,
657        };
658        let domain = proto_instance_to_domain(proto);
659        assert_eq!(domain.gear, "calc");
660        assert_eq!(domain.state, InstanceState::Healthy);
661        assert_eq!(domain.instance_id, "calc-1");
662        assert_eq!(
663            domain.endpoint.as_ref().map(|e| e.uri.as_str()),
664            Some("http://calc:8080")
665        );
666        assert_eq!(domain.version.as_deref(), Some("1.2.3"));
667        assert_eq!(
668            domain.rest_endpoint.map(|e| e.uri),
669            Some("http://calc:8080".to_owned())
670        );
671        // Enumeration is spec-free: only the hash crosses the wire.
672        assert_eq!(
673            domain.openapi_spec_hash.as_deref(),
674            Some("1a2b3c4d5e6f7a8b")
675        );
676        // Labels cross the wire and land in a BTreeMap for deterministic matching.
677        assert_eq!(domain.labels.get("shard"), Some(&"7".to_owned()));
678    }
679
680    #[test]
681    fn proto_instance_maps_empty_version_to_none() {
682        let proto = InstanceInfo {
683            gear_name: "worker".to_owned(),
684            instance_id: "worker-1".to_owned(),
685            endpoint_uri: "http://worker:7000".to_owned(),
686            version: String::new(),
687            rest_endpoint_uri: None,
688            openapi_spec_hash: None,
689            labels: std::collections::HashMap::new(),
690            state: ProtoInstanceState::Unspecified as i32,
691        };
692        let domain = proto_instance_to_domain(proto);
693        // A non-empty proto endpoint_uri maps to `Some`.
694        assert_eq!(
695            domain.endpoint.as_ref().map(|e| e.uri.as_str()),
696            Some("http://worker:7000")
697        );
698        // An empty proto version string maps to `None` rather than an empty string.
699        assert!(domain.version.is_none());
700        assert!(domain.rest_endpoint.is_none());
701        assert!(domain.openapi_spec_hash.is_none());
702        assert!(domain.labels.is_empty());
703        // An unset proto state (`UNSPECIFIED`) maps to the non-serving Unknown
704        // sentinel — distinct from the pre-serving Registered baseline.
705        assert_eq!(domain.state, InstanceState::Unknown);
706        assert!(!domain.state.is_serving());
707    }
708
709    #[test]
710    fn proto_instance_maps_empty_endpoint_to_none() {
711        // proto3 carries an absent primary endpoint as an empty string; it must
712        // map back to `None`, not an empty-URI sentinel a dialer could mistake
713        // for a real address.
714        let proto = InstanceInfo {
715            gear_name: "grpc-only".to_owned(),
716            instance_id: "g-1".to_owned(),
717            endpoint_uri: String::new(),
718            version: String::new(),
719            rest_endpoint_uri: None,
720            openapi_spec_hash: None,
721            labels: std::collections::HashMap::new(),
722            state: ProtoInstanceState::Ready as i32,
723        };
724        let domain = proto_instance_to_domain(proto);
725        assert!(
726            domain.endpoint.is_none(),
727            "an empty proto endpoint_uri must map to None"
728        );
729    }
730
731    #[test]
732    fn proto_state_unspecified_and_unrecognised_map_to_unknown() {
733        // `UNSPECIFIED` (peer never set the field) and any discriminant this
734        // build does not know (e.g. a newer server) both collapse to the
735        // non-serving Unknown sentinel rather than being read as Registered.
736        assert_eq!(
737            proto_state_to_domain(ProtoInstanceState::Unspecified as i32),
738            InstanceState::Unknown
739        );
740        assert_eq!(proto_state_to_domain(9999), InstanceState::Unknown);
741        assert!(!proto_state_to_domain(9999).is_serving());
742
743        // Known discriminants still map through unchanged.
744        assert_eq!(
745            proto_state_to_domain(ProtoInstanceState::Registered as i32),
746            InstanceState::Registered
747        );
748        assert_eq!(
749            proto_state_to_domain(ProtoInstanceState::Healthy as i32),
750            InstanceState::Healthy
751        );
752    }
753
754    #[test]
755    fn call_error_types_invalid_argument_as_permanent() {
756        let err = call_error(
757            "register_instance",
758            &tonic::Status::invalid_argument("bad label"),
759        );
760        assert!(
761            err.downcast_ref::<DirectoryInvalidArgument>().is_some(),
762            "InvalidArgument must map to the typed permanent DirectoryInvalidArgument"
763        );
764    }
765
766    #[test]
767    fn call_error_types_permission_denied_as_permanent() {
768        // A true authorization decision (peer not authorized, or namespace /
769        // trust domain not allowlisted) is permanent, so the presence loop stops
770        // retrying.
771        let err = call_error(
772            "register_instance",
773            &tonic::Status::permission_denied("peer not authorized"),
774        );
775        assert!(
776            err.downcast_ref::<DirectoryPermissionDenied>().is_some(),
777            "PermissionDenied must map to the typed permanent DirectoryPermissionDenied"
778        );
779    }
780
781    #[test]
782    fn call_error_keeps_transient_codes_opaque() {
783        // Transient codes stay untyped (code preserved in the message) so the
784        // presence loop keeps retrying:
785        // - `Unauthenticated` — a stale/rotated credential must not collapse to
786        //   the permanent sentinel;
787        // - `FailedPrecondition` — a recoverable gRPC service-name conflict must
788        //   not be mislabeled as a permanent authorization denial.
789        for status in [
790            tonic::Status::unavailable("connection reset"),
791            tonic::Status::unauthenticated("invalid internal token"),
792            tonic::Status::failed_precondition("service name already owned by another gear"),
793        ] {
794            let err = call_error("heartbeat", &status);
795            assert!(err.downcast_ref::<DirectoryInvalidArgument>().is_none());
796            assert!(
797                err.downcast_ref::<DirectoryPermissionDenied>().is_none(),
798                "{:?} must stay transient/retryable, not map to DirectoryPermissionDenied",
799                status.code()
800            );
801            assert!(err.to_string().contains(&format!("{:?}", status.code())));
802        }
803    }
804}