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
+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());
}