1use 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
28fn 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
37type AuthedChannel = InterceptedService<Channel, InternalAuthInterceptor>;
43
44fn 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
64fn 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
95pub struct DirectoryGrpcClient {
106 inner: DirectoryServiceClient<AuthedChannel>,
107}
108
109impl DirectoryGrpcClient {
110 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 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 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 pub fn connect_lazy_with_interceptor(
178 uri: impl Into<String>,
179 interceptor: InternalAuthInterceptor,
180 ) -> Result<Self> {
181 let cfg = GrpcClientConfig::new("directory");
182 let channel: Channel = connect_lazy(uri, &cfg)?;
184 Ok(Self::from_channel_with_interceptor(channel, interceptor))
185 }
186
187 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 pub async fn connect_no_retry(uri: impl Into<String>, cfg: &GrpcClientConfig) -> Result<Self> {
210 let uri_string = uri.into();
211
212 let endpoint = tonic::transport::Endpoint::from_shared(uri_string)?
214 .connect_timeout(cfg.connect_timeout)
215 .timeout(cfg.rpc_timeout);
216
217 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 #[must_use]
238 pub fn from_channel(channel: Channel) -> Self {
239 Self::from_channel_with_interceptor(channel, InternalAuthInterceptor::disabled())
240 }
241
242 #[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 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 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 let lease_ttl_ms = response.into_inner().lease_ttl_ms;
405 if lease_ttl_ms == 0 {
406 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
462fn 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
475fn 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 grpc_services: Vec::new(),
501 labels: proto.labels.into_iter().collect::<BTreeMap<_, _>>(),
504 state: proto_state_to_domain(proto.state),
506 }
507}
508
509fn 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 let endpoint = tonic::transport::Endpoint::from_static("http://[::1]:50051");
546
547 let channel_result = endpoint.connect().await;
550
551 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 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 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 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 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 assert_eq!(
659 domain.openapi_spec_hash.as_deref(),
660 Some("1a2b3c4d5e6f7a8b")
661 );
662 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 assert_eq!(
681 domain.endpoint.as_ref().map(|e| e.uri.as_str()),
682 Some("http://worker:7000")
683 );
684 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 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 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 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 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 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 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}