Add terminal service implementation and integration tests

- Introduced terminal.h header file defining the terminal service API.
- Implemented integration tests for terminal service registration and health checks.
- Added unit tests for FFI layer, health checks, and terminal service functionality.
- Created a mock center for testing terminal registration and deregistration.
- Ensured proper error handling and response validation in tests.
This commit is contained in:
2026-09-20 10:55:38 +08:00
parent 3bef0e4ef2
commit 7f331565c7
90 changed files with 7807 additions and 14 deletions
+16 -1
View File
@@ -2,4 +2,19 @@
name = "registry"
version.workspace = true
edition.workspace = true
author.workspace = true
authors.workspace = true
[dependencies]
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
[dev-dependencies]
terminal = { path = "../terminal" }
+120
View File
@@ -0,0 +1,120 @@
# Registry
The registry implements the `control.Center` service over plaintext HTTP/2 gRPC
using ConnectRPC and Axum. It stores the active terminal directory and checks
each terminal through `grpc.health.v1.Health/Check` on its registered port.
## Run
Run from the workspace root:
```powershell
Copy-Item .env.example .env
cargo run -p registry
```
The `.env` file is optional and is read from the current working directory.
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` |
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.
## Directory Contract
- Registration requires a nonempty host, a reachable port in `1..=65535`, and a
nonempty MAC. Metadata is stored as provided; it is not interpreted here.
- MAC identity is `trim().to_ascii_lowercase()`. Separator characters are not
rewritten. Logical identifiers are accepted as well as physical MAC addresses.
- IDs are UUID v5 values in namespace `9a55cb17-4014-5712-8c2a-64d47c9b613a`, using
the normalized MAC's UTF-8 bytes. Do not change this namespace or normalization:
the same identity retains its ID across restarts and explicit deregistration.
- Identical registration retries return the existing ID without writing or
publishing. Changed information retains the ID, resets health to `UNKNOWN`,
and requests a new check. Deregistering an absent ID succeeds without publishing.
- Business failures use `success=false`. Registration errors are strings;
deregistration errors are `google.protobuf.StringValue` packed into `Any`.
- Subscribers immediately receive the full current directory, including an empty
directory. Later messages are complete replacement snapshots, not deltas.
Slow readers may skip intermediate snapshots and receive the latest state.
- Directory mutations serialize, persist first, then publish. Once accepted,
a mutation completes even if its requesting client disconnects, so a retry
can safely discover the committed outcome.
## Storage And Recovery
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.
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
no separate backup recovery state. A process crash leaves either the previous
or committed snapshot. Uncommitted `.registry-snapshot-*` files are ignored and
can be removed while the registry is stopped. This is not a guarantee against
filesystem damage or sudden power loss; keep operational backups separately.
Only one registry process may own a data path. Shared storage, replication,
configuration hot reload, authentication, and TLS are not implemented. Deploy
on a trusted network or behind an appropriately secured proxy; registration
authorizes outbound health connections to the supplied host and port.
## Health
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.
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.
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`
stream from Watch. Health describes service readiness, not simulation state.
## Verify
All test implementations and test-only helpers live under `tests/`:
- `tests/unit/{config,health,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)
declares it under `integration_tests`.
Like Terminal, [src/lib.rs](src/lib.rs) loads both test groups through `#[cfg(test)]`
and `#[path]`. Production modules do not declare individual test modules. Tests
use explicit crate imports and narrowly scoped `pub(crate)` functions, without
adding public library APIs or exposing the directory's private state.
The cancellation test uses a current-thread runtime to drop a polled caller
before its spawned transaction is scheduled, without accessing internal locks.
Both test groups run in the library test target; there is no standalone
`--test integration` target. Each test module is loaded exactly once.
```powershell
cargo test -p registry
cargo test -p registry --lib unit_tests
cargo test -p registry --lib integration_tests::runtime
cargo test -p registry -p terminal
cargo test --workspace
```
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.
+110
View File
@@ -0,0 +1,110 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::RegistryError;
const KEYS: [&str; 7] = [
"HOST",
"PORT",
"DATA_PATH",
"HEALTH_INTERVAL_SECS",
"HEALTH_TIMEOUT_SECS",
"DATA_FILE_COUNT",
"LOG_LEVEL",
];
#[derive(Clone, Debug)]
pub struct Config {
pub host: String,
pub port: u16,
pub data_path: PathBuf,
pub health_interval: Duration,
pub health_timeout: Duration,
pub data_file_count: u64,
pub log_level: String,
}
impl Config {
pub fn load() -> Result<Self, RegistryError> {
let mut environment = HashMap::new();
for key in KEYS {
match std::env::var(key) {
Ok(value) => {
environment.insert(key.to_owned(), value);
}
Err(std::env::VarError::NotPresent) => {}
Err(error) => return Err(RegistryError::new("CONFIG_ERROR", error.to_string())),
}
}
Self::from_file(Path::new(".env"), environment)
}
pub(crate) fn from_file(
path: &Path,
environment: HashMap<String, String>,
) -> Result<Self, RegistryError> {
let mut values = HashMap::new();
match dotenvy::from_path_iter(path) {
Ok(entries) => {
for entry in entries {
let (key, value) = entry
.map_err(|error| RegistryError::new("CONFIG_ERROR", error.to_string()))?;
values.insert(key, value);
}
}
Err(dotenvy::Error::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(RegistryError::new("CONFIG_ERROR", error.to_string())),
}
values.extend(environment);
let value = |key: &str, default: &str| {
values
.get(key)
.map(String::as_str)
.unwrap_or(default)
.trim()
.to_owned()
};
let positive = |key: &str, default: &str| -> Result<u64, RegistryError> {
value(key, default)
.parse::<u64>()
.ok()
.filter(|number| *number > 0)
.ok_or_else(|| {
RegistryError::new("CONFIG_ERROR", format!("{key} must be a positive integer"))
})
};
let port = u16::try_from(positive("PORT", "50051")?)
.map_err(|_| RegistryError::new("CONFIG_ERROR", "PORT exceeds 65535"))?;
let host = value("HOST", "0.0.0.0");
let data_path = value("DATA_PATH", "registry/data/terminals.bin");
if host.is_empty() || data_path.is_empty() {
return Err(RegistryError::new(
"CONFIG_ERROR",
"host and data path must not be empty",
));
}
let health_interval = Duration::from_secs(positive("HEALTH_INTERVAL_SECS", "10")?);
let health_timeout = Duration::from_secs(positive("HEALTH_TIMEOUT_SECS", "3")?);
if std::time::Instant::now()
.checked_add(health_interval.max(health_timeout))
.is_none()
{
return Err(RegistryError::new(
"CONFIG_ERROR",
"health duration is too large",
));
}
let data_file_count = positive("DATA_FILE_COUNT", "10")?;
let log_level = value("LOG_LEVEL", "info");
Ok(Self {
host,
port,
data_path: data_path.into(),
health_interval,
health_timeout,
data_file_count: data_file_count,
log_level,
})
}
}
+52
View File
@@ -0,0 +1,52 @@
use std::fmt;
use buffa::MessageField;
use buffa_types::google::protobuf::{Any, StringValue};
use proto::proto::control::InvokeResponse;
#[derive(Debug)]
pub struct RegistryError {
pub code: &'static str,
pub message: String,
}
impl RegistryError {
pub(crate) fn new(code: &'static str, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
pub(crate) fn into_response(self) -> InvokeResponse {
let message = StringValue {
value: self.to_string(),
..Default::default()
};
InvokeResponse {
success: false,
message: MessageField::some(Any::pack(&message, StringValue::TYPE_URL)),
..Default::default()
}
}
}
impl fmt::Display for RegistryError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}: {}", self.code, self.message)
}
}
impl std::error::Error for RegistryError {}
impl From<std::io::Error> for RegistryError {
fn from(error: std::io::Error) -> Self {
Self::new("IO_ERROR", error.to_string())
}
}
impl From<tokio::task::JoinError> for RegistryError {
fn from(error: tokio::task::JoinError) -> Self {
Self::new("INTERNAL", error.to_string())
}
}
+88
View File
@@ -0,0 +1,88 @@
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 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 {
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(),
}
}
pub(crate) async fn monitor(service: RegistryService, interval: Duration, timeout: Duration) {
let mut shutdown = service.shutdown_receiver();
let mut timer = tokio::time::interval(interval);
timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
if *shutdown.borrow() {
return;
}
tokio::select! {
biased;
_ = shutdown.wait_for(|stopped| *stopped) => return,
_ = service.probe_requested() => {},
_ = timer.tick() => {},
}
let targets = service.probe_targets().await;
let checks = stream::iter(targets)
.map(|target| async move {
let status = check(&target.info, timeout).await;
(target, status)
})
.buffer_unordered(32);
tokio::pin!(checks);
loop {
let result = tokio::select! {
biased;
_ = shutdown.wait_for(|stopped| *stopped) => return,
result = checks.next() => result,
};
match result {
Some((target, status)) => service.update_health(&target, status).await,
None => break,
}
}
}
}
+19
View File
@@ -0,0 +1,19 @@
pub mod config;
pub mod error;
mod health;
mod rpc;
pub mod runtime;
pub mod service;
mod storage;
pub use config::Config;
pub use error::RegistryError;
pub use service::RegistryService;
#[cfg(test)]
#[path = "../tests/unit/mod.rs"]
mod unit_tests;
#[cfg(test)]
#[path = "../tests/integration/mod.rs"]
mod integration_tests;
+27 -4
View File
@@ -1,4 +1,27 @@
fn main() {
println!("Hello, registry!");
}
use registry::{Config, RegistryService, runtime};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::load()?;
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 {}",
listener.local_addr()?,
service.subscribe().borrow().infos.len(),
config.data_path.display()
);
runtime::serve(
listener,
service,
config.health_interval,
config.health_timeout,
async {
if let Err(error) = tokio::signal::ctrl_c().await {
eprintln!("failed to listen for shutdown signal: {error}");
}
},
)
.await?;
Ok(())
}
+77
View File
@@ -0,0 +1,77 @@
use buffa_types::google::protobuf::{Empty, StringValue};
use connectrpc::{
ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::{Stream, stream};
use proto::proto::control::{
Center, InvokeResponse, TerminalInfo, TerminalInfos, TerminalRegisterResponse,
};
use tokio::sync::watch;
use crate::RegistryService;
#[allow(refining_impl_trait)]
impl Center for RegistryService {
async fn register_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, TerminalInfo>,
) -> ServiceResult<TerminalRegisterResponse> {
let (success, message) = match self.register(request.to_owned_message()).await {
Ok(id) => (true, id),
Err(error) => (false, error.to_string()),
};
Response::ok(TerminalRegisterResponse {
success,
message,
..Default::default()
})
}
async fn deregister_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, StringValue>,
) -> ServiceResult<InvokeResponse> {
Response::ok(
match self.deregister(request.to_owned_message().value).await {
Ok(()) => InvokeResponse {
success: true,
..Default::default()
},
Err(error) => error.into_response(),
},
)
}
async fn subscribe_terminal(
&self,
_context: RequestContext,
_request: ServiceRequest<'_, Empty>,
) -> ServiceResult<ServiceStream<TerminalInfos>> {
Response::stream_ok(snapshots(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)))
},
)
}
+72
View File
@@ -0,0 +1,72 @@
use std::future::{Future, IntoFuture};
use std::io;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use crate::{RegistryService, health};
pub async fn serve(
listener: TcpListener,
service: RegistryService,
health_interval: Duration,
health_timeout: Duration,
stop: impl Future<Output = ()> + Send,
) -> io::Result<()> {
if health_interval.is_zero()
|| health_timeout.is_zero()
|| std::time::Instant::now()
.checked_add(health_interval.max(health_timeout))
.is_none()
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"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 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();
tokio::pin!(server);
let mut monitor = tokio::spawn(health::monitor(
service.clone(),
health_interval,
health_timeout,
));
let mut monitor_finished = false;
let mut server_finished = false;
let completed = tokio::select! {
result = &mut server => { server_finished = true; result },
_ = stop => Ok(()),
result = &mut monitor => {
monitor_finished = true;
if result.is_ok() && *service.shutdown_receiver().borrow() {
Ok(())
} else {
Err(io::Error::other(format!("health monitor stopped unexpectedly: {result:?}")))
}
}
};
service.shutdown().await;
let drained = if server_finished {
Ok(())
} else {
match tokio::time::timeout(Duration::from_secs(5), &mut server).await {
Ok(result) => result,
Err(_) => Err(io::Error::new(
io::ErrorKind::TimedOut,
"registry shutdown timed out",
)),
}
};
if !monitor_finished {
monitor.await.map_err(io::Error::other)?;
}
completed.and(drained)
}
+206
View File
@@ -0,0 +1,206 @@
use std::collections::HashMap;
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 tokio::sync::{Mutex, Notify, watch};
use uuid::Uuid;
use crate::{RegistryError, storage};
const ID_NAMESPACE: Uuid = Uuid::from_u128(0x9a55cb17401457128c2a64d47c9b613a);
struct Directory {
snapshot: TerminalInfos,
revisions: HashMap<String, u64>,
next_revision: u64,
}
struct Inner {
directory: Mutex<Directory>,
data_path: PathBuf,
snapshots: watch::Sender<TerminalInfos>,
shutdown: watch::Sender<bool>,
probe_requested: Notify,
}
#[derive(Clone)]
pub struct RegistryService {
inner: Arc<Inner>,
}
#[derive(Clone)]
pub(crate) struct ProbeTarget {
pub id: String,
pub info: TerminalInfo,
revision: u64,
}
impl RegistryService {
pub async fn open(data_path: impl Into<PathBuf>) -> Result<Self, RegistryError> {
let data_path = data_path.into();
let load_path = data_path.clone();
let snapshot = tokio::task::spawn_blocking(move || storage::load(&load_path)).await??;
let revisions = snapshot.infos.keys().map(|id| (id.clone(), 0)).collect();
let (snapshots, _) = watch::channel(snapshot.clone());
let (shutdown, _) = watch::channel(false);
Ok(Self {
inner: Arc::new(Inner {
directory: Mutex::new(Directory {
snapshot,
revisions,
next_revision: 1,
}),
data_path,
snapshots,
shutdown,
probe_requested: Notify::new(),
}),
})
}
pub fn subscribe(&self) -> watch::Receiver<TerminalInfos> {
self.inner.snapshots.subscribe()
}
pub fn shutdown_receiver(&self) -> watch::Receiver<bool> {
self.inner.shutdown.subscribe()
}
pub async fn shutdown(&self) {
let _directory = self.inner.directory.lock().await;
self.inner.shutdown.send_replace(true);
}
pub async fn register(&self, info: TerminalInfo) -> Result<String, RegistryError> {
let info = normalize_info(info)?;
let service = self.clone();
tokio::spawn(async move { service.register_transaction(info).await }).await?
}
async fn register_transaction(&self, info: TerminalInfo) -> Result<String, RegistryError> {
let mut directory = self.inner.directory.lock().await;
self.ensure_running()?;
let id = terminal_id(&info.terminal_mac);
if directory
.snapshot
.infos
.get(&id)
.and_then(|runtime| runtime.info.as_option())
== Some(&info)
{
return Ok(id);
}
let mut candidate = directory.snapshot.clone();
candidate.infos.insert(
id.clone(),
TerminalRuntimeInfo {
info: MessageField::some(info),
status: ServingStatus::UNKNOWN.into(),
..Default::default()
},
);
self.persist(candidate.clone()).await?;
let revision = directory.next_revision;
directory.next_revision += 1;
directory.revisions.insert(id.clone(), revision);
directory.snapshot = candidate.clone();
self.inner.snapshots.send_replace(candidate);
self.inner.probe_requested.notify_one();
Ok(id)
}
pub async fn deregister(&self, id: String) -> Result<(), RegistryError> {
let service = self.clone();
tokio::spawn(async move {
let mut directory = service.inner.directory.lock().await;
service.ensure_running()?;
let mut candidate = directory.snapshot.clone();
if candidate.infos.remove(&id).is_none() {
return Ok(());
}
service.persist(candidate.clone()).await?;
directory.revisions.remove(&id);
directory.snapshot = candidate.clone();
service.inner.snapshots.send_replace(candidate);
service.inner.probe_requested.notify_one();
Ok(())
})
.await?
}
async fn persist(&self, snapshot: TerminalInfos) -> Result<(), RegistryError> {
let path = self.inner.data_path.clone();
tokio::task::spawn_blocking(move || storage::save(&path, snapshot)).await?
}
fn ensure_running(&self) -> Result<(), RegistryError> {
if *self.inner.shutdown.borrow() {
Err(RegistryError::new(
"UNAVAILABLE",
"registry is shutting down",
))
} else {
Ok(())
}
}
pub(crate) async fn probe_requested(&self) {
self.inner.probe_requested.notified().await;
}
pub(crate) async fn probe_targets(&self) -> Vec<ProbeTarget> {
let directory = self.inner.directory.lock().await;
directory
.snapshot
.infos
.iter()
.map(|(id, runtime)| ProbeTarget {
id: id.clone(),
info: runtime.info.as_option().unwrap().clone(),
revision: directory.revisions[id],
})
.collect()
}
pub(crate) async fn update_health(
&self,
target: &ProbeTarget,
status: EnumValue<ServingStatus>,
) {
let mut directory = self.inner.directory.lock().await;
if *self.inner.shutdown.borrow()
|| directory.revisions.get(&target.id) != Some(&target.revision)
{
return;
}
if let Some(runtime) = directory.snapshot.infos.get_mut(&target.id) {
if runtime.status != status {
runtime.status = status;
self.inner
.snapshots
.send_replace(directory.snapshot.clone());
}
}
}
}
pub(crate) fn terminal_id(mac: &str) -> String {
Uuid::new_v5(&ID_NAMESPACE, mac.as_bytes()).to_string()
}
pub(crate) fn normalize_info(mut info: TerminalInfo) -> Result<TerminalInfo, RegistryError> {
info.terminal_mac = info.terminal_mac.trim().to_ascii_lowercase();
if info.terminal_mac.is_empty()
|| info.terminal_host.trim().is_empty()
|| !(1..=65535).contains(&info.terminal_port)
{
return Err(RegistryError::new(
"INVALID_ARGUMENT",
"host and MAC must be nonempty and port must be 1..=65535",
));
}
Ok(info)
}
+92
View File
@@ -0,0 +1,92 @@
use std::io::Write;
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 crate::RegistryError;
use crate::service::{normalize_info, terminal_id};
pub(crate) fn load(path: &Path) -> Result<TerminalInfos, RegistryError> {
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(TerminalInfos::default());
}
Err(error) => return Err(error.into()),
};
match decode(&bytes) {
Ok(snapshot) => Ok(snapshot),
Err(error) => {
let backup = corrupt_path(path);
std::fs::rename(path, &backup)?;
eprintln!(
"invalid registry snapshot ({error}); moved to {}",
backup.display()
);
Ok(TerminalInfos::default())
}
}
}
pub(crate) fn decode(bytes: &[u8]) -> Result<TerminalInfos, RegistryError> {
let mut snapshot = TerminalInfos::decode_from_slice(bytes)
.map_err(|error| RegistryError::new("INVALID_SNAPSHOT", error.to_string()))?;
for (id, runtime) in &mut snapshot.infos {
let info = runtime
.info
.as_option()
.ok_or_else(|| RegistryError::new("INVALID_SNAPSHOT", "terminal info is missing"))?;
let normalized = normalize_info(info.clone())?;
if &normalized != info || *id != terminal_id(&normalized.terminal_mac) {
return Err(RegistryError::new(
"INVALID_SNAPSHOT",
"noncanonical terminal identity",
));
}
runtime.status = ServingStatus::UNKNOWN.into();
}
Ok(snapshot)
}
fn corrupt_path(path: &Path) -> PathBuf {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let mut suffix = 0_u64;
loop {
let mut name = path.as_os_str().to_os_string();
name.push(format!(".corrupt-{timestamp}-{suffix}"));
let candidate = PathBuf::from(name);
if !candidate.exists() {
return candidate;
}
suffix += 1;
}
}
pub(crate) fn save(path: &Path, mut snapshot: TerminalInfos) -> Result<(), RegistryError> {
for runtime in snapshot.infos.values_mut() {
runtime.status = ServingStatus::UNKNOWN.into();
}
let bytes = snapshot
.try_encode_to_vec()
.map_err(|error| RegistryError::new("ENCODE_FAILED", error.to_string()))?;
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
std::fs::create_dir_all(parent)?;
let mut temporary = tempfile::Builder::new()
.prefix(".registry-snapshot-")
.tempfile_in(parent)?;
temporary.write_all(&bytes)?;
temporary.as_file().sync_all()?;
temporary
.persist(path)
.map_err(|error| RegistryError::from(error.error))?;
Ok(())
}
+1
View File
@@ -0,0 +1 @@
mod runtime;
+281
View File
@@ -0,0 +1,281 @@
use std::ffi::c_void;
use std::time::Duration;
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 terminal::ffi::*;
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use crate::{RegistryService, runtime::serve};
#[tokio::test]
async fn center_rpc_register_update_subscribe_deregister_and_shutdown() {
tokio::time::timeout(Duration::from_secs(10), async {
let directory = tempfile::tempdir().unwrap();
let service = RegistryService::open(directory.path().join("terminals.bin"))
.await
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let uri: axum::http::Uri = format!("http://{}", listener.local_addr().unwrap())
.parse()
.unwrap();
let (stop, stopped) = oneshot::channel();
let server = tokio::spawn(serve(
listener,
service.clone(),
Duration::from_secs(10),
Duration::from_millis(100),
async {
let _ = stopped.await;
},
));
let connection = Http2Connection::connect_plaintext(uri.clone())
.await
.unwrap();
let client = CenterClient::new(
connection.shared(32),
ClientConfig::new(uri)
.with_protocol(Protocol::Grpc)
.with_default_timeout(Duration::from_secs(5)),
);
let mut first = client.subscribe_terminal(Empty::default()).await.unwrap();
let mut second = client.subscribe_terminal(Empty::default()).await.unwrap();
assert!(
first
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.infos
.is_empty()
);
assert!(
second
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.infos
.is_empty()
);
let invalid = client
.register_terminal(TerminalInfo::default())
.await
.unwrap()
.into_owned();
assert!(!invalid.success);
assert!(invalid.message.starts_with("INVALID_ARGUMENT:"));
let mut info = TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_port: 1234,
terminal_mac: " AA:BB ".into(),
..Default::default()
};
let response = client
.register_terminal(info.clone())
.await
.unwrap()
.into_owned();
assert!(response.success);
let id = response.message;
assert_eq!(
first
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.infos[&id]
.info
.terminal_mac,
"aa:bb"
);
assert!(
second
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.infos
.contains_key(&id)
);
info.terminal_port = 4321;
let updated = client
.register_terminal(info.clone())
.await
.unwrap()
.into_owned();
assert!(updated.success);
assert_eq!(updated.message, id);
loop {
let snapshot = first.message().await.unwrap().unwrap().to_owned_message();
if snapshot.infos[&id].info.terminal_port == 4321 {
break;
}
}
for _attempt in 0..2 {
assert!(
client
.deregister_terminal(StringValue {
value: id.clone(),
..Default::default()
})
.await
.unwrap()
.into_owned()
.success
);
}
loop {
if first
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.infos
.is_empty()
{
break;
}
}
stop.send(()).unwrap();
assert!(first.message().await.unwrap().is_none());
drop(second);
drop(first);
drop(client);
server.await.unwrap().unwrap();
})
.await
.unwrap();
}
struct TerminalHandle(*mut c_void);
impl Drop for TerminalHandle {
fn drop(&mut self) {
unsafe {
terminal_service_destroy(self.0);
}
}
}
#[test]
fn real_terminal_survives_registry_restart_and_deregisters() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("terminals.bin");
let runtime = tokio::runtime::Runtime::new().unwrap();
let service = runtime.block_on(RegistryService::open(&path)).unwrap();
let listener = runtime.block_on(TcpListener::bind("127.0.0.1:0")).unwrap();
let address = listener.local_addr().unwrap();
let (stop, stopped) = oneshot::channel();
let server = runtime.spawn(serve(
listener,
service.clone(),
Duration::from_millis(20),
Duration::from_secs(1),
async {
let _ = stopped.await;
},
));
let handle = TerminalHandle(terminal_service_create());
let info = TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_port: 0,
terminal_mac: "real-terminal".into(),
..Default::default()
}
.encode_to_vec();
assert_eq!(
unsafe { terminal_service_configure(handle.0, info.as_ptr(), info.len()) },
TERMINAL_OK
);
let host = b"127.0.0.1";
let mut bound_port = 0;
assert_eq!(
unsafe {
terminal_service_start(
handle.0,
host.as_ptr(),
host.len(),
address.port(),
&mut bound_port,
)
},
TERMINAL_OK
);
assert_ne!(bound_port, 0);
let id = runtime.block_on(async {
let mut receiver = service.subscribe();
let snapshot = tokio::time::timeout(
Duration::from_secs(3),
receiver.wait_for(|snapshot| {
snapshot
.infos
.values()
.any(|runtime| runtime.status == ServingStatus::SERVING)
}),
)
.await
.unwrap()
.unwrap();
snapshot.infos.keys().next().unwrap().clone()
});
stop.send(()).unwrap();
runtime.block_on(async {
tokio::time::timeout(Duration::from_secs(6), server)
.await
.unwrap()
.unwrap()
.unwrap();
});
let restored = runtime.block_on(RegistryService::open(path)).unwrap();
assert_eq!(
restored.subscribe().borrow().infos[&id].status,
ServingStatus::UNKNOWN
);
assert_eq!(
restored.subscribe().borrow().infos[&id].info.terminal_port,
u32::from(bound_port)
);
let listener = runtime.block_on(TcpListener::bind(address)).unwrap();
let (stop, stopped) = oneshot::channel();
let server = runtime.spawn(serve(
listener,
restored.clone(),
Duration::from_millis(20),
Duration::from_secs(1),
async {
let _ = stopped.await;
},
));
runtime.block_on(async {
let mut receiver = restored.subscribe();
tokio::time::timeout(
Duration::from_secs(3),
receiver.wait_for(|snapshot| snapshot.infos[&id].status == ServingStatus::SERVING),
)
.await
.unwrap()
.unwrap();
});
assert_eq!(unsafe { terminal_service_stop(handle.0) }, TERMINAL_OK);
assert!(restored.subscribe().borrow().infos.is_empty());
drop(handle);
stop.send(()).unwrap();
runtime.block_on(async {
tokio::time::timeout(Duration::from_secs(6), server)
.await
.unwrap()
.unwrap()
.unwrap();
});
}
+39
View File
@@ -0,0 +1,39 @@
use std::collections::HashMap;
use std::time::Duration;
use crate::Config;
#[test]
fn defaults_file_and_environment_precedence() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join(".env");
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();
let config = Config::from_file(
&path,
HashMap::from([("REGISTRY_PORT".into(), "4321".into())]),
)
.unwrap();
assert_eq!(config.port, 4321);
assert_eq!(config.host, "localhost");
}
#[test]
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", ""),
] {
assert!(Config::from_file(&path, HashMap::from([(key.into(), value.into())])).is_err());
}
std::fs::write(&path, "REGISTRY_PORT='unterminated").unwrap();
assert!(Config::from_file(&path, HashMap::new()).is_err());
}
+141
View File
@@ -0,0 +1,141 @@
use std::sync::Arc;
use std::time::Duration;
use connectrpc::{
ConnectError, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::stream;
use proto::proto::control::TerminalInfo;
use proto::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};
struct FakeHealth(watch::Receiver<ServingStatus>);
#[allow(refining_impl_trait)]
impl Health for FakeHealth {
async fn check(
&self,
_: RequestContext,
request: ServiceRequest<'_, HealthCheckRequest>,
) -> ServiceResult<HealthCheckResponse> {
assert!(request.to_owned_message().service.is_empty());
Response::ok(HealthCheckResponse {
status: (*self.0.borrow()).into(),
..Default::default()
})
}
async fn watch(
&self,
_: RequestContext,
_: ServiceRequest<'_, HealthCheckRequest>,
) -> ServiceResult<ServiceStream<HealthCheckResponse>> {
Response::stream_ok(stream::empty::<Result<HealthCheckResponse, ConnectError>>())
}
}
async fn wait_status(
receiver: &mut watch::Receiver<proto::proto::control::TerminalInfos>,
id: &str,
status: ServingStatus,
) {
tokio::time::timeout(
Duration::from_secs(3),
receiver.wait_for(|snapshot| {
snapshot
.infos
.get(id)
.is_some_and(|runtime| runtime.status == status)
}),
)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn health_monitor_tracks_failure_and_recovery_without_removal() {
let directory = tempfile::tempdir().unwrap();
let service = RegistryService::open(directory.path().join("terminals.bin"))
.await
.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let (status, receiver) = watch::channel(ServingStatus::SERVING);
let rpc = connectrpc::Router::new().add_service(Arc::new(FakeHealth(receiver)));
let (stop, stopped) = oneshot::channel();
let server = tokio::spawn(async move {
axum::serve(
listener,
axum::Router::new().fallback_service(rpc.into_axum_service()),
)
.with_graceful_shutdown(async {
let _ = stopped.await;
})
.await
.unwrap();
});
let id = service
.register(TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_port: address.port().into(),
terminal_mac: "probe".into(),
..Default::default()
})
.await
.unwrap();
let mut snapshots = service.subscribe();
let worker = tokio::spawn(monitor(
service.clone(),
Duration::from_millis(20),
Duration::from_millis(100),
));
wait_status(&mut snapshots, &id, ServingStatus::SERVING).await;
status.send_replace(ServingStatus::NOT_SERVING);
wait_status(&mut snapshots, &id, ServingStatus::NOT_SERVING).await;
status.send_replace(ServingStatus::SERVING);
wait_status(&mut snapshots, &id, ServingStatus::SERVING).await;
stop.send(()).unwrap();
server.await.unwrap();
wait_status(&mut snapshots, &id, ServingStatus::NOT_SERVING).await;
assert_eq!(snapshots.borrow().infos.len(), 1);
service.shutdown().await;
tokio::time::timeout(Duration::from_secs(1), worker)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn timeout_covers_http2_connection_setup() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let info = TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_port: listener.local_addr().unwrap().port().into(),
..Default::default()
};
let status = tokio::time::timeout(
Duration::from_secs(1),
check(&info, Duration::from_millis(20)),
)
.await
.unwrap();
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()
})
.unwrap();
assert_eq!(uri.port_u16(), Some(1234));
}
}
+5
View File
@@ -0,0 +1,5 @@
mod config;
mod health;
mod rpc;
mod service;
mod storage;
+57
View File
@@ -0,0 +1,57 @@
use futures_util::StreamExt;
use proto::proto::control::TerminalInfo;
use crate::RegistryService;
use crate::rpc::snapshots;
#[tokio::test]
async fn subscribers_receive_initial_and_changed_snapshots_then_close() {
let directory = tempfile::tempdir().unwrap();
let service = RegistryService::open(directory.path().join("terminals.bin"))
.await
.unwrap();
let mut first = Box::pin(snapshots(service.subscribe(), service.shutdown_receiver()));
let mut second = Box::pin(snapshots(service.subscribe(), service.shutdown_receiver()));
assert!(first.next().await.unwrap().unwrap().infos.is_empty());
assert!(second.next().await.unwrap().unwrap().infos.is_empty());
let info = TerminalInfo {
terminal_host: "localhost".into(),
terminal_port: 1234,
terminal_mac: "aa".into(),
..Default::default()
};
let id = service.register(info.clone()).await.unwrap();
assert!(first.next().await.unwrap().unwrap().infos.contains_key(&id));
assert!(
second
.next()
.await
.unwrap()
.unwrap()
.infos
.contains_key(&id)
);
service.register(info).await.unwrap();
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), first.next())
.await
.is_err()
);
service.deregister(id).await.unwrap();
assert!(first.next().await.unwrap().unwrap().infos.is_empty());
assert!(second.next().await.unwrap().unwrap().infos.is_empty());
service.shutdown().await;
assert!(first.next().await.is_none());
assert!(second.next().await.is_none());
assert!(
service
.register(TerminalInfo {
terminal_host: "localhost".into(),
terminal_port: 1234,
terminal_mac: "aa".into(),
..Default::default()
})
.await
.is_err()
);
}
+177
View File
@@ -0,0 +1,177 @@
use proto::proto::control::TerminalInfo;
use proto::proto::grpc::health::v1::health_check_response::ServingStatus;
use crate::RegistryService;
use crate::service::normalize_info;
fn info() -> TerminalInfo {
TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_port: 1234,
terminal_mac: " AA:BB ".into(),
..Default::default()
}
}
#[tokio::test]
async fn identity_idempotency_restart_and_deregistration() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("terminals.bin");
let service = RegistryService::open(&path).await.unwrap();
let mut receiver = service.subscribe();
let id = service.register(info()).await.unwrap();
receiver.borrow_and_update();
let mut normalized = info();
normalized.terminal_mac = "aa:bb".into();
assert_eq!(service.register(normalized).await.unwrap(), id);
assert!(!receiver.has_changed().unwrap());
let target = service.probe_targets().await.pop().unwrap();
service
.update_health(&target, ServingStatus::SERVING.into())
.await;
let mut healthy = service.subscribe();
let persisted = std::fs::read(&path).unwrap();
service
.update_health(&target, ServingStatus::SERVING.into())
.await;
assert!(!healthy.has_changed().unwrap());
assert_eq!(std::fs::read(&path).unwrap(), persisted);
healthy.borrow_and_update();
let restored = RegistryService::open(&path).await.unwrap();
assert_eq!(
restored.subscribe().borrow().infos[&id].status,
ServingStatus::UNKNOWN
);
assert_eq!(restored.register(info()).await.unwrap(), id);
restored.deregister(id.clone()).await.unwrap();
let receiver = restored.subscribe();
restored.deregister(id.clone()).await.unwrap();
assert!(!receiver.has_changed().unwrap());
assert_eq!(restored.register(info()).await.unwrap(), id);
assert_eq!(
RegistryService::open(path)
.await
.unwrap()
.register(info())
.await
.unwrap(),
id
);
}
#[tokio::test]
async fn concurrent_registration_and_stale_probe_results() {
let directory = tempfile::tempdir().unwrap();
let service = RegistryService::open(directory.path().join("terminals.bin"))
.await
.unwrap();
let (first, second) = tokio::join!(service.register(info()), service.register(info()));
let id = first.unwrap();
assert_eq!(id, second.unwrap());
assert_eq!(service.subscribe().borrow().infos.len(), 1);
let old = service.probe_targets().await.pop().unwrap();
let mut updated = info();
updated.terminal_port += 1;
assert_eq!(service.register(updated).await.unwrap(), id);
service
.update_health(&old, ServingStatus::SERVING.into())
.await;
assert_eq!(
service.subscribe().borrow().infos[&id].status,
ServingStatus::UNKNOWN
);
service.deregister(id.clone()).await.unwrap();
service.register(info()).await.unwrap();
service
.update_health(&old, ServingStatus::SERVING.into())
.await;
assert_eq!(
service.subscribe().borrow().infos[&id].status,
ServingStatus::UNKNOWN
);
}
#[tokio::test]
async fn failed_persistence_does_not_commit_memory() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("terminals.bin");
let service = RegistryService::open(&path).await.unwrap();
let receiver = service.subscribe();
std::fs::create_dir(&path).unwrap();
assert!(service.register(info()).await.is_err());
assert!(receiver.borrow().infos.is_empty());
assert!(!receiver.has_changed().unwrap());
std::fs::remove_dir(&path).unwrap();
let id = service.register(info()).await.unwrap();
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
let mut updated = info();
updated.terminal_port = 4321;
assert!(service.register(updated).await.is_err());
assert_eq!(receiver.borrow().infos[&id].info.terminal_port, 1234);
assert!(service.deregister(id.clone()).await.is_err());
assert!(receiver.borrow().infos.contains_key(&id));
}
#[tokio::test(flavor = "current_thread")]
async fn cancelled_caller_does_not_interrupt_an_accepted_transaction() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("terminals.bin");
let service = RegistryService::open(&path).await.unwrap();
let mut receiver = service.subscribe();
let mut registration = Box::pin(service.register(info()));
assert!(futures_util::poll!(registration.as_mut()).is_pending());
drop(registration);
tokio::time::timeout(std::time::Duration::from_secs(2), receiver.changed())
.await
.unwrap()
.unwrap();
let committed = receiver.borrow().clone();
let restored = RegistryService::open(&path).await.unwrap();
assert_eq!(committed, *restored.subscribe().borrow());
let id = committed.infos.keys().next().unwrap().clone();
let mut deregistration = Box::pin(service.deregister(id));
assert!(futures_util::poll!(deregistration.as_mut()).is_pending());
drop(deregistration);
tokio::time::timeout(std::time::Duration::from_secs(2), receiver.changed())
.await
.unwrap()
.unwrap();
assert!(receiver.borrow().infos.is_empty());
assert!(
RegistryService::open(path)
.await
.unwrap()
.subscribe()
.borrow()
.infos
.is_empty()
);
}
#[test]
fn invalid_registration_is_rejected() {
for port in [0, 65536] {
assert!(
normalize_info(TerminalInfo {
terminal_port: port,
..info()
})
.is_err()
);
}
assert!(
normalize_info(TerminalInfo {
terminal_mac: " ".into(),
..info()
})
.is_err()
);
assert!(
normalize_info(TerminalInfo {
terminal_host: " ".into(),
..info()
})
.is_err()
);
}
+45
View File
@@ -0,0 +1,45 @@
use buffa::Message;
use proto::proto::control::TerminalInfos;
use crate::storage::{decode, load, save};
#[test]
fn corrupt_snapshot_is_preserved_and_uncommitted_temporary_is_ignored() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("terminals.bin");
std::fs::write(&path, [0xff]).unwrap();
assert!(load(&path).unwrap().infos.is_empty());
let backup = std::fs::read_dir(directory.path())
.unwrap()
.next()
.unwrap()
.unwrap()
.path();
assert!(
backup
.file_name()
.unwrap()
.to_string_lossy()
.contains(".corrupt-")
);
assert_eq!(std::fs::read(backup).unwrap(), [0xff]);
std::fs::write(
directory.path().join(".registry-snapshot-interrupted"),
[0xff],
)
.unwrap();
save(&path, TerminalInfos::default()).unwrap();
assert!(load(&path).unwrap().infos.is_empty());
assert_eq!(std::fs::read(path).unwrap(), Vec::<u8>::new());
}
#[test]
fn semantic_corruption_is_rejected() {
let snapshot = TerminalInfos {
infos: [("wrong-id".into(), Default::default())]
.into_iter()
.collect(),
..Default::default()
};
assert!(decode(&snapshot.try_encode_to_vec().unwrap()).is_err());
}