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:
2026-10-09 15:57:35 +08:00
parent 7f331565c7
commit bbb67a68ab
65 changed files with 3313 additions and 695 deletions
+104 -2
View File
@@ -5,14 +5,116 @@ use buffa::Message;
use buffa_types::google::protobuf::{Empty, StringValue};
use connectrpc::Protocol;
use connectrpc::client::{ClientConfig, Http2Connection};
use proto::proto::control::{CenterClient, TerminalInfo};
use proto::proto::grpc::health::v1::health_check_response::ServingStatus;
use proto::control::{CenterClient, TerminalInfo};
use proto::grpc::health::v1::health_check_response::ServingStatus;
use terminal::ffi::*;
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use crate::{RegistryService, runtime::serve};
#[tokio::test]
async fn registry_health_is_independent_of_downstream_health() {
use proto::grpc::health::v1::HealthCheckRequest;
use proto::rpc::client::{RpcChannel, RpcClientOptions, RpcEndpoint};
tokio::time::timeout(Duration::from_secs(5), async {
let directory = tempfile::tempdir().unwrap();
let service = RegistryService::open(directory.path().join("terminals.bin"))
.await
.unwrap();
assert_eq!(
service.health_reporter().status(""),
Some(ServingStatus::NOT_SERVING)
);
let listener = 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 task = tokio::spawn(serve(
listener,
service.clone(),
Duration::from_millis(20),
Duration::from_millis(30),
std::future::pending(),
));
let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default())
.await
.unwrap();
let health = channel.health_client();
for name in ["", "control.Center"] {
assert_eq!(
health
.check(HealthCheckRequest {
service: name.into(),
..Default::default()
})
.await
.unwrap()
.into_owned()
.status,
ServingStatus::SERVING
);
}
let mut updates = health.watch(HealthCheckRequest::default()).await.unwrap();
assert_eq!(
updates
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVING
);
let unresponsive = TcpListener::bind("127.0.0.1:0").await.unwrap();
let response = channel
.center_client()
.register_terminal(TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_port: unresponsive.local_addr().unwrap().port().into(),
terminal_mac: "unresponsive".into(),
..Default::default()
})
.await
.unwrap()
.into_owned();
assert!(response.success);
let mut directory_updates = service.subscribe();
directory_updates
.wait_for(|snapshot| {
snapshot.infos[&response.message].status == ServingStatus::NOT_SERVING
})
.await
.unwrap();
assert_eq!(
health
.check(HealthCheckRequest::default())
.await
.unwrap()
.into_owned()
.status,
ServingStatus::SERVING
);
service.shutdown().await;
for name in ["", "control.Center"] {
assert_eq!(
service.health_reporter().status(name),
Some(ServingStatus::NOT_SERVING)
);
}
while let Some(message) = updates.message().await.unwrap() {
assert_eq!(
message.to_owned_message().status,
ServingStatus::NOT_SERVING
);
}
task.await.unwrap().unwrap();
assert!(service.set_ready().await.is_err());
})
.await
.unwrap();
}
#[tokio::test]
async fn center_rpc_register_update_subscribe_deregister_and_shutdown() {
tokio::time::timeout(Duration::from_secs(10), async {
+28 -9
View File
@@ -10,14 +10,24 @@ fn defaults_file_and_environment_precedence() {
let config = Config::from_file(&path, HashMap::new()).unwrap();
assert_eq!(config.port, 50051);
assert_eq!(config.health_interval, Duration::from_secs(10));
std::fs::write(&path, "REGISTRY_PORT=1234\nREGISTRY_HOST=localhost\n").unwrap();
assert_eq!(config.log_level, "info");
assert_eq!(config.log_dir, std::path::Path::new("logs/registry"));
assert_eq!(config.log_max_files, 10);
std::fs::write(&path, "PORT=1234\nHOST=localhost\nLOG_LEVEL=warn\nLOG_DIR=custom-logs\nLOG_MAX_FILES=4\nDATA_FILE_COUNT=7\n").unwrap();
let config = Config::from_file(
&path,
HashMap::from([("REGISTRY_PORT".into(), "4321".into())]),
HashMap::from([
("PORT".into(), "4321".into()),
("LOG_LEVEL".into(), "DEBUG".into()),
]),
)
.unwrap();
assert_eq!(config.port, 4321);
assert_eq!(config.host, "localhost");
assert_eq!(config.log_level, "DEBUG");
assert_eq!(config.log_dir, std::path::Path::new("custom-logs"));
assert_eq!(config.log_max_files, 4);
assert_eq!(config.data_file_count, 7);
}
#[test]
@@ -25,15 +35,24 @@ fn invalid_configuration_fails() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join(".env");
for (key, value) in [
("REGISTRY_PORT", "0"),
("REGISTRY_PORT", "65536"),
("REGISTRY_HEALTH_INTERVAL_SECS", "0"),
("REGISTRY_HEALTH_TIMEOUT_SECS", "abc"),
("REGISTRY_HOST", " "),
("REGISTRY_DATA_PATH", ""),
("PORT", "0"),
("PORT", "65536"),
("HEALTH_INTERVAL_SECS", "0"),
("HEALTH_TIMEOUT_SECS", "abc"),
("HOST", " "),
("DATA_PATH", ""),
("LOG_LEVEL", ""),
("LOG_LEVEL", "verbose"),
("LOG_DIR", " "),
("LOG_MAX_FILES", "0"),
("LOG_MAX_FILES", "-1"),
("LOG_MAX_FILES", "18446744073709551616"),
] {
assert!(Config::from_file(&path, HashMap::from([(key.into(), value.into())])).is_err());
}
std::fs::write(&path, "REGISTRY_PORT='unterminated").unwrap();
let config =
Config::from_file(&path, HashMap::from([("LOG_LEVEL".into(), "off".into())])).unwrap();
assert_eq!(config.log_level, "off");
std::fs::write(&path, "PORT='unterminated").unwrap();
assert!(Config::from_file(&path, HashMap::new()).is_err());
}
+20 -13
View File
@@ -5,14 +5,14 @@ use connectrpc::{
ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::stream;
use proto::proto::control::TerminalInfo;
use proto::proto::grpc::health::v1::{
use proto::control::TerminalInfo;
use proto::grpc::health::v1::{
Health, HealthCheckRequest, HealthCheckResponse, health_check_response::ServingStatus,
};
use tokio::sync::{oneshot, watch};
use crate::RegistryService;
use crate::health::{check, endpoint, monitor};
use crate::health::{check, monitor};
struct FakeHealth(watch::Receiver<ServingStatus>);
@@ -39,7 +39,7 @@ impl Health for FakeHealth {
}
async fn wait_status(
receiver: &mut watch::Receiver<proto::proto::control::TerminalInfos>,
receiver: &mut watch::Receiver<proto::control::TerminalInfos>,
id: &str,
status: ServingStatus,
) {
@@ -127,15 +127,22 @@ async fn timeout_covers_http2_connection_setup() {
assert_eq!(status, ServingStatus::NOT_SERVING);
}
#[test]
fn endpoint_supports_ipv6_and_hostnames() {
for host in ["::1", "[::1]", "localhost"] {
let uri = endpoint(&TerminalInfo {
terminal_host: host.into(),
terminal_port: 1234,
..Default::default()
})
#[tokio::test]
async fn readiness_cannot_override_shutdown() {
let directory = tempfile::tempdir().unwrap();
let service = RegistryService::open(directory.path().join("terminals.bin"))
.await
.unwrap();
assert_eq!(uri.port_u16(), Some(1234));
assert_eq!(
service.health_reporter().status(""),
Some(ServingStatus::NOT_SERVING)
);
let _ = tokio::join!(service.shutdown(), service.set_ready());
assert!(service.set_ready().await.is_err());
for name in ["", "control.Center"] {
assert_eq!(
service.health_reporter().status(name),
Some(ServingStatus::NOT_SERVING)
);
}
}
+70
View File
@@ -0,0 +1,70 @@
use std::collections::HashMap;
use std::process::Command;
use crate::{Config, logging};
#[test]
fn bridge_outputs_once_filters_and_flushes() {
if let Some(directory) = std::env::var_os("REGISTRY_LOG_TEST_CHILD") {
let directory = std::path::PathBuf::from(directory);
let config = Config::from_file(
&directory.join("absent.env"),
HashMap::from([("LOG_DIR".into(), directory.to_string_lossy().into_owned())]),
)
.unwrap();
logging::init_bridge().unwrap();
let guard = logging::init(&config).unwrap();
log::info!(target: "registry::log_test", "bridge-visible terminal_id=test-terminal");
log::debug!("bridge-hidden");
tracing::warn!(target: "registry::log_test", terminal_id = "test-terminal", "structured-visible");
let snapshot = directory.join("snapshot.bin");
std::fs::write(&snapshot, [0xff]).unwrap();
crate::storage::load(&snapshot).unwrap();
log::error!("last-record-before-flush");
drop(guard);
return;
}
let directory = tempfile::tempdir().unwrap();
let output = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"unit_tests::logging::bridge_outputs_once_filters_and_flushes",
"--nocapture",
])
.env("REGISTRY_LOG_TEST_CHILD", directory.path())
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let console = String::from_utf8(output.stderr).unwrap();
let logs = std::fs::read_dir(directory.path())
.unwrap()
.map(|entry| entry.unwrap().path())
.filter(|path| path.extension().is_some_and(|extension| extension == "log"))
.collect::<Vec<_>>();
assert_eq!(logs.len(), 1);
let name = logs[0].file_name().unwrap().to_str().unwrap();
assert!(name.starts_with("registry."));
let date = &name["registry.".len()..name.len() - ".log".len()];
assert_eq!(date.len(), 10);
assert_eq!(&date[4..5], "-");
assert_eq!(&date[7..8], "-");
let file = std::fs::read_to_string(&logs[0]).unwrap();
for text in [&console, &file] {
for message in [
"bridge-visible",
"structured-visible",
"invalid registry snapshot",
"last-record-before-flush",
] {
assert_eq!(text.matches(message).count(), 1, "{text}");
}
assert!(!text.contains("bridge-hidden"));
assert!(text.contains("registry::log_test"));
assert!(text.contains("test-terminal"));
assert!(!text.contains('\u{1b}'));
}
}
+1
View File
@@ -1,5 +1,6 @@
mod config;
mod health;
mod logging;
mod rpc;
mod service;
mod storage;
+2 -2
View File
@@ -1,8 +1,8 @@
use futures_util::StreamExt;
use proto::proto::control::TerminalInfo;
use proto::control::TerminalInfo;
use crate::RegistryService;
use crate::rpc::snapshots;
use proto::rpc::stream::watch_stream as snapshots;
#[tokio::test]
async fn subscribers_receive_initial_and_changed_snapshots_then_close() {
+2 -2
View File
@@ -1,5 +1,5 @@
use proto::proto::control::TerminalInfo;
use proto::proto::grpc::health::v1::health_check_response::ServingStatus;
use proto::control::TerminalInfo;
use proto::grpc::health::v1::health_check_response::ServingStatus;
use crate::RegistryService;
use crate::service::normalize_info;
+1 -1
View File
@@ -1,5 +1,5 @@
use buffa::Message;
use proto::proto::control::TerminalInfos;
use proto::control::TerminalInfos;
use crate::storage::{decode, load, save};