feat(rpc): implement health check service and error handling
- Added `RpcError` enum for comprehensive error handling in RPC operations. - Introduced `HealthReporter` and `HealthService` for managing service health statuses. - Implemented health check and watch functionality in the health service. - Created integration tests for health check service, covering various scenarios. - Added unit tests for client options validation and stream functionality. - Established logging infrastructure for terminal and registry components. - Implemented logging lifecycle management and conflict resolution in tests.
This commit is contained in:
@@ -9,6 +9,9 @@ connectrpc.workspace = true
|
||||
buffa.workspace = true
|
||||
buffa-types.workspace = true
|
||||
serde.workspace = true
|
||||
axum.workspace = true
|
||||
tokio.workspace = true
|
||||
futures-util.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
connectrpc-build.workspace = true
|
||||
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
# Protocol And RPC Infrastructure
|
||||
|
||||
This crate owns generated Protobuf types and reusable ConnectRPC transport and
|
||||
Health mechanisms. It does not own simulation logic, terminal registration
|
||||
policy, a Tokio runtime, process signals, logging initialization or persistence.
|
||||
|
||||
## Generated Types
|
||||
|
||||
[build.rs](build.rs) generates Center, Terminal, common messages and standard
|
||||
gRPC Health types. Use `proto::control` and `proto::grpc`; the previous
|
||||
`proto::proto::control` and `proto::proto::grpc` paths remain compatible aliases
|
||||
to the same generated types. Do not edit generated files under `target`.
|
||||
Data protocol generation and protocol wire definitions are unchanged.
|
||||
|
||||
## Clients
|
||||
|
||||
```rust
|
||||
use std::time::Duration;
|
||||
use proto::rpc::client::{CallOptions, RpcChannel, RpcClientOptions, RpcEndpoint};
|
||||
|
||||
async fn register(info: proto::control::TerminalInfo)
|
||||
-> Result<(), Box<dyn std::error::Error>>
|
||||
{
|
||||
let endpoint = RpcEndpoint::from_host_port("127.0.0.1", 50051)?;
|
||||
let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default()).await?;
|
||||
let response = channel.center_client().register_terminal_with_options(
|
||||
info, CallOptions::default().with_timeout(Duration::from_secs(3)),
|
||||
).await?.into_owned();
|
||||
if !response.success { return Err(response.message.into()); }
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
`RpcEndpoint` accepts DNS names, IPv4, and raw or bracketed IPv6 hosts with an
|
||||
explicit nonzero port. `from_uri` requires an `http` origin with a valid explicit
|
||||
port and no credentials, query or non-root path. Only plaintext HTTP/2 gRPC is
|
||||
supported; unsupported schemes fail instead of silently downgrading to plaintext.
|
||||
Listener port zero is still supported separately by Tokio's bind API.
|
||||
|
||||
`RpcClientOptions` defaults to a three-second connection establishment timeout,
|
||||
no default RPC deadline, and a 1024-entry transport buffer. The capacity is a
|
||||
queue bound, not a business concurrency limit. Timeouts must be positive and
|
||||
representable. The establishment budget covers the connection operation, with
|
||||
the same bound configured for transport reconnects. HTTP/2 connection construction
|
||||
may finish before a peer replies; response waiting is governed by RPC deadlines.
|
||||
|
||||
`center_client`, `terminal_client` and `health_client` return the existing
|
||||
generated clients sharing one transport. Their normal methods and `CallOptions`
|
||||
remain available. Long-lived subscriptions have no short default deadline unless
|
||||
the caller explicitly supplies one. This crate adds no automatic method retries
|
||||
or connection pool; it retains the transport's own reconnect behavior.
|
||||
|
||||
`health::check_health(endpoint, service_name, total_timeout)` bounds connection
|
||||
and Check together and returns `Result<HealthCheckResponse, RpcError>`. It preserves
|
||||
RPC error codes and unknown Protobuf enum values. Mapping failures to a business
|
||||
status, retries, polling intervals and stale-result checks belong to the caller.
|
||||
|
||||
## Servers And Streams
|
||||
|
||||
`rpc::Router` re-exports the existing ConnectRPC router. Register generated service
|
||||
implementations normally with `add_service`, then call
|
||||
`rpc::server::serve(listener, router, shutdown_future)` on an existing runtime.
|
||||
The helper builds the Axum adapter and graceful-shutdown future; it does not bind,
|
||||
spawn, register the service with a center, install logs, or impose an exit timeout.
|
||||
The caller retains ownership of server tasks and shutdown policy.
|
||||
|
||||
`rpc::stream::watch_stream(receiver, shutdown)` sends an initial latest snapshot,
|
||||
then each observed watch update. It marks the initial value consumed and gives
|
||||
shutdown priority. Closed shutdown/data channels end the stream. Slow consumers
|
||||
may skip intermediate values; there is no history queue or implicit equality
|
||||
filter. The sender decides when an application snapshot has changed.
|
||||
|
||||
## Shared Health
|
||||
|
||||
```rust
|
||||
use proto::rpc::health::{HealthReporter, HealthService, ServingStatus};
|
||||
|
||||
let reporter = HealthReporter::new();
|
||||
reporter.set_statuses(&[
|
||||
("", ServingStatus::NOT_SERVING),
|
||||
("control.Center", ServingStatus::NOT_SERVING),
|
||||
])?;
|
||||
let (shutdown, receiver) = tokio::sync::watch::channel(false);
|
||||
let health = HealthService::new(&reporter, receiver);
|
||||
let router = proto::rpc::Router::new().add_service(std::sync::Arc::new(health));
|
||||
```
|
||||
|
||||
`HealthReporter` is the state owner; it starts with no registered names. Reporters
|
||||
can be cloned. `set_statuses` atomically updates a batch, `remove_service` removes
|
||||
a name, and `status` reads it. Repeating a state is a no-op. Registered statuses
|
||||
are UNKNOWN, SERVING and NOT_SERVING; SERVICE_UNKNOWN is reserved for absent names.
|
||||
Empty service name `""` is explicit state, not an automatic aggregate of others.
|
||||
|
||||
`HealthService` holds receivers only and implements the generated `Health` trait:
|
||||
|
||||
- Check returns the named state, or gRPC NotFound for an unregistered name.
|
||||
- Watch immediately returns the named state (SERVICE_UNKNOWN if absent), and
|
||||
follows registration, changes, removal and re-registration on that same stream.
|
||||
- Only the selected service's visible state changes produce records. Watching
|
||||
arbitrary unknown names does not permanently add them to the status table.
|
||||
- Shutdown, a closed shutdown channel or loss of all reporters ends the stream.
|
||||
Publish NOT_SERVING before shutdown when appropriate, but do not assume every
|
||||
slow client receives the final state before stream termination.
|
||||
|
||||
Reporter lifetime is independent of a single server run. For a restart, construct
|
||||
a new HealthService with the retained reporter and the new shutdown receiver.
|
||||
Do not reuse the old closed signal. Components define readiness: Terminal uses
|
||||
its Ready lifecycle; Registry reports its own service readiness independently of
|
||||
downstream terminals. No business crate is a dependency of this crate.
|
||||
|
||||
## Verify
|
||||
|
||||
Tests are grouped under `tests/unit` and `tests/integration`, loaded by
|
||||
[src/lib.rs](src/lib.rs). They exercise address validation, compatibility aliases,
|
||||
watch shutdown/latest-value semantics, real Health RPCs, dynamic registrations,
|
||||
error-code preservation and deadlines.
|
||||
|
||||
```powershell
|
||||
cargo test -p proto
|
||||
cargo test -p registry -p terminal
|
||||
```
|
||||
@@ -1,3 +1,14 @@
|
||||
pub mod proto {
|
||||
connectrpc::include_generated!("proto_gen.rs");
|
||||
}
|
||||
|
||||
pub use proto::{control, grpc};
|
||||
pub mod rpc;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/mod.rs"]
|
||||
mod unit_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/integration/mod.rs"]
|
||||
mod integration_tests;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
use std::net::Ipv6Addr;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use axum::http::Uri;
|
||||
use connectrpc::Protocol;
|
||||
use connectrpc::client::{ClientConfig, Http2Connection, SharedHttp2Connection};
|
||||
|
||||
use super::RpcError;
|
||||
use crate::control::{CenterClient, TerminalClient};
|
||||
use crate::grpc::health::v1::HealthClient;
|
||||
|
||||
pub use connectrpc::client::CallOptions;
|
||||
pub type CenterRpcClient = CenterClient<SharedHttp2Connection>;
|
||||
pub type TerminalRpcClient = TerminalClient<SharedHttp2Connection>;
|
||||
pub type HealthRpcClient = HealthClient<SharedHttp2Connection>;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RpcEndpoint(Uri);
|
||||
|
||||
impl RpcEndpoint {
|
||||
pub fn from_host_port(host: &str, port: u16) -> Result<Self, RpcError> {
|
||||
if port == 0 || host.is_empty() || host.trim() != host {
|
||||
return Err(RpcError::InvalidEndpoint(
|
||||
"host must be nonempty and port nonzero".into(),
|
||||
));
|
||||
}
|
||||
let literal = host
|
||||
.strip_prefix('[')
|
||||
.and_then(|value| value.strip_suffix(']'))
|
||||
.unwrap_or(host);
|
||||
let authority = if let Ok(address) = literal.parse::<Ipv6Addr>() {
|
||||
format!("[{address}]:{port}")
|
||||
} else {
|
||||
if !host
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b".-_".contains(&byte))
|
||||
{
|
||||
return Err(RpcError::InvalidEndpoint(
|
||||
"host must be a DNS name, IPv4 or IPv6 address".into(),
|
||||
));
|
||||
}
|
||||
format!("{host}:{port}")
|
||||
};
|
||||
Uri::builder()
|
||||
.scheme("http")
|
||||
.authority(authority)
|
||||
.path_and_query("/")
|
||||
.build()
|
||||
.map(Self)
|
||||
.map_err(|error| RpcError::InvalidEndpoint(error.to_string()))
|
||||
}
|
||||
|
||||
pub fn from_uri(uri: Uri) -> Result<Self, RpcError> {
|
||||
if uri.scheme_str() != Some("http")
|
||||
|| uri
|
||||
.path_and_query()
|
||||
.is_some_and(|path| path.as_str() != "/" && !path.as_str().is_empty())
|
||||
|| uri
|
||||
.authority()
|
||||
.is_some_and(|authority| authority.as_str().contains('@'))
|
||||
{
|
||||
return Err(RpcError::InvalidEndpoint(
|
||||
"expected http origin without credentials, path or query".into(),
|
||||
));
|
||||
}
|
||||
let host = uri
|
||||
.host()
|
||||
.ok_or_else(|| RpcError::InvalidEndpoint("missing host".into()))?;
|
||||
let port = uri
|
||||
.port_u16()
|
||||
.ok_or_else(|| RpcError::InvalidEndpoint("explicit valid port is required".into()))?;
|
||||
Self::from_host_port(host, port)
|
||||
}
|
||||
|
||||
pub fn uri(&self) -> &Uri {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RpcClientOptions {
|
||||
pub connect_timeout: Duration,
|
||||
pub request_timeout: Option<Duration>,
|
||||
pub buffer_capacity: usize,
|
||||
}
|
||||
|
||||
impl Default for RpcClientOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
connect_timeout: Duration::from_secs(3),
|
||||
request_timeout: None,
|
||||
buffer_capacity: 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_duration(duration: Duration) -> Result<(), RpcError> {
|
||||
if duration.is_zero() || Instant::now().checked_add(duration).is_none() {
|
||||
Err(RpcError::InvalidOptions(
|
||||
"timeouts must be positive and representable",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RpcChannel {
|
||||
transport: SharedHttp2Connection,
|
||||
config: ClientConfig,
|
||||
}
|
||||
|
||||
impl RpcChannel {
|
||||
pub async fn connect(
|
||||
endpoint: &RpcEndpoint,
|
||||
options: RpcClientOptions,
|
||||
) -> Result<Self, RpcError> {
|
||||
validate_duration(options.connect_timeout)?;
|
||||
if let Some(timeout) = options.request_timeout {
|
||||
validate_duration(timeout)?;
|
||||
}
|
||||
if options.buffer_capacity == 0
|
||||
|| options.buffer_capacity > tokio::sync::Semaphore::MAX_PERMITS
|
||||
{
|
||||
return Err(RpcError::InvalidOptions(
|
||||
"invalid connection buffer capacity",
|
||||
));
|
||||
}
|
||||
let connection = tokio::time::timeout(
|
||||
options.connect_timeout,
|
||||
Http2Connection::builder()
|
||||
.establishment_timeout(options.connect_timeout)
|
||||
.tcp_connect_timeout(options.connect_timeout)
|
||||
.connect_plaintext(endpoint.0.clone()),
|
||||
)
|
||||
.await
|
||||
.map_err(RpcError::ConnectTimeout)?
|
||||
.map_err(RpcError::Connect)?;
|
||||
let mut config = ClientConfig::new(endpoint.0.clone()).with_protocol(Protocol::Grpc);
|
||||
if let Some(timeout) = options.request_timeout {
|
||||
config = config.with_default_timeout(timeout);
|
||||
}
|
||||
Ok(Self {
|
||||
transport: connection.shared(options.buffer_capacity),
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn center_client(&self) -> CenterRpcClient {
|
||||
CenterClient::new(self.transport.clone(), self.config.clone())
|
||||
}
|
||||
pub fn terminal_client(&self) -> TerminalRpcClient {
|
||||
TerminalClient::new(self.transport.clone(), self.config.clone())
|
||||
}
|
||||
pub fn health_client(&self) -> HealthRpcClient {
|
||||
HealthClient::new(self.transport.clone(), self.config.clone())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RpcError {
|
||||
InvalidEndpoint(String),
|
||||
InvalidOptions(&'static str),
|
||||
InvalidHealthStatus,
|
||||
Connect(connectrpc::ConnectError),
|
||||
ConnectTimeout(tokio::time::error::Elapsed),
|
||||
Call(connectrpc::ConnectError),
|
||||
HealthTimeout(tokio::time::error::Elapsed),
|
||||
}
|
||||
|
||||
impl fmt::Display for RpcError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidEndpoint(message) => write!(formatter, "invalid RPC endpoint: {message}"),
|
||||
Self::InvalidOptions(message) => write!(formatter, "invalid RPC options: {message}"),
|
||||
Self::InvalidHealthStatus => {
|
||||
formatter.write_str("SERVICE_UNKNOWN is reserved for unregistered Health services")
|
||||
}
|
||||
Self::Connect(error) => write!(formatter, "RPC connection failed: {error}"),
|
||||
Self::ConnectTimeout(error) => write!(formatter, "RPC connection timed out: {error}"),
|
||||
Self::Call(error) => write!(formatter, "RPC call failed: {error}"),
|
||||
Self::HealthTimeout(error) => write!(formatter, "health check timed out: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RpcError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::Connect(error) | Self::Call(error) => Some(error),
|
||||
Self::ConnectTimeout(error) | Self::HealthTimeout(error) => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use connectrpc::{
|
||||
ConnectError, ErrorCode, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
|
||||
};
|
||||
use futures_util::{Stream, stream};
|
||||
use tokio::sync::watch;
|
||||
|
||||
use super::{
|
||||
RpcError,
|
||||
client::{RpcChannel, RpcClientOptions, RpcEndpoint, validate_duration},
|
||||
};
|
||||
pub use crate::grpc::health::v1::health_check_response::ServingStatus;
|
||||
use crate::grpc::health::v1::{Health, HealthCheckRequest, HealthCheckResponse};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HealthReporter {
|
||||
states: watch::Sender<HashMap<String, ServingStatus>>,
|
||||
}
|
||||
|
||||
impl Default for HealthReporter {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl HealthReporter {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
states: watch::channel(HashMap::new()).0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_status(&self, service: &str, status: ServingStatus) -> Result<(), RpcError> {
|
||||
self.set_statuses(&[(service, status)])
|
||||
}
|
||||
|
||||
pub fn set_statuses(&self, updates: &[(&str, ServingStatus)]) -> Result<(), RpcError> {
|
||||
if updates
|
||||
.iter()
|
||||
.any(|(_, status)| *status == ServingStatus::SERVICE_UNKNOWN)
|
||||
{
|
||||
return Err(RpcError::InvalidHealthStatus);
|
||||
}
|
||||
self.states.send_if_modified(|states| {
|
||||
let mut next = states.clone();
|
||||
for (service, status) in updates {
|
||||
next.insert((*service).to_owned(), *status);
|
||||
}
|
||||
if *states == next {
|
||||
return false;
|
||||
}
|
||||
*states = next;
|
||||
true
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_service(&self, service: &str) {
|
||||
self.states
|
||||
.send_if_modified(|states| states.remove(service).is_some());
|
||||
}
|
||||
|
||||
pub fn status(&self, service: &str) -> Option<ServingStatus> {
|
||||
self.states.borrow().get(service).copied()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HealthService {
|
||||
states: watch::Receiver<HashMap<String, ServingStatus>>,
|
||||
shutdown: watch::Receiver<bool>,
|
||||
}
|
||||
|
||||
impl HealthService {
|
||||
pub fn new(reporter: &HealthReporter, shutdown: watch::Receiver<bool>) -> Self {
|
||||
Self {
|
||||
states: reporter.states.subscribe(),
|
||||
shutdown,
|
||||
}
|
||||
}
|
||||
|
||||
fn responses(
|
||||
&self,
|
||||
service: String,
|
||||
) -> impl Stream<Item = Result<HealthCheckResponse, ConnectError>> + Send + 'static {
|
||||
stream::unfold(
|
||||
(self.states.clone(), self.shutdown.clone(), service, None),
|
||||
|(mut states, mut shutdown, service, mut previous)| async move {
|
||||
loop {
|
||||
if *shutdown.borrow() || shutdown.has_changed().is_err() {
|
||||
return None;
|
||||
}
|
||||
let status = states
|
||||
.borrow_and_update()
|
||||
.get(&service)
|
||||
.copied()
|
||||
.unwrap_or(ServingStatus::SERVICE_UNKNOWN);
|
||||
if previous != Some(status) {
|
||||
previous = Some(status);
|
||||
let response = HealthCheckResponse {
|
||||
status: status.into(),
|
||||
..Default::default()
|
||||
};
|
||||
return Some((Ok(response), (states, shutdown, service, previous)));
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait_for(|stopped| *stopped) => return None,
|
||||
changed = states.changed() => { if changed.is_err() { return None; } }
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(refining_impl_trait)]
|
||||
impl Health for HealthService {
|
||||
async fn check(
|
||||
&self,
|
||||
_: RequestContext,
|
||||
request: ServiceRequest<'_, HealthCheckRequest>,
|
||||
) -> ServiceResult<HealthCheckResponse> {
|
||||
let service = request.to_owned_message().service;
|
||||
let status = self
|
||||
.states
|
||||
.borrow()
|
||||
.get(&service)
|
||||
.copied()
|
||||
.ok_or_else(|| ConnectError::new(ErrorCode::NotFound, "unknown service"))?;
|
||||
Response::ok(HealthCheckResponse {
|
||||
status: status.into(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
async fn watch(
|
||||
&self,
|
||||
_: RequestContext,
|
||||
request: ServiceRequest<'_, HealthCheckRequest>,
|
||||
) -> ServiceResult<ServiceStream<HealthCheckResponse>> {
|
||||
Response::stream_ok(self.responses(request.to_owned_message().service))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn check_health(
|
||||
endpoint: &RpcEndpoint,
|
||||
service: &str,
|
||||
total_timeout: Duration,
|
||||
) -> Result<HealthCheckResponse, RpcError> {
|
||||
validate_duration(total_timeout)?;
|
||||
tokio::time::timeout(total_timeout, async {
|
||||
let channel = RpcChannel::connect(
|
||||
endpoint,
|
||||
RpcClientOptions {
|
||||
connect_timeout: total_timeout,
|
||||
request_timeout: None,
|
||||
buffer_capacity: 1,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
channel
|
||||
.health_client()
|
||||
.check(HealthCheckRequest {
|
||||
service: service.into(),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.map(|response| response.into_owned())
|
||||
.map_err(RpcError::Call)
|
||||
})
|
||||
.await
|
||||
.map_err(RpcError::HealthTimeout)?
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod client;
|
||||
pub mod error;
|
||||
pub mod health;
|
||||
pub mod server;
|
||||
pub mod stream;
|
||||
|
||||
pub use connectrpc::Router;
|
||||
pub use error::RpcError;
|
||||
@@ -0,0 +1,12 @@
|
||||
use std::{future::Future, io};
|
||||
|
||||
pub async fn serve(
|
||||
listener: tokio::net::TcpListener,
|
||||
router: connectrpc::Router,
|
||||
shutdown: impl Future<Output = ()> + Send + 'static,
|
||||
) -> io::Result<()> {
|
||||
let app = axum::Router::new().fallback_service(router.into_axum_service());
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown)
|
||||
.await
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use connectrpc::ConnectError;
|
||||
use futures_util::{Stream, stream};
|
||||
use tokio::sync::watch;
|
||||
|
||||
pub fn watch_stream<T>(
|
||||
receiver: watch::Receiver<T>,
|
||||
shutdown: watch::Receiver<bool>,
|
||||
) -> impl Stream<Item = Result<T, ConnectError>> + Send
|
||||
where
|
||||
T: Clone + Send + Sync + 'static,
|
||||
{
|
||||
stream::unfold(
|
||||
(receiver, shutdown, true),
|
||||
|(mut receiver, mut shutdown, initial)| async move {
|
||||
if *shutdown.borrow() || shutdown.has_changed().is_err() {
|
||||
return None;
|
||||
}
|
||||
if !initial {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait_for(|stopped| *stopped) => return None,
|
||||
changed = receiver.changed() => { if changed.is_err() { return None; } }
|
||||
}
|
||||
}
|
||||
let item = receiver.borrow_and_update().clone();
|
||||
Some((Ok(item), (receiver, shutdown, false)))
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
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<bool>,
|
||||
RpcChannel,
|
||||
RpcEndpoint,
|
||||
tokio::task::JoinHandle<std::io::Result<()>>,
|
||||
) {
|
||||
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<crate::grpc::health::v1::HealthCheckResponse> {
|
||||
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<crate::grpc::health::v1::HealthCheckResponse>,
|
||||
> {
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
mod health;
|
||||
@@ -0,0 +1,68 @@
|
||||
use crate::rpc::client::{RpcChannel, RpcClientOptions, RpcEndpoint};
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn validates_endpoints_and_preserves_compatibility_exports() {
|
||||
let defaults = RpcClientOptions::default();
|
||||
assert_eq!(defaults.connect_timeout, Duration::from_secs(3));
|
||||
assert!(defaults.request_timeout.is_none());
|
||||
for host in ["localhost", "127.0.0.1", "::1", "[::1]"] {
|
||||
let endpoint = RpcEndpoint::from_host_port(host, 1234).unwrap();
|
||||
assert_eq!(endpoint.uri().port_u16(), Some(1234));
|
||||
assert_eq!(
|
||||
RpcEndpoint::from_uri(endpoint.uri().clone()).unwrap(),
|
||||
endpoint
|
||||
);
|
||||
}
|
||||
for host in [
|
||||
"",
|
||||
" foo ",
|
||||
"user@host",
|
||||
"host/path",
|
||||
"host?query",
|
||||
"host:99",
|
||||
"[foo]",
|
||||
] {
|
||||
assert!(RpcEndpoint::from_host_port(host, 1234).is_err());
|
||||
}
|
||||
assert!(RpcEndpoint::from_host_port("localhost", 0).is_err());
|
||||
for uri in [
|
||||
"https://localhost:99/",
|
||||
"http://localhost/",
|
||||
"http://localhost:0/",
|
||||
"http://localhost:65536/",
|
||||
"http://localhost:99/path",
|
||||
"http://localhost:99/?q=1",
|
||||
"http://user@localhost:99/",
|
||||
] {
|
||||
assert!(
|
||||
RpcEndpoint::from_uri(uri.parse().unwrap()).is_err(),
|
||||
"{uri}"
|
||||
);
|
||||
}
|
||||
let _: crate::control::TerminalInfo = crate::proto::control::TerminalInfo::default();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_options_fail_before_connecting() {
|
||||
let endpoint = RpcEndpoint::from_host_port("localhost", 1234).unwrap();
|
||||
for options in [
|
||||
RpcClientOptions {
|
||||
connect_timeout: Duration::ZERO,
|
||||
..Default::default()
|
||||
},
|
||||
RpcClientOptions {
|
||||
request_timeout: Some(Duration::ZERO),
|
||||
..Default::default()
|
||||
},
|
||||
RpcClientOptions {
|
||||
buffer_capacity: 0,
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
assert!(matches!(
|
||||
RpcChannel::connect(&endpoint, options).await,
|
||||
Err(crate::rpc::RpcError::InvalidOptions(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
mod client;
|
||||
mod stream;
|
||||
@@ -0,0 +1,42 @@
|
||||
use crate::rpc::stream::watch_stream;
|
||||
use futures_util::StreamExt;
|
||||
use tokio::sync::watch;
|
||||
|
||||
#[tokio::test]
|
||||
async fn initial_latest_multiple_subscribers_and_shutdown() {
|
||||
let (sender, receiver) = watch::channel(0);
|
||||
let (stop, shutdown) = watch::channel(false);
|
||||
let mut first = Box::pin(watch_stream(receiver.clone(), shutdown.clone()));
|
||||
let mut second = Box::pin(watch_stream(receiver, shutdown.clone()));
|
||||
sender.send_replace(1);
|
||||
assert_eq!(first.next().await.unwrap().unwrap(), 1);
|
||||
assert_eq!(second.next().await.unwrap().unwrap(), 1);
|
||||
sender.send_replace(2);
|
||||
sender.send_replace(3);
|
||||
assert_eq!(first.next().await.unwrap().unwrap(), 3);
|
||||
assert_eq!(second.next().await.unwrap().unwrap(), 3);
|
||||
stop.send_replace(true);
|
||||
assert!(first.next().await.is_none());
|
||||
assert!(second.next().await.is_none());
|
||||
assert!(
|
||||
Box::pin(watch_stream(sender.subscribe(), shutdown))
|
||||
.next()
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn channel_closure_ends_stream() {
|
||||
let (sender, receiver) = watch::channel(0);
|
||||
let (stop, shutdown) = watch::channel(false);
|
||||
let mut stream = Box::pin(watch_stream(receiver, shutdown));
|
||||
stream.next().await.unwrap().unwrap();
|
||||
drop(sender);
|
||||
assert!(stream.next().await.is_none());
|
||||
let (sender, receiver) = watch::channel(0);
|
||||
let mut stream = Box::pin(watch_stream(receiver, stop.subscribe()));
|
||||
drop(stop);
|
||||
assert!(stream.next().await.is_none());
|
||||
drop(sender);
|
||||
}
|
||||
Reference in New Issue
Block a user