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:
+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
|
||||
```
|
||||
Reference in New Issue
Block a user