use std::sync::Arc; use std::time::Duration; use crate::grpc::health::v1::HealthCheckRequest; use crate::rpc::{ Router, RpcError, client::{CallOptions, RpcChannel, RpcClientOptions, RpcEndpoint}, health::{HealthReporter, HealthService, ServingStatus, check_health}, server, }; use connectrpc::ErrorCode; use tokio::sync::watch; async fn launch() -> ( HealthReporter, watch::Sender, RpcChannel, RpcEndpoint, tokio::task::JoinHandle>, ) { let reporter = HealthReporter::new(); let (stop, mut shutdown) = watch::channel(false); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let endpoint = RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); let router = Router::new().add_service(Arc::new(HealthService::new(&reporter, shutdown.clone()))); let task = tokio::spawn(server::serve(listener, router, async move { let _ = shutdown.wait_for(|stopped| *stopped).await; })); let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default()) .await .unwrap(); (reporter, stop, channel, endpoint, task) } #[tokio::test] async fn dynamic_service_watch_and_independent_statuses() { tokio::time::timeout(Duration::from_secs(5), async { let (reporter, stop, channel, endpoint, task) = launch().await; let client = channel.health_client(); let error = client .check(HealthCheckRequest::default()) .await .unwrap_err(); assert_eq!(error.code, ErrorCode::NotFound); let probe = check_health(&endpoint, "", Duration::from_secs(1)) .await .unwrap_err(); assert!(matches!(probe, RpcError::Call(error) if error.code == ErrorCode::NotFound)); let mut stream = client .watch(HealthCheckRequest { service: "dynamic".into(), ..Default::default() }) .await .unwrap(); assert_eq!( stream .message() .await .unwrap() .unwrap() .to_owned_message() .status, ServingStatus::SERVICE_UNKNOWN ); assert!(reporter.status("dynamic").is_none()); reporter.set_status("", ServingStatus::NOT_SERVING).unwrap(); reporter .set_status("dynamic", ServingStatus::SERVING) .unwrap(); assert_eq!( stream .message() .await .unwrap() .unwrap() .to_owned_message() .status, ServingStatus::SERVING ); assert_eq!( check_health(&endpoint, "", Duration::from_secs(1)) .await .unwrap() .status, ServingStatus::NOT_SERVING ); reporter .set_status("dynamic", ServingStatus::SERVING) .unwrap(); reporter .set_status("other", ServingStatus::SERVING) .unwrap(); assert!( tokio::time::timeout(Duration::from_millis(20), stream.message()) .await .is_err() ); reporter .set_status("dynamic", ServingStatus::NOT_SERVING) .unwrap(); assert_eq!( stream .message() .await .unwrap() .unwrap() .to_owned_message() .status, ServingStatus::NOT_SERVING ); reporter.remove_service("dynamic"); assert_eq!( stream .message() .await .unwrap() .unwrap() .to_owned_message() .status, ServingStatus::SERVICE_UNKNOWN ); reporter .set_status("dynamic", ServingStatus::UNKNOWN) .unwrap(); assert_eq!( stream .message() .await .unwrap() .unwrap() .to_owned_message() .status, ServingStatus::UNKNOWN ); assert!( reporter .set_statuses(&[ ("dynamic", ServingStatus::SERVING), ("invalid", ServingStatus::SERVICE_UNKNOWN) ]) .is_err() ); assert_eq!(reporter.status("dynamic"), Some(ServingStatus::UNKNOWN)); drop(reporter); assert!(stream.message().await.unwrap().is_none()); stop.send_replace(true); task.await.unwrap().unwrap(); }) .await .unwrap(); } #[tokio::test] async fn shutdown_and_explicit_stream_deadline() { tokio::time::timeout(Duration::from_secs(5), async { let (reporter, stop, channel, _, task) = launch().await; let client = channel.health_client(); let mut ordinary = client.watch(HealthCheckRequest::default()).await.unwrap(); ordinary.message().await.unwrap().unwrap(); let mut limited = client .watch_with_options( HealthCheckRequest::default(), CallOptions::default().with_timeout(Duration::from_millis(30)), ) .await .unwrap(); limited.message().await.unwrap().unwrap(); assert_eq!( limited.message().await.unwrap_err().code, ErrorCode::DeadlineExceeded ); reporter.set_status("", ServingStatus::SERVING).unwrap(); assert_eq!( ordinary .message() .await .unwrap() .unwrap() .to_owned_message() .status, ServingStatus::SERVING ); stop.send_replace(true); assert!(ordinary.message().await.unwrap().is_none()); task.await.unwrap().unwrap(); }) .await .unwrap(); } #[tokio::test] async fn connection_and_probe_budgets_are_bounded() { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let endpoint = RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); let accept = tokio::spawn(async move { let (socket, _) = listener.accept().await.unwrap(); std::future::pending::<()>().await; drop(socket); }); let timeout = Duration::from_millis(30); let result = tokio::time::timeout( Duration::from_secs(1), RpcChannel::connect( &endpoint, RpcClientOptions { connect_timeout: timeout, ..Default::default() }, ), ) .await .unwrap(); match result { Ok(channel) => { let response = tokio::time::timeout( Duration::from_secs(1), channel.health_client().check_with_options( HealthCheckRequest::default(), CallOptions::default().with_timeout(timeout), ), ) .await .unwrap(); assert!(matches!(response, Err(error) if error.code == ErrorCode::DeadlineExceeded)); } Err(RpcError::ConnectTimeout(_) | RpcError::Connect(_)) => {} Err(error) => panic!("unexpected connect error: {error}"), } accept.abort(); let _ = accept.await; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let endpoint = RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); assert!( tokio::time::timeout(Duration::from_secs(1), check_health(&endpoint, "", timeout)) .await .unwrap() .is_err() ); drop(listener); assert!(matches!( check_health(&endpoint, "", timeout).await, Err(RpcError::Connect(_)) )); } enum ProbeBehavior { Unimplemented, NoResponse, FutureStatus, } #[allow(refining_impl_trait)] impl crate::grpc::health::v1::Health for ProbeBehavior { async fn check( &self, _: connectrpc::RequestContext, _: connectrpc::ServiceRequest<'_, HealthCheckRequest>, ) -> connectrpc::ServiceResult { use buffa::Message; match self { Self::Unimplemented => Err(connectrpc::ConnectError::new( ErrorCode::Unimplemented, "not supported", )), Self::NoResponse => std::future::pending().await, Self::FutureStatus => connectrpc::Response::ok( crate::grpc::health::v1::HealthCheckResponse::decode_from_slice(&[8, 99]).unwrap(), ), } } async fn watch( &self, _: connectrpc::RequestContext, _: connectrpc::ServiceRequest<'_, HealthCheckRequest>, ) -> connectrpc::ServiceResult< connectrpc::ServiceStream, > { Err(connectrpc::ConnectError::new( ErrorCode::Unimplemented, "not supported", )) } } #[tokio::test] async fn probes_preserve_rpc_codes_unknown_enum_values_and_total_deadline() { use buffa::Message; tokio::time::timeout(Duration::from_secs(5), async { for (behavior, expected) in [(ProbeBehavior::Unimplemented, "unimplemented"), (ProbeBehavior::FutureStatus, "future"), (ProbeBehavior::NoResponse, "timeout")] { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let endpoint = RpcEndpoint::from_host_port("127.0.0.1", listener.local_addr().unwrap().port()).unwrap(); let (stop, mut shutdown) = watch::channel(false); let router = Router::new().add_service(Arc::new(behavior)); let task = tokio::spawn(server::serve(listener, router, async move { let _ = shutdown.wait_for(|stopped| *stopped).await; })); let response = check_health(&endpoint, "", Duration::from_millis(100)).await; match expected { "unimplemented" => assert!(matches!(response, Err(RpcError::Call(error)) if error.code == ErrorCode::Unimplemented)), "future" => assert_eq!(response.unwrap().encode_to_vec(), [8, 99]), _ => assert!(matches!(response, Err(RpcError::HealthTimeout(_)))), } stop.send_replace(true); if expected == "timeout" { task.abort(); let _ = task.await; } else { task.await.unwrap().unwrap(); } } }).await.unwrap(); }