use redup_bootstrap_client::ClientFactory;
use redup_bootstrap_grpc::CallContext;
use redup_bootstrap_grpc::contracts::grpc::health::v1::health_check_response::ServingStatus;
use redup_primitives::Address;
use crate::dependency::CustomProbe;
use crate::error::ModuleError;
pub fn grpc_probe(
clients: ClientFactory,
address: Address,
service: impl Into<String>,
) -> CustomProbe {
let service = service.into();
CustomProbe::new(move |_attempt| {
let clients = clients.detached();
let address = address.clone();
let service = service.clone();
async move {
let mut health = clients
.health(&address)
.map_err(|error| -> ModuleError { Box::new(error) })?;
let response = health
.check(&CallContext::root(), service)
.await
.map_err(|error| -> ModuleError { Box::new(error) })?;
Ok(response.status == ServingStatus::Serving as i32)
}
})
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use redup_abstractions::{Probe, ProbeSettings};
use redup_bootstrap_client::{ClientConfig, ClientFactory, NoLoad, Settings};
use redup_bootstrap_grpc::CallContext;
use redup_bootstrap_grpc::contracts::grpc::health::v1::health_check_response::ServingStatus;
use redup_bootstrap_grpc::contracts::grpc::health::v1::health_server::{Health, HealthServer};
use redup_bootstrap_grpc::contracts::grpc::health::v1::{
HealthCheckRequest, HealthCheckResponse,
};
use redup_primitives::Address;
use tokio::net::TcpListener;
use tokio::sync::watch;
use tokio_stream::wrappers::TcpListenerStream;
use tokio_util::sync::CancellationToken;
use tonic::{Request, Response, Status};
use super::grpc_probe;
const SERVICE: &str = "redup.blobstorage.v1.BlobStorageService";
struct HealthStub;
#[tonic::async_trait]
impl Health for HealthStub {
async fn check(
&self,
request: Request<HealthCheckRequest>,
) -> Result<Response<HealthCheckResponse>, Status> {
let status = if request.into_inner().service == SERVICE {
ServingStatus::Serving
} else {
ServingStatus::NotServing
};
Ok(Response::new(HealthCheckResponse {
status: status as i32,
}))
}
}
async fn address() -> Address {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("the test listener");
let port = listener.local_addr().expect("the listener address").port();
tokio::spawn(async move {
tonic::transport::Server::builder()
.add_service(HealthServer::new(HealthStub))
.serve_with_incoming(TcpListenerStream::new(listener))
.await
.expect("the test health server");
});
Address::parse(&format!("127.0.0.1:{port}")).expect("the test address")
}
fn settings(connect: Duration) -> Settings {
let directory = tempfile::tempdir().expect("the temporary directory");
std::fs::write(
directory.path().join("config.yaml"),
format!("client:\n connectTimeout: {}ms\n", connect.as_millis()),
)
.expect("the configuration file");
let channel =
redup_config::load::<ClientConfig>(&redup_config::Source::directory(directory.path()))
.expect("the client configuration")
.value;
Settings {
channel,
unary_timeout: Duration::from_secs(1),
..Settings::default()
}
}
async fn observation(service: &str) -> bool {
let probe = grpc_probe(
ClientFactory::new(Settings::default(), Arc::new(NoLoad)),
address().await,
service,
);
let (sender, mut receiver) = watch::channel(redup_abstractions::Observation::unknown());
let token = CancellationToken::new();
let settings = ProbeSettings::new(Duration::from_millis(10), Duration::from_secs(1));
let runner = tokio::spawn(async move { probe.run(&settings, sender, token.clone()).await });
let result = tokio::time::timeout(Duration::from_secs(3), async {
loop {
let observation = receiver.borrow().clone();
if observation.is_available() {
return true;
}
if observation.error().is_some() {
return false;
}
receiver.changed().await.expect("the watch channel");
}
})
.await
.expect("the probe observation");
runner.abort();
result
}
#[tokio::test]
async fn serving_service_is_reachable() {
assert!(observation(SERVICE).await);
}
#[tokio::test]
async fn another_service_is_not_reachable() {
assert!(!observation("redup.other.v1.OtherService").await);
}
#[tokio::test]
async fn a_failed_trial_does_not_poison_the_service_channel() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("the closed port");
let port = listener.local_addr().expect("the closed address").port();
drop(listener);
let address = Address::parse(&format!("127.0.0.1:{port}")).expect("the test address");
let clients = ClientFactory::new(settings(Duration::from_millis(300)), Arc::new(NoLoad));
let probe = grpc_probe(clients.clone(), address.clone(), SERVICE);
let (sender, mut receiver) = watch::channel(redup_abstractions::Observation::unknown());
let token = CancellationToken::new();
let probe_settings =
ProbeSettings::new(Duration::from_millis(10), Duration::from_millis(100));
let runner = tokio::spawn(async move {
probe.run(&probe_settings, sender, token.clone()).await;
});
tokio::time::timeout(Duration::from_secs(2), async {
loop {
if receiver.borrow().error().is_some() {
return;
}
receiver.changed().await.expect("the watch channel");
}
})
.await
.expect("the probe failure");
tokio::time::sleep(Duration::from_millis(350)).await;
let server = tokio::spawn(async move {
let listener = TcpListener::bind(("127.0.0.1", port))
.await
.expect("the test listener");
tonic::transport::Server::builder()
.add_service(HealthServer::new(HealthStub))
.serve_with_incoming(TcpListenerStream::new(listener))
.await
.expect("the test health server");
});
let mut health = clients.health(&address).expect("the health client");
let result = health.check(&CallContext::root(), SERVICE).await;
assert!(
result.is_ok(),
"the failed trial poisoned the service channel: {result:?}"
);
runner.abort();
server.abort();
}
}