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
+4 -1
View File
@@ -9,12 +9,15 @@ proto.workspace = true
connectrpc.workspace = true
buffa.workspace = true
buffa-types.workspace = true
axum.workspace = true
futures-util.workspace = true
tokio.workspace = true
dotenvy.workspace = true
uuid.workspace = true
tempfile.workspace = true
log.workspace = true
tracing.workspace = true
flysim-log.workspace = true
[dev-dependencies]
terminal = { path = "../terminal" }
axum.workspace = true
+71 -9
View File
@@ -18,19 +18,59 @@ Process environment variables override file values. Relative data paths are
also resolved against the current working directory. Invalid configuration
stops startup. The actual `.env` and default data directory are git-ignored.
| Variable | Default |
| ------------------------------- | ----------------------------- |
| `REGISTRY_HOST` | `0.0.0.0` |
| `REGISTRY_PORT` | `50051` |
| `REGISTRY_DATA_PATH` | `registry/data/terminals.bin` |
| `REGISTRY_HEALTH_INTERVAL_SECS` | `10` |
| `REGISTRY_HEALTH_TIMEOUT_SECS` | `3` |
- `HOST`: `0.0.0.0`.
- `PORT`: `50051`.
- `DATA_PATH`: `registry/data/terminals.bin`.
- `HEALTH_INTERVAL_SECS`: `10`.
- `HEALTH_TIMEOUT_SECS`: `3`.
- `DATA_FILE_COUNT`: `10`, independent of logging retention.
- `LOG_LEVEL`: `info`.
- `LOG_DIR`: `logs/registry`.
- `LOG_MAX_FILES`: `10`.
Ports must be in `1..=65535`; health durations must be positive integer seconds.
Ctrl+C stops new work, closes subscription streams, cancels active health checks,
and allows up to five seconds for HTTP connections to drain after directory
transactions finish.
## Logging
The backend is provided by [flysim-log](../log/README.md). This component only
maps configuration/errors and controls the process-owned logging guard.
Business messages use `log::info!`, `log::warn!` and `log::error!`. `tracing-log`
forwards these records to `tracing-subscriber`; native tracing events/spans use
the same subscriber. `env_logger` is not initialized. Each event is formatted
once for stderr and once for the file, with UTC timestamp, level and target.
Native tracing fields are preserved. Files contain no ANSI color sequences;
stderr colors are enabled only when connected to a terminal.
`LOG_LEVEL` accepts `off`, `error`, `warn`, `info`, `debug` or `trace`, ignoring
case. `LOG_DIR` must be nonempty and `LOG_MAX_FILES` must be positive. Environment
variables override `.env` values; `RUST_LOG` is not used by this configuration.
Relative log paths resolve against the working directory.
Files are named `registry.YYYY-MM-DD.log` and roll daily on UTC boundaries when
new records arrive. The appender retains at most `LOG_MAX_FILES` matching files;
this is a file-count cap, not a guarantee of exactly that many files or days.
Old matching files can be removed on initialization and rotation. Use a dedicated
directory per process: do not share it with another registry or place unrelated
files with the same `registry` prefix and `.log` suffix there. The default `logs/`
directory is git-ignored. Rotation does not cap individual file size.
File writes use an 8192-entry bounded queue and a worker thread. The producer
blocks when the queue is full instead of dropping logs; stderr writes are
synchronous. Slow storage or consoles can therefore delay the calling thread.
The worker guard is retained until shutdown and dropped after the final log
record to drain buffered writes. This is not a durability guarantee for disk
errors, process termination, power loss, or a stalled writer at shutdown.
Logging is initialized before snapshot recovery, so corruption warnings reach
both outputs. Configuration/appender initialization failures are reported using
`log` through a temporary stderr-only subscriber and exit unsuccessfully.
Runtime failures are logged before releasing the file worker. The binary owns
global logging; library consumers must configure their own logging explicitly.
## Directory Contract
- Registration requires a nonempty host, a reachable port in `1..=65535`, and a
@@ -58,7 +98,7 @@ The data file contains a Protobuf `TerminalInfos` message. Health is always
written and restored as `UNKNOWN`; runtime health changes do not write to disk.
Missing snapshots start an empty directory. Undecodable or semantically invalid
snapshots are renamed to `terminals.bin.corrupt-<timestamp>-<suffix>` and reported
on stderr before starting empty. Ordinary I/O or backup failures stop startup.
as warning logs before starting empty. Ordinary I/O or backup failures stop startup.
Writes use a synchronized temporary file in the same directory and `tempfile`'s
atomic replacement API, including on Windows. There is no delete/rename gap and
@@ -74,6 +114,19 @@ authorizes outbound health connections to the supplied host and port.
## Health
Registry exposes `grpc.health.v1.Health` on the same port as `control.Center`,
using [proto's shared Health service](../proto/README.md). Empty service name and
`control.Center` start as NOT_SERVING and become SERVING once the directory is
loaded, the listener is bound and the serving runtime starts. Shutdown marks
both NOT_SERVING before signaling streams to close. Readiness and shutdown use
the same state lock, so a concurrent startup cannot undo shutdown.
This describes Registry readiness, not downstream health: an empty directory
or offline terminals do not make Registry unhealthy. It does not continuously
probe disk writability. Background monitor/server failures trigger the existing
shutdown path. A slow watcher is not guaranteed to receive the final NOT_SERVING
message before the stream ends.
Checks start immediately on startup and after directory changes, then run at the
configured interval with at most 32 concurrent probes. The timeout includes DNS,
TCP/HTTP2 connection setup and the RPC. Requests use an empty service name.
@@ -81,6 +134,10 @@ Responses update health; connection errors, RPC errors and timeouts become
`NOT_SERVING`. Offline terminals remain registered until explicitly removed.
Version checks discard results from a previous registration or address update.
Endpoint construction, the single Health call, server hosting and watch streams
come from `proto::rpc`. Polling, concurrency, error-to-NOT_SERVING mapping,
registration business logic and stale-result checks remain in Registry.
Terminal exposes both Health RPCs on its existing port. Empty service names and
`control.Terminal` report `SERVING` only when the terminal lifecycle is `Ready`.
Unknown names return `NotFound` from Check and a persistent `SERVICE_UNKNOWN`
@@ -90,7 +147,7 @@ stream from Watch. Health describes service readiness, not simulation state.
All test implementations and test-only helpers live under `tests/`:
- `tests/unit/{config,health,rpc,service,storage}.rs` contains module-level tests.
- `tests/unit/{config,health,logging,rpc,service,storage}.rs` contains module-level tests.
[tests/unit/mod.rs](tests/unit/mod.rs) declares these modules as `unit_tests`.
- [tests/integration/runtime.rs](tests/integration/runtime.rs) tests real RPC
calls and Terminal interoperability; [tests/integration/mod.rs](tests/integration/mod.rs)
@@ -109,6 +166,7 @@ Both test groups run in the library test target; there is no standalone
```powershell
cargo test -p registry
cargo test -p registry --lib unit_tests
cargo test -p registry --lib unit_tests::logging
cargo test -p registry --lib integration_tests::runtime
cargo test -p registry -p terminal
cargo test --workspace
@@ -118,3 +176,7 @@ Tests cover configuration, identity, persistence failures and corruption,
request cancellation, stale probe results, subscriptions, health recovery and
timeouts, real CenterClient calls, and a real Terminal started through its C ABI
that remains online while the registry restarts.
Logging tests isolate global bridge/subscriber installation in child processes
and verify Registry's dual output and recovery messages. File retention,
reopen/append, filtering and backpressure tests live in the shared log crate.
+17 -1
View File
@@ -4,7 +4,7 @@ use std::time::Duration;
use crate::RegistryError;
const KEYS: [&str; 7] = [
const KEYS: [&str; 9] = [
"HOST",
"PORT",
"DATA_PATH",
@@ -12,6 +12,8 @@ const KEYS: [&str; 7] = [
"HEALTH_TIMEOUT_SECS",
"DATA_FILE_COUNT",
"LOG_LEVEL",
"LOG_DIR",
"LOG_MAX_FILES",
];
#[derive(Clone, Debug)]
@@ -23,6 +25,8 @@ pub struct Config {
pub health_timeout: Duration,
pub data_file_count: u64,
pub log_level: String,
pub log_dir: PathBuf,
pub log_max_files: usize,
}
impl Config {
@@ -97,6 +101,16 @@ impl Config {
}
let data_file_count = positive("DATA_FILE_COUNT", "10")?;
let log_level = value("LOG_LEVEL", "info");
crate::logging::parse_level(&log_level)?;
let log_dir = value("LOG_DIR", "logs/registry");
if log_dir.is_empty() {
return Err(RegistryError::new(
"CONFIG_ERROR",
"LOG_DIR must not be empty",
));
}
let log_max_files = usize::try_from(positive("LOG_MAX_FILES", "10")?)
.map_err(|_| RegistryError::new("CONFIG_ERROR", "LOG_MAX_FILES is too large"))?;
Ok(Self {
host,
port,
@@ -105,6 +119,8 @@ impl Config {
health_timeout,
data_file_count: data_file_count,
log_level,
log_dir: log_dir.into(),
log_max_files,
})
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ use std::fmt;
use buffa::MessageField;
use buffa_types::google::protobuf::{Any, StringValue};
use proto::proto::control::InvokeResponse;
use proto::control::InvokeResponse;
#[derive(Debug)]
pub struct RegistryError {
+11 -39
View File
@@ -1,53 +1,25 @@
use std::net::Ipv6Addr;
use std::time::Duration;
use axum::http::Uri;
use buffa::EnumValue;
use connectrpc::Protocol;
use connectrpc::client::{ClientConfig, Http2Connection};
use futures_util::{StreamExt, stream};
use proto::proto::control::TerminalInfo;
use proto::proto::grpc::health::v1::{
HealthCheckRequest, HealthClient, health_check_response::ServingStatus,
use proto::control::TerminalInfo;
use proto::rpc::{
client::RpcEndpoint,
health::{ServingStatus, check_health},
};
use crate::RegistryService;
pub(crate) fn endpoint(info: &TerminalInfo) -> Option<Uri> {
let host = if info.terminal_host.parse::<Ipv6Addr>().is_ok() {
format!("[{}]", info.terminal_host)
} else {
info.terminal_host.clone()
};
Uri::builder()
.scheme("http")
.authority(format!("{host}:{}", info.terminal_port))
.path_and_query("/")
.build()
.ok()
}
pub(crate) async fn check(info: &TerminalInfo, timeout: Duration) -> EnumValue<ServingStatus> {
let Some(uri) = endpoint(info) else {
let Ok(port) = u16::try_from(info.terminal_port) else {
return ServingStatus::NOT_SERVING.into();
};
let result = tokio::time::timeout(timeout, async {
let connection = Http2Connection::connect_plaintext(uri.clone()).await?;
let client = HealthClient::new(
connection.shared(1),
ClientConfig::new(uri)
.with_protocol(Protocol::Grpc)
.with_default_timeout(timeout),
);
client
.check(HealthCheckRequest::default())
.await
.map(|response| response.into_owned().status)
})
.await;
match result {
Ok(Ok(status)) => status,
_ => ServingStatus::NOT_SERVING.into(),
let Ok(endpoint) = RpcEndpoint::from_host_port(&info.terminal_host, port) else {
return ServingStatus::NOT_SERVING.into();
};
match check_health(&endpoint, "", timeout).await {
Ok(response) => response.status,
Err(_) => ServingStatus::NOT_SERVING.into(),
}
}
+1
View File
@@ -1,6 +1,7 @@
pub mod config;
pub mod error;
mod health;
pub mod logging;
mod rpc;
pub mod runtime;
pub mod service;
+37
View File
@@ -0,0 +1,37 @@
use flysim_log::{LoggingConfig, LoggingError, LoggingGuard};
use crate::{Config, RegistryError};
pub(crate) fn parse_level(value: &str) -> Result<log::LevelFilter, RegistryError> {
flysim_log::parse_level(value).map_err(map_error)
}
pub fn init_bridge() -> Result<(), RegistryError> {
flysim_log::install_log_bridge().map_err(map_error)
}
pub fn init(config: &Config) -> Result<LoggingGuard, RegistryError> {
let logging = LoggingConfig {
level: parse_level(&config.log_level)?,
directory: config.log_dir.clone(),
file_prefix: "registry".into(),
max_files: config.log_max_files,
};
let (subscriber, guard) = flysim_log::build_subscriber(&logging).map_err(map_error)?;
flysim_log::install_subscriber(subscriber).map_err(map_error)?;
Ok(guard)
}
pub fn report_startup_error(error: &dyn std::fmt::Display) {
tracing::dispatcher::with_default(&flysim_log::stderr_subscriber(), || {
log::error!("registry startup failed: {error}");
});
}
fn map_error(error: LoggingError) -> RegistryError {
let code = match error {
LoggingError::InvalidConfig(_) => "CONFIG_ERROR",
_ => "LOG_INIT_FAILED",
};
RegistryError::new(code, error.to_string())
}
+41 -6
View File
@@ -1,12 +1,47 @@
use registry::{Config, RegistryService, runtime};
use std::process::ExitCode;
use registry::{Config, RegistryService, logging, runtime};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?;
async fn main() -> ExitCode {
if let Err(error) = logging::init_bridge() {
logging::report_startup_error(&error);
return ExitCode::FAILURE;
}
let config = match Config::load() {
Ok(config) => config,
Err(error) => {
logging::report_startup_error(&error);
return ExitCode::FAILURE;
}
};
let guard = match logging::init(&config) {
Ok(guard) => guard,
Err(error) => {
logging::report_startup_error(&error);
return ExitCode::FAILURE;
}
};
let result = run(config).await;
let exit = match result {
Ok(()) => {
log::info!("registry stopped");
ExitCode::SUCCESS
}
Err(error) => {
log::error!("registry failed: {error}");
ExitCode::FAILURE
}
};
drop(guard);
exit
}
async fn run(config: Config) -> Result<(), Box<dyn std::error::Error>> {
let service = RegistryService::open(&config.data_path).await?;
let listener = tokio::net::TcpListener::bind((config.host.as_str(), config.port)).await?;
println!(
"registry listening on {}; restored {} terminals from {}",
log::info!(
"registry started listen_addr={} terminal_count={} data_path={}",
listener.local_addr()?,
service.subscribe().borrow().infos.len(),
config.data_path.display()
@@ -18,7 +53,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.health_timeout,
async {
if let Err(error) = tokio::signal::ctrl_c().await {
eprintln!("failed to listen for shutdown signal: {error}");
log::error!("failed to listen for shutdown signal: {error}");
}
},
)
+4 -30
View File
@@ -1,12 +1,9 @@
use buffa_types::google::protobuf::{Empty, StringValue};
use connectrpc::{
ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::{Stream, stream};
use proto::proto::control::{
use connectrpc::{RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream};
use proto::control::{
Center, InvokeResponse, TerminalInfo, TerminalInfos, TerminalRegisterResponse,
};
use tokio::sync::watch;
use proto::rpc::stream::watch_stream;
use crate::RegistryService;
@@ -49,29 +46,6 @@ impl Center for RegistryService {
_context: RequestContext,
_request: ServiceRequest<'_, Empty>,
) -> ServiceResult<ServiceStream<TerminalInfos>> {
Response::stream_ok(snapshots(self.subscribe(), self.shutdown_receiver()))
Response::stream_ok(watch_stream(self.subscribe(), self.shutdown_receiver()))
}
}
pub(crate) fn snapshots(
receiver: watch::Receiver<TerminalInfos>,
shutdown: watch::Receiver<bool>,
) -> impl Stream<Item = Result<TerminalInfos, ConnectError>> + Send {
stream::unfold(
(receiver, shutdown, true),
|(mut receiver, mut shutdown, initial)| async move {
if *shutdown.borrow() {
return None;
}
if !initial {
tokio::select! {
biased;
_ = shutdown.wait_for(|stopped| *stopped) => return None,
changed = receiver.changed() => { if changed.is_err() { return None; } }
}
}
let snapshot = receiver.borrow_and_update().clone();
Some((Ok(snapshot), (receiver, shutdown, false)))
},
)
}
+12 -8
View File
@@ -1,8 +1,9 @@
use std::future::{Future, IntoFuture};
use std::future::Future;
use std::io;
use std::sync::Arc;
use std::time::Duration;
use proto::rpc::{Router, health::HealthService, server};
use tokio::net::TcpListener;
use crate::{RegistryService, health};
@@ -25,15 +26,18 @@ pub async fn serve(
"health durations must be positive",
));
}
let rpc = connectrpc::Router::new().add_service(Arc::new(service.clone()));
let app = axum::Router::new().fallback_service(rpc.into_axum_service());
let rpc = Router::new()
.add_service(Arc::new(service.clone()))
.add_service(Arc::new(HealthService::new(
service.health_reporter(),
service.shutdown_receiver(),
)));
let mut shutdown = service.shutdown_receiver();
let server = axum::serve(listener, app)
.with_graceful_shutdown(async move {
let _ = shutdown.wait_for(|stopped| *stopped).await;
})
.into_future();
let server = server::serve(listener, rpc, async move {
let _ = shutdown.wait_for(|stopped| *stopped).await;
});
tokio::pin!(server);
service.set_ready().await.map_err(io::Error::other)?;
let mut monitor = tokio::spawn(health::monitor(
service.clone(),
health_interval,
+30 -2
View File
@@ -3,8 +3,8 @@ use std::path::PathBuf;
use std::sync::Arc;
use buffa::{EnumValue, MessageField};
use proto::proto::control::{TerminalInfo, TerminalInfos, TerminalRuntimeInfo};
use proto::proto::grpc::health::v1::health_check_response::ServingStatus;
use proto::control::{TerminalInfo, TerminalInfos, TerminalRuntimeInfo};
use proto::rpc::health::{HealthReporter, ServingStatus};
use tokio::sync::{Mutex, Notify, watch};
use uuid::Uuid;
@@ -23,6 +23,7 @@ struct Inner {
data_path: PathBuf,
snapshots: watch::Sender<TerminalInfos>,
shutdown: watch::Sender<bool>,
health: HealthReporter,
probe_requested: Notify,
}
@@ -46,6 +47,13 @@ impl RegistryService {
let revisions = snapshot.infos.keys().map(|id| (id.clone(), 0)).collect();
let (snapshots, _) = watch::channel(snapshot.clone());
let (shutdown, _) = watch::channel(false);
let health = HealthReporter::new();
health
.set_statuses(&[
("", ServingStatus::NOT_SERVING),
("control.Center", ServingStatus::NOT_SERVING),
])
.expect("valid initial health statuses");
Ok(Self {
inner: Arc::new(Inner {
directory: Mutex::new(Directory {
@@ -56,6 +64,7 @@ impl RegistryService {
data_path,
snapshots,
shutdown,
health,
probe_requested: Notify::new(),
}),
})
@@ -71,9 +80,28 @@ impl RegistryService {
pub async fn shutdown(&self) {
let _directory = self.inner.directory.lock().await;
self.publish_readiness(ServingStatus::NOT_SERVING);
self.inner.shutdown.send_replace(true);
}
pub(crate) fn health_reporter(&self) -> &HealthReporter {
&self.inner.health
}
pub(crate) async fn set_ready(&self) -> Result<(), RegistryError> {
let _directory = self.inner.directory.lock().await;
self.ensure_running()?;
self.publish_readiness(ServingStatus::SERVING);
Ok(())
}
fn publish_readiness(&self, status: ServingStatus) {
self.inner
.health
.set_statuses(&[("", status), ("control.Center", status)])
.expect("readiness maps to valid health statuses");
}
pub async fn register(&self, info: TerminalInfo) -> Result<String, RegistryError> {
let info = normalize_info(info)?;
let service = self.clone();
+5 -4
View File
@@ -3,8 +3,8 @@ use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use buffa::Message;
use proto::proto::control::TerminalInfos;
use proto::proto::grpc::health::v1::health_check_response::ServingStatus;
use proto::control::TerminalInfos;
use proto::grpc::health::v1::health_check_response::ServingStatus;
use crate::RegistryError;
use crate::service::{normalize_info, terminal_id};
@@ -22,8 +22,9 @@ pub(crate) fn load(path: &Path) -> Result<TerminalInfos, RegistryError> {
Err(error) => {
let backup = corrupt_path(path);
std::fs::rename(path, &backup)?;
eprintln!(
"invalid registry snapshot ({error}); moved to {}",
log::warn!(
"invalid registry snapshot error={error} path={} backup_path={}",
path.display(),
backup.display()
);
Ok(TerminalInfos::default())
+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};