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;
+191
View File
@@ -0,0 +1,191 @@
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use axum::Router;
use buffa_types::google::protobuf::{Empty, StringValue};
use connectrpc::client::{ClientConfig, Http2Connection};
use connectrpc::{
ConnectError, Protocol, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::stream;
use proto::proto::control::{
Center, Command, InvokeResponse, TerminalClient, TerminalInfo, TerminalInfos,
TerminalRegisterResponse,
};
use proto::proto::grpc::health::v1::{
HealthCheckRequest, HealthClient, health_check_response::ServingStatus,
};
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
use crate::runtime::RunningServer;
use crate::terminal::Service;
const CENTER_ASSIGNED_ID: &str = "center-terminal-1";
#[derive(Default)]
struct FakeCenter {
registered: Mutex<Option<TerminalInfo>>,
deregistered_id: Mutex<Option<String>>,
}
#[allow(refining_impl_trait)]
impl Center for FakeCenter {
async fn register_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, TerminalInfo>,
) -> ServiceResult<TerminalRegisterResponse> {
*self.registered.lock().unwrap() = Some(request.to_owned_message());
Response::ok(TerminalRegisterResponse {
success: true,
message: CENTER_ASSIGNED_ID.to_owned(),
..Default::default()
})
}
async fn deregister_terminal(
&self,
_context: RequestContext,
request: ServiceRequest<'_, StringValue>,
) -> ServiceResult<InvokeResponse> {
*self.deregistered_id.lock().unwrap() = Some(request.to_owned_message().value);
Response::ok(InvokeResponse {
success: true,
..Default::default()
})
}
async fn subscribe_terminal(
&self,
_context: RequestContext,
_request: ServiceRequest<'_, Empty>,
) -> ServiceResult<ServiceStream<TerminalInfos>> {
Response::stream_ok(stream::empty::<Result<TerminalInfos, ConnectError>>())
}
}
#[test]
fn start_registers_actual_port_and_stop_deregisters_same_id() {
let center = Arc::new(FakeCenter::default());
let center_runtime = Runtime::new().unwrap();
let listener = center_runtime
.block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0)))
.unwrap();
let center_port = listener.local_addr().unwrap().port();
let rpc = connectrpc::Router::new().add_service(Arc::clone(&center));
let app = Router::new().fallback_service(rpc.into_axum_service());
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let (started_tx, started_rx) = mpsc::sync_channel(1);
let center_task = center_runtime.spawn(async move {
started_tx.send(()).unwrap();
axum::serve(listener, app)
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
});
started_rx.recv_timeout(Duration::from_secs(1)).unwrap();
let service = Service::new_value();
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".to_owned(),
terminal_port: 0,
terminal_mac: "00:11:22:33:44:55".to_owned(),
..Default::default()
})
.unwrap();
let server = RunningServer::start(&service, "127.0.0.1".to_owned(), center_port).unwrap();
let registered = center.registered.lock().unwrap().clone().unwrap();
assert_ne!(registered.terminal_port, 0);
assert_eq!(registered.terminal_port, u32::from(server.bound_port()));
assert_eq!(
service.meta_status_receiver().borrow().terminal_id,
CENTER_ASSIGNED_ID
);
let terminal_uri: axum::http::Uri = format!("http://127.0.0.1:{}", server.bound_port())
.parse()
.unwrap();
center_runtime.block_on(async {
let connection = Http2Connection::connect_plaintext(terminal_uri.clone())
.await
.unwrap();
let connection = connection.shared(32);
let config = ClientConfig::new(terminal_uri)
.with_protocol(Protocol::Grpc)
.with_default_timeout(Duration::from_secs(2));
let health = HealthClient::new(connection.clone(), config.clone());
for name in ["", "control.Terminal"] {
let response = health
.check(HealthCheckRequest {
service: name.into(),
..Default::default()
})
.await
.unwrap()
.into_owned();
assert_eq!(response.status, ServingStatus::SERVING);
}
let error = health
.check(HealthCheckRequest {
service: "missing".into(),
..Default::default()
})
.await
.unwrap_err();
assert_eq!(error.code, connectrpc::ErrorCode::NotFound);
let mut watcher = health.watch(HealthCheckRequest::default()).await.unwrap();
assert_eq!(
watcher
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVING
);
drop(watcher);
let mut watcher = health
.watch(HealthCheckRequest {
service: "missing".into(),
..Default::default()
})
.await
.unwrap();
assert_eq!(
watcher
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVICE_UNKNOWN
);
drop(watcher);
let client = TerminalClient::new(connection, config);
let response = client
.execute(Command {
id: "not-registered".to_owned(),
..Default::default()
})
.await
.unwrap()
.into_owned();
assert!(!response.success);
});
server.stop(&service).unwrap();
assert_eq!(
center.deregistered_id.lock().unwrap().as_deref(),
Some(CENTER_ASSIGNED_ID)
);
shutdown_tx.send(()).unwrap();
center_runtime.block_on(center_task).unwrap().unwrap();
}
+79
View File
@@ -0,0 +1,79 @@
use std::ptr;
use buffa::Message;
use proto::proto::control::TerminalInfo;
use crate::ffi::*;
#[test]
fn null_handles_are_rejected() {
assert_eq!(
unsafe { terminal_service_configure(ptr::null_mut(), ptr::null(), 0) },
TERMINAL_ERROR_NULL
);
assert_eq!(
unsafe { terminal_service_destroy(ptr::null_mut()) },
TERMINAL_ERROR_NULL
);
}
#[test]
fn invalid_protobuf_is_reported_through_last_error() {
let handle = terminal_service_create();
let invalid = [0xff_u8, 0xff];
assert_eq!(
unsafe { terminal_service_configure(handle, invalid.as_ptr(), invalid.len()) },
TERMINAL_ERROR_DECODE
);
let mut required = 0;
assert_eq!(
unsafe { terminal_service_last_error(handle, ptr::null_mut(), &mut required) },
TERMINAL_OK
);
assert!(required > 1);
let mut buffer = vec![0_u8; required];
assert_eq!(
unsafe { terminal_service_last_error(handle, buffer.as_mut_ptr(), &mut required) },
TERMINAL_OK
);
let message = std::str::from_utf8(&buffer[..required - 1]).unwrap();
assert!(message.starts_with("DECODE_FAILED:"));
assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK);
}
#[test]
fn configured_service_can_be_destroyed() {
let handle = terminal_service_create();
let info = TerminalInfo {
terminal_host: "127.0.0.1".to_owned(),
terminal_port: 0,
terminal_mac: "00:11:22:33:44:55".to_owned(),
..Default::default()
}
.encode_to_vec();
assert_eq!(
unsafe { terminal_service_configure(handle, info.as_ptr(), info.len()) },
TERMINAL_OK
);
assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK);
}
#[test]
fn null_callback_is_rejected() {
let handle = terminal_service_create();
let command_id = b"init";
assert_eq!(
unsafe {
terminal_service_register_command(
handle,
command_id.as_ptr(),
command_id.len(),
None,
ptr::null_mut(),
)
},
TERMINAL_ERROR_INVALID_ARGUMENT
);
assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK);
}
+67
View File
@@ -0,0 +1,67 @@
use futures_util::StreamExt;
use proto::proto::control::TerminalInfo;
use proto::proto::grpc::health::v1::health_check_response::ServingStatus;
use crate::health::TerminalHealth;
use crate::terminal::Service;
#[tokio::test]
async fn lifecycle_health_stream_and_shutdown() {
let service = Service::new_value();
let health = TerminalHealth(service.clone());
let mut responses = health.responses("");
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::NOT_SERVING
);
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_mac: "test".into(),
..Default::default()
})
.unwrap();
service.set_starting().unwrap();
assert_eq!(
service.health_receiver().borrow().status,
ServingStatus::NOT_SERVING
);
service.set_ready("id".into()).unwrap();
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::SERVING
);
service.set_stopping().unwrap();
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::NOT_SERVING
);
service.set_stopped();
service.set_starting().unwrap();
service.set_configured();
assert_eq!(
service.health_receiver().borrow().status,
ServingStatus::NOT_SERVING
);
service.signal_shutdown();
assert!(responses.next().await.is_none());
assert!(health.responses("").next().await.is_none());
}
#[tokio::test]
async fn unknown_watch_stays_open_until_shutdown() {
let service = Service::new_value();
let health = TerminalHealth(service.clone());
let mut responses = health.responses("missing");
assert_eq!(
responses.next().await.unwrap().unwrap().status,
ServingStatus::SERVICE_UNKNOWN
);
assert!(
tokio::time::timeout(std::time::Duration::from_millis(20), responses.next())
.await
.is_err()
);
service.signal_shutdown();
assert!(responses.next().await.is_none());
}
+3
View File
@@ -0,0 +1,3 @@
mod ffi;
mod health;
mod terminal;
+228
View File
@@ -0,0 +1,228 @@
use std::ffi::c_void;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use buffa::Message;
use proto::proto::control::{
Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle,
TerminalEventInfo, TerminalInfo, TerminalStatus,
};
use crate::callback::{CommandCallback, EventCallback, TerminalResponseSink};
use crate::terminal::Service;
unsafe extern "C" fn successful_command(
_user_data: *mut c_void,
_command: *const u8,
_command_len: usize,
sink: TerminalResponseSink,
sink_context: *mut c_void,
) -> i32 {
send_response(sink, sink_context, true)
}
unsafe extern "C" fn counted_event(
user_data: *mut c_void,
_event: *const u8,
_event_len: usize,
_instance_id: u64,
sink: TerminalResponseSink,
sink_context: *mut c_void,
) -> i32 {
unsafe { &*(user_data as *const AtomicUsize) }.fetch_add(1, Ordering::SeqCst);
send_response(sink, sink_context, true)
}
fn send_response(sink: TerminalResponseSink, sink_context: *mut c_void, success: bool) -> i32 {
let response = InvokeResponse {
success,
..Default::default()
}
.encode_to_vec();
unsafe { sink(sink_context, response.as_ptr(), response.len()) }
}
fn ready_service() -> Service {
let service = Service::new_value();
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".to_owned(),
terminal_port: 0,
terminal_mac: "00:11:22:33:44:55".to_owned(),
..Default::default()
})
.unwrap();
service.set_starting().unwrap();
service.set_ready("terminal-1".to_owned()).unwrap();
service
}
async fn initialize(service: &Service) {
service
.register_command(
"init".to_owned(),
CommandCallback::new(Some(successful_command), std::ptr::null_mut()).unwrap(),
)
.unwrap();
let response = service
.execute_command(Command {
id: "init".to_owned(),
..Default::default()
})
.await;
assert!(response.success);
}
#[test]
fn status_sequence_and_timestamp_are_managed_by_rust() {
let service = ready_service();
let receiver = service.status_receiver();
service
.push_status(TerminalStatus {
sequence: 999,
timestamp: -1,
..Default::default()
})
.unwrap();
let first = receiver.borrow().clone();
assert_eq!(first.sequence, 1);
assert!(first.timestamp > 0);
service.push_status(TerminalStatus::default()).unwrap();
assert_eq!(receiver.borrow().sequence, 2);
}
#[tokio::test]
async fn meta_status_is_derived_from_rust_owned_state() {
let service = ready_service();
initialize(&service).await;
let counter = AtomicUsize::new(0);
service
.register_event(
TerminalEventInfo {
event_id: "engine-fire".to_owned(),
..Default::default()
},
EventCallback::new(
Some(counted_event),
(&counter as *const AtomicUsize).cast_mut().cast::<c_void>(),
)
.unwrap(),
)
.unwrap();
let receiver = service.meta_status_receiver();
assert_eq!(receiver.borrow().terminal_id, "terminal-1");
assert_eq!(receiver.borrow().publishable_events.len(), 1);
let response = service
.publish_event(TerminalEvent {
event_id: "engine-fire".to_owned(),
trigger_delay_ms: 10_000,
..Default::default()
})
.await;
let handle = response
.message
.as_option()
.unwrap()
.unpack_if::<TerminalEventHandle>(TerminalEventHandle::TYPE_URL)
.unwrap()
.unwrap();
assert_eq!(
receiver.borrow().triggered_events.get(&handle.instance_id),
Some(&handle.event_id)
);
let cancelled = service.cancel_event(TerminalCancelEvent {
event_id: handle.event_id,
instance_id: handle.instance_id,
..Default::default()
});
assert!(cancelled.success);
assert!(receiver.borrow().triggered_events.is_empty());
}
#[tokio::test]
async fn repeating_event_waits_for_explicit_completion() {
let service = ready_service();
initialize(&service).await;
let counter = AtomicUsize::new(0);
service
.register_event(
TerminalEventInfo {
event_id: "repeat".to_owned(),
..Default::default()
},
EventCallback::new(
Some(counted_event),
(&counter as *const AtomicUsize).cast_mut().cast::<c_void>(),
)
.unwrap(),
)
.unwrap();
let response = service
.publish_event(TerminalEvent {
event_id: "repeat".to_owned(),
trigger_delay_ms: 10,
repeat_period_ms: 10,
..Default::default()
})
.await;
let handle = response
.message
.as_option()
.unwrap()
.unpack_if::<TerminalEventHandle>(TerminalEventHandle::TYPE_URL)
.unwrap()
.unwrap();
wait_for_count(&counter, 1).await;
tokio::time::sleep(Duration::from_millis(30)).await;
assert_eq!(counter.load(Ordering::SeqCst), 1);
service
.complete_event(
&handle,
&InvokeResponse {
success: true,
..Default::default()
},
)
.unwrap();
wait_for_count(&counter, 2).await;
service
.complete_event(
&handle,
&InvokeResponse {
success: false,
..Default::default()
},
)
.unwrap();
tokio::time::timeout(Duration::from_secs(1), async {
while service
.meta_status_receiver()
.borrow()
.triggered_events
.contains_key(&handle.instance_id)
{
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
async fn wait_for_count(counter: &AtomicUsize, expected: usize) {
tokio::time::timeout(Duration::from_secs(1), async {
while counter.load(Ordering::SeqCst) < expected {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}