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, GrpcServiceEndpoint, HeartbeatRequest,
24    InstanceInfo, ListAllInstancesRequest, ListInstancesRequest, RegisterInstanceRequest,
25    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 list_instances(&self, gear: &str) -> Result<Vec<ServiceInstanceInfo>> {
288        let mut client = self.inner.clone();
289        let request = tonic::Request::new(ListInstancesRequest {
290            gear_name: gear.to_owned(),
291            match_labels: std::collections::HashMap::new(),
292        });
293
294        let response = client
295            .list_instances(request)
296            .await
297            .map_err(|e| lookup_error(&format!("instances of gear {gear}"), &e))?;
298
299        let instances = response
300            .into_inner()
301            .instances
302            .into_iter()
303            .map(proto_instance_to_domain)
304            .collect();
305
306        Ok(instances)
307    }
308
309    async fn resolve_by_labels(
310        &self,
311        gear: &str,
312        selector: &LabelSelector,
313    ) -> Result<Vec<ServiceInstanceInfo>> {
314        // Push the selector server-side so the directory returns only matching
315        // instances. Every `list_instances` response is spec-free (only the
316        // `openapi_spec_hash` rides along; the document is fetched from the
317        // instance's `/.well-known/openapi.json`), so an empty (match-all)
318        // selector never leaks a full OpenAPI document over the wire.
319        //
320        // cancel-safe: the single await is the unary `list_instances` RPC, which
321        // precedes any local state change; cancelling it just drops the in-flight
322        // response and leaves nothing partially applied.
323        let mut client = self.inner.clone();
324        let match_labels = selector
325            .match_labels
326            .iter()
327            .map(|(k, v)| (k.clone(), v.clone()))
328            .collect();
329        let request = tonic::Request::new(ListInstancesRequest {
330            gear_name: gear.to_owned(),
331            match_labels,
332        });
333
334        let response = client
335            .list_instances(request)
336            .await
337            .map_err(|e| lookup_error(&format!("instances of gear {gear}"), &e))?;
338
339        let instances = response
340            .into_inner()
341            .instances
342            .into_iter()
343            .map(proto_instance_to_domain)
344            .filter(|i| selector.matches(&i.labels))
345            .collect();
346
347        Ok(instances)
348    }
349
350    async fn list_all_instances(&self) -> Result<Vec<ServiceInstanceInfo>> {
351        let mut client = self.inner.clone();
352        let response = client
353            .list_all_instances(tonic::Request::new(ListAllInstancesRequest {}))
354            .await
355            .map_err(|e| lookup_error("all instances", &e))?;
356
357        let instances = response
358            .into_inner()
359            .instances
360            .into_iter()
361            .map(|proto| proto_instance_to_domain(proto).without_labels())
362            .collect();
363
364        Ok(instances)
365    }
366
367    async fn register_instance(&self, info: RegisterInstanceInfo) -> Result<()> {
368        self.register_with_lease(info).await.map(|_| ())
369    }
370
371    async fn register_with_lease(&self, info: RegisterInstanceInfo) -> Result<RegisterAck> {
372        let mut client = self.inner.clone();
373
374        // Convert gRPC service endpoints
375        let grpc_services = info
376            .grpc_services
377            .into_iter()
378            .map(|(name, ep)| GrpcServiceEndpoint {
379                service_name: name,
380                endpoint_uri: ep.uri,
381            })
382            .collect();
383
384        let req = RegisterInstanceRequest {
385            gear_name: info.gear,
386            instance_id: info.instance_id,
387            grpc_services,
388            version: info.version.unwrap_or_default(),
389            rest_endpoint_uri: info.rest_endpoint.map(|ep| ep.uri),
390            labels: info.labels.into_iter().collect(),
391            reported_state: info.reported_state.map(reported_to_proto),
392            openapi_spec_hash: info.openapi_spec_hash,
393        };
394
395        let gear_for_log = req.gear_name.clone();
396        let response = client
397            .register_instance(tonic::Request::new(req))
398            .await
399            .map_err(|e| call_error("register_instance", &e))?;
400
401        // A zero TTL means the directory returned none (e.g. an older server
402        // that answered Empty, which decodes as lease_ttl_ms = 0): the caller
403        // falls back to its configured heartbeat interval.
404        let lease_ttl_ms = response.into_inner().lease_ttl_ms;
405        if lease_ttl_ms == 0 {
406            // Unexpected in a co-versioned deployment; flag it rather than
407            // silently flapping on the fallback cadence.
408            tracing::warn!(
409                gear = %gear_for_log,
410                "directory granted no lease TTL on registration; using the fallback \
411                 heartbeat interval (expected only against a pre-lease DirectoryService)"
412            );
413        }
414        Ok(RegisterAck {
415            lease_ttl: (lease_ttl_ms > 0).then(|| Duration::from_millis(lease_ttl_ms)),
416        })
417    }
418
419    async fn deregister_instance(&self, gear: &str, instance_id: &str) -> Result<()> {
420        let mut client = self.inner.clone();
421
422        let req = DeregisterInstanceRequest {
423            gear_name: gear.to_owned(),
424            instance_id: instance_id.to_owned(),
425        };
426
427        client
428            .deregister_instance(tonic::Request::new(req))
429            .await
430            .map_err(|e| call_error("deregister_instance", &e))?;
431
432        Ok(())
433    }
434
435    async fn send_heartbeat(&self, gear: &str, instance_id: &str) -> Result<()> {
436        self.heartbeat(gear, instance_id, None).await
437    }
438
439    async fn heartbeat(
440        &self,
441        gear: &str,
442        instance_id: &str,
443        reported: Option<ReportedState>,
444    ) -> Result<()> {
445        let mut client = self.inner.clone();
446
447        let req = HeartbeatRequest {
448            gear_name: gear.to_owned(),
449            instance_id: instance_id.to_owned(),
450            reported_state: reported.map(reported_to_proto),
451        };
452
453        client
454            .heartbeat(tonic::Request::new(req))
455            .await
456            .map_err(|e| heartbeat_error(gear, instance_id, &e))?;
457
458        Ok(())
459    }
460}
461
462/// Map a `Heartbeat` RPC's `tonic::Status` onto the typed sentinels.
463///
464/// A heartbeat for an instance the directory does not know returns `NotFound`;
465/// the client surfaces it as [`DirectoryNotFound`] so the presence
466/// loop re-registers after one heartbeat instead of waiting on a self-heal
467/// timer. Every other status falls through to [`call_error`].
468fn heartbeat_error(gear: &str, instance_id: &str, status: &tonic::Status) -> anyhow::Error {
469    if status.code() == tonic::Code::NotFound {
470        return DirectoryNotFound::new(format!("instance {gear}/{instance_id}")).into();
471    }
472    call_error("heartbeat", status)
473}
474
475/// Convert a proto `InstanceInfo` into the domain [`ServiceInstanceInfo`].
476fn proto_instance_to_domain(proto: InstanceInfo) -> ServiceInstanceInfo {
477    ServiceInstanceInfo {
478        gear: proto.gear_name,
479        instance_id: proto.instance_id,
480        endpoint: if proto.endpoint_uri.is_empty() {
481            None
482        } else {
483            Some(ServiceEndpoint::new(proto.endpoint_uri))
484        },
485        version: if proto.version.is_empty() {
486            None
487        } else {
488            Some(proto.version)
489        },
490        rest_endpoint: proto.rest_endpoint_uri.map(ServiceEndpoint::new),
491        openapi_spec_hash: proto.openapi_spec_hash,
492        // The `InstanceInfo` proto message carries no per-service gRPC
493        // breakdown, so nothing to reconstruct over the OoP directory transport;
494        // only the in-process `LocalDirectoryClient` populates this (from the
495        // live `GearInstance`). No consumer reads `grpc_services` off a
496        // gRPC-obtained instance today — a single gRPC endpoint is available via
497        // the primary `endpoint`. When a label-targeted gRPC client needs the
498        // full per-service map remotely (the TopologyView work), add a
499        // `repeated GrpcServiceEndpoint grpc_services` field to `InstanceInfo`.
500        grpc_services: Vec::new(),
501        // Stable addressing labels cross the wire (ordering is normalized into a
502        // BTreeMap for deterministic selector matching).
503        labels: proto.labels.into_iter().collect::<BTreeMap<_, _>>(),
504        // Live serving state so label-targeted callers can filter on health.
505        state: proto_state_to_domain(proto.state),
506    }
507}
508
509/// Map the proto `InstanceState` (an open enum carried as `i32`) onto the
510/// domain [`InstanceState`].
511///
512/// `UNSPECIFIED` (a peer that never set the field, e.g. an older server) and
513/// any discriminant this build does not recognise map to the non-serving
514/// [`InstanceState::Unknown`] — kept distinct from
515/// [`InstanceState::Registered`] so "the state is unknown" is not silently read
516/// as a known pre-serving baseline. An unrecognised discriminant is logged so
517/// the version skew is observable rather than swallowed.
518fn proto_state_to_domain(state: i32) -> InstanceState {
519    match ProtoInstanceState::try_from(state) {
520        Ok(ProtoInstanceState::Ready) => InstanceState::Ready,
521        Ok(ProtoInstanceState::Healthy) => InstanceState::Healthy,
522        Ok(ProtoInstanceState::Quarantined) => InstanceState::Quarantined,
523        Ok(ProtoInstanceState::Draining) => InstanceState::Draining,
524        Ok(ProtoInstanceState::Registered) => InstanceState::Registered,
525        Ok(ProtoInstanceState::Unspecified) => InstanceState::Unknown,
526        Err(_) => {
527            tracing::warn!(
528                raw_state = state,
529                "directory returned an unrecognised InstanceState discriminant; \
530                 treating as Unknown (non-serving)"
531            );
532            InstanceState::Unknown
533        }
534    }
535}
536
537#[cfg(test)]
538#[cfg_attr(coverage_nightly, coverage(off))]
539mod tests {
540    use super::*;
541
542    #[tokio::test]
543    async fn test_grpc_client_can_be_constructed() {
544        // Smoke test to ensure types compile and connect
545        let endpoint = tonic::transport::Endpoint::from_static("http://[::1]:50051");
546
547        // We can't actually connect without a server, but we can construct the client type
548        // This ensures the API is correct
549        let channel_result = endpoint.connect().await;
550
551        // It's expected to fail since there's no server, but if it does somehow succeed:
552        if let Ok(channel) = channel_result {
553            let _client = DirectoryGrpcClient::from_channel(channel);
554        }
555    }
556
557    #[tokio::test]
558    async fn from_channel_constructs_without_connecting() {
559        // `connect_lazy` yields a Channel without a live server, so both the
560        // default (no-credential) and interceptor-bearing constructors can be
561        // exercised offline.
562        let channel = Channel::from_static("http://[::1]:50051").connect_lazy();
563        let _default = DirectoryGrpcClient::from_channel(channel.clone());
564        let _authed = DirectoryGrpcClient::from_channel_with_interceptor(
565            channel,
566            InternalAuthInterceptor::disabled(),
567        );
568    }
569
570    #[tokio::test]
571    async fn connect_lazy_succeeds_against_unreachable_peer() {
572        // The lazy constructor performs no eager connect, so an OoP gear can
573        // build its directory client before the `DirectoryService` is up
574        // (`cpt-cf-adr-eventual-readiness`). Nothing is listening on port 1, yet
575        // both the plain and interceptor-bearing constructors return `Ok`.
576        let plain = DirectoryGrpcClient::connect_lazy("http://127.0.0.1:1");
577        assert!(
578            plain.is_ok(),
579            "connect_lazy must not eagerly connect (unreachable peer -> Ok)"
580        );
581
582        let authed = DirectoryGrpcClient::connect_lazy_with_interceptor(
583            "http://127.0.0.1:1",
584            InternalAuthInterceptor::disabled(),
585        );
586        assert!(
587            authed.is_ok(),
588            "connect_lazy_with_interceptor must not eagerly connect (unreachable peer -> Ok)"
589        );
590    }
591
592    #[tokio::test]
593    async fn connect_lazy_rejects_malformed_uri() {
594        // A malformed endpoint is a static misconfiguration worth failing fast
595        // on — the only error path of the lazy constructors.
596        assert!(
597            DirectoryGrpcClient::connect_lazy(String::new()).is_err(),
598            "connect_lazy should fail on a malformed URI"
599        );
600        assert!(
601            DirectoryGrpcClient::connect_lazy_with_interceptor(
602                String::new(),
603                InternalAuthInterceptor::disabled(),
604            )
605            .is_err(),
606            "connect_lazy_with_interceptor should fail on a malformed URI"
607        );
608    }
609
610    #[tokio::test]
611    async fn resolve_grpc_service_through_lazy_client_errors_not_hangs() {
612        // A lazy client builds against an unreachable directory; the first RPC
613        // returns a lookup/call error rather than hanging (outer timeout proves
614        // non-hang; nothing is listening on port 1).
615        let client =
616            DirectoryGrpcClient::connect_lazy("http://127.0.0.1:1").expect("lazy build ok");
617        let outcome = tokio::time::timeout(
618            std::time::Duration::from_secs(5),
619            client.resolve_grpc_service(crate::DIRECTORY_SERVICE_NAME),
620        )
621        .await;
622        assert!(
623            outcome.is_ok(),
624            "resolve_grpc_service through a lazy client must not hang against an unreachable peer"
625        );
626        assert!(
627            outcome.unwrap().is_err(),
628            "resolve_grpc_service against an unreachable directory must return Err"
629        );
630    }
631
632    #[test]
633    fn proto_instance_maps_all_fields_to_domain() {
634        let proto = InstanceInfo {
635            gear_name: "calc".to_owned(),
636            instance_id: "calc-1".to_owned(),
637            endpoint_uri: "http://calc:8080".to_owned(),
638            version: "1.2.3".to_owned(),
639            rest_endpoint_uri: Some("http://calc:8080".to_owned()),
640            openapi_spec_hash: Some("1a2b3c4d5e6f7a8b".to_owned()),
641            labels: [("shard".to_owned(), "7".to_owned())].into_iter().collect(),
642            state: ProtoInstanceState::Healthy as i32,
643        };
644        let domain = proto_instance_to_domain(proto);
645        assert_eq!(domain.gear, "calc");
646        assert_eq!(domain.state, InstanceState::Healthy);
647        assert_eq!(domain.instance_id, "calc-1");
648        assert_eq!(
649            domain.endpoint.as_ref().map(|e| e.uri.as_str()),
650            Some("http://calc:8080")
651        );
652        assert_eq!(domain.version.as_deref(), Some("1.2.3"));
653        assert_eq!(
654            domain.rest_endpoint.map(|e| e.uri),
655            Some("http://calc:8080".to_owned())
656        );
657        // Enumeration is spec-free: only the hash crosses the wire.
658        assert_eq!(
659            domain.openapi_spec_hash.as_deref(),
660            Some("1a2b3c4d5e6f7a8b")
661        );
662        // Labels cross the wire and land in a BTreeMap for deterministic matching.
663        assert_eq!(domain.labels.get("shard"), Some(&"7".to_owned()));
664    }
665
666    #[test]
667    fn proto_instance_maps_empty_version_to_none() {
668        let proto = InstanceInfo {
669            gear_name: "worker".to_owned(),
670            instance_id: "worker-1".to_owned(),
671            endpoint_uri: "http://worker:7000".to_owned(),
672            version: String::new(),
673            rest_endpoint_uri: None,
674            openapi_spec_hash: None,
675            labels: std::collections::HashMap::new(),
676            state: ProtoInstanceState::Unspecified as i32,
677        };
678        let domain = proto_instance_to_domain(proto);
679        // A non-empty proto endpoint_uri maps to `Some`.
680        assert_eq!(
681            domain.endpoint.as_ref().map(|e| e.uri.as_str()),
682            Some("http://worker:7000")
683        );
684        // An empty proto version string maps to `None` rather than an empty string.
685        assert!(domain.version.is_none());
686        assert!(domain.rest_endpoint.is_none());
687        assert!(domain.openapi_spec_hash.is_none());
688        assert!(domain.labels.is_empty());
689        // An unset proto state (`UNSPECIFIED`) maps to the non-serving Unknown
690        // sentinel — distinct from the pre-serving Registered baseline.
691        assert_eq!(domain.state, InstanceState::Unknown);
692        assert!(!domain.state.is_serving());
693    }
694
695    #[test]
696    fn proto_instance_maps_empty_endpoint_to_none() {
697        // proto3 carries an absent primary endpoint as an empty string; it must
698        // map back to `None`, not an empty-URI sentinel a dialer could mistake
699        // for a real address.
700        let proto = InstanceInfo {
701            gear_name: "grpc-only".to_owned(),
702            instance_id: "g-1".to_owned(),
703            endpoint_uri: String::new(),
704            version: String::new(),
705            rest_endpoint_uri: None,
706            openapi_spec_hash: None,
707            labels: std::collections::HashMap::new(),
708            state: ProtoInstanceState::Ready as i32,
709        };
710        let domain = proto_instance_to_domain(proto);
711        assert!(
712            domain.endpoint.is_none(),
713            "an empty proto endpoint_uri must map to None"
714        );
715    }
716
717    #[test]
718    fn proto_state_unspecified_and_unrecognised_map_to_unknown() {
719        // `UNSPECIFIED` (peer never set the field) and any discriminant this
720        // build does not know (e.g. a newer server) both collapse to the
721        // non-serving Unknown sentinel rather than being read as Registered.
722        assert_eq!(
723            proto_state_to_domain(ProtoInstanceState::Unspecified as i32),
724            InstanceState::Unknown
725        );
726        assert_eq!(proto_state_to_domain(9999), InstanceState::Unknown);
727        assert!(!proto_state_to_domain(9999).is_serving());
728
729        // Known discriminants still map through unchanged.
730        assert_eq!(
731            proto_state_to_domain(ProtoInstanceState::Registered as i32),
732            InstanceState::Registered
733        );
734        assert_eq!(
735            proto_state_to_domain(ProtoInstanceState::Healthy as i32),
736            InstanceState::Healthy
737        );
738    }
739
740    #[test]
741    fn call_error_types_invalid_argument_as_permanent() {
742        let err = call_error(
743            "register_instance",
744            &tonic::Status::invalid_argument("bad label"),
745        );
746        assert!(
747            err.downcast_ref::<DirectoryInvalidArgument>().is_some(),
748            "InvalidArgument must map to the typed permanent DirectoryInvalidArgument"
749        );
750    }
751
752    #[test]
753    fn call_error_types_permission_denied_as_permanent() {
754        // A true authorization decision (peer not authorized, or namespace /
755        // trust domain not allowlisted) is permanent, so the presence loop stops
756        // retrying.
757        let err = call_error(
758            "register_instance",
759            &tonic::Status::permission_denied("peer not authorized"),
760        );
761        assert!(
762            err.downcast_ref::<DirectoryPermissionDenied>().is_some(),
763            "PermissionDenied must map to the typed permanent DirectoryPermissionDenied"
764        );
765    }
766
767    #[test]
768    fn call_error_keeps_transient_codes_opaque() {
769        // Transient codes stay untyped (code preserved in the message) so the
770        // presence loop keeps retrying:
771        // - `Unauthenticated` — a stale/rotated credential must not collapse to
772        //   the permanent sentinel;
773        // - `FailedPrecondition` — a recoverable gRPC service-name conflict must
774        //   not be mislabeled as a permanent authorization denial.
775        for status in [
776            tonic::Status::unavailable("connection reset"),
777            tonic::Status::unauthenticated("invalid internal token"),
778            tonic::Status::failed_precondition("service name already owned by another gear"),
779        ] {
780            let err = call_error("heartbeat", &status);
781            assert!(err.downcast_ref::<DirectoryInvalidArgument>().is_none());
782            assert!(
783                err.downcast_ref::<DirectoryPermissionDenied>().is_none(),
784                "{:?} must stay transient/retryable, not map to DirectoryPermissionDenied",
785                status.code()
786            );
787            assert!(err.to_string().contains(&format!("{:?}", status.code())));
788        }
789    }
790}