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, GetOpenApiSpecRequest, GrpcServiceEndpoint,
24 HeartbeatRequest, InstanceInfo, ListAllInstancesRequest, ListInstancesRequest,
25 RegisterInstanceRequest, 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 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 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 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 let lease_ttl_ms = response.into_inner().lease_ttl_ms;
419 if lease_ttl_ms == 0 {
420 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
476fn 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
489fn 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 grpc_services: Vec::new(),
515 labels: proto.labels.into_iter().collect::<BTreeMap<_, _>>(),
518 state: proto_state_to_domain(proto.state),
520 }
521}
522
523fn 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 let endpoint = tonic::transport::Endpoint::from_static("http://[::1]:50051");
560
561 let channel_result = endpoint.connect().await;
564
565 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 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 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 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 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 assert_eq!(
673 domain.openapi_spec_hash.as_deref(),
674 Some("1a2b3c4d5e6f7a8b")
675 );
676 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 assert_eq!(
695 domain.endpoint.as_ref().map(|e| e.uri.as_str()),
696 Some("http://worker:7000")
697 );
698 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 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 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 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 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 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 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}