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
+8 -1
View File
@@ -12,9 +12,16 @@ proto.workspace = true
connectrpc.workspace = true
buffa.workspace = true
buffa-types.workspace = true
tokio.workspace = true
log.workspace = true
tracing.workspace = true
flysim-log.workspace = true
[dev-dependencies]
tempfile.workspace = true
tracing-subscriber.workspace = true
axum.workspace = true
futures-util.workspace = true
tokio.workspace = true
[build-dependencies]
cbindgen.workspace = true
+116 -12
View File
@@ -30,7 +30,8 @@ The C header declares functions and callbacks, not C Protobuf message structs.
## Host Integration
1. Call `terminal_service_create` to obtain an opaque handle.
1. Call `terminal_service_create` to obtain an opaque handle. To enable built-in
logs, call `terminal_logging_init` once before starting any terminal.
2. Serialize `control.TerminalInfo` and call `terminal_service_configure`.
3. Register command callbacks and event definitions/callbacks. Keep callback code
and user data alive for every possible invocation.
@@ -39,8 +40,9 @@ The C header declares functions and callbacks, not C Protobuf message structs.
the listener and center registration are ready.
5. Push simulation snapshots with `terminal_service_push_status`; report event
completion with `terminal_service_complete_event` when host work finishes.
6. Call `terminal_service_stop`, inspect any error, then destroy the stopped
handle with `terminal_service_destroy`.
6. Call `terminal_service_stop` and inspect any error. After all terminals and
callbacks have stopped, call `terminal_logging_shutdown` if built-in logs were
enabled, then destroy the remaining handle with `terminal_service_destroy`.
All functions are synchronous at the ABI boundary. In particular, start and stop
perform blocking network work. Invoke them from a normal host/control thread,
@@ -60,8 +62,8 @@ a handle while another thread may still use it.
Use an address that the center and control clients can reach. There is no separate
bind/advertised address, NAT discovery, or automatic conversion of wildcard hosts.
The center URI is built as `http://<center_host>:<center_port>`; bracket an IPv6
literal in `center_host`, for example `[::1]`.
The shared `RpcEndpoint` builds the center URI from host and port. IPv6 literals
can be supplied raw (`::1`) or bracketed (`[::1]`).
When the requested terminal port is zero, the actual bound port is written into
the stored `TerminalInfo` before registration and returned to the host. This also
@@ -71,6 +73,79 @@ stopped to request another OS-assigned port.
Command callback registration does not populate `meta_info.supported_type` or
its command descriptions automatically. The host must supply matching metadata.
## Logging
The backend is provided by [flysim-log](../log/README.md). Terminal retains
the module-wide FFI state, error mapping and explicit guard ownership; extracting
the backend does not change any C ABI signature or DLL-global restrictions.
Terminal records low-frequency lifecycle events with `log` macros: listener and
registration success, registration/deregistration failures and retries, shutdown
timeouts, and local stop. It does not log command payloads or high-frequency
status pushes. The same events reach stderr and daily rotating files through
`log -> tracing-log -> tracing-subscriber`; native tracing events also work.
Calling create/start/stop never installs or shuts down global logging implicitly.
For a C/C++ host, use the generated declarations in [terminal.h](terminal.h):
```c
void *handle = terminal_service_create();
const char *level = "info";
const char *directory = "logs/terminal";
int32_t result = terminal_logging_init(
handle,
(const uint8_t *)level, strlen(level),
(const uint8_t *)directory, strlen(directory),
10
);
```
Include `terminal.h` and `<string.h>` for this snippet. Check `result` against
`TERMINAL_OK` and retrieve details through `terminal_service_last_error`.
The handle supplies error storage only; logging is module-wide, not owned by
that terminal instance. UTF-8 input buffers are borrowed only for the call.
The level accepts `off/error/warn/info/debug/trace` case-insensitively; the log
directory must be nonempty and the maximum file count positive. Configuration
is passed explicitly, not read from `.env` or `RUST_LOG`. Files are named
`terminal.YYYY-MM-DD.log`, with UTC daily rotation and at most the specified
number of matching files (the example uses 10). Retention may remove old matching
files during initialization/rotation; it is not an exact number of days. Use a
dedicated directory per host process and do not store unrelated `terminal*.log`
files there. Relative paths resolve against the host's working directory.
Both outputs include UTC time, level and target; files disable ANSI colors.
stderr is synchronous. File output runs on a worker with an 8192-entry queue;
a full queue blocks the logging thread instead of dropping records. Slow
storage or consoles can delay the host and RPC threads. Worker-guard release
drains buffered records during normal shutdown, but cannot guarantee delivery
after a crash, forced termination, disk failure, or a stalled writer.
After stopping every terminal and in-flight callback, call
`terminal_logging_shutdown(handle)` on a normal host thread. Repeated shutdown
is harmless, and shutdown before initialization is a no-op. Keep a handle alive
for reporting shutdown errors. Do not close logging from inside a callback or
while another thread is initializing/shutting it down.
Initialization is once per module's logging instance. An existing logger or
subscriber is not replaced: initialization returns `TERMINAL_ERROR_INVALID_STATE`.
Invalid parameters return `TERMINAL_ERROR_INVALID_ARGUMENT`, and file/worker
initialization errors return `TERMINAL_ERROR_INTERNAL`. Ordinary parameter or I/O
failures may be corrected and retried. Installed global logger/subscriber state
cannot be uninstalled. Installation of the two globals is not atomic: serialize
this call with all host logging setup; a concurrent subscriber installation can
leave the bridge installed even though initialization fails. Such a failure is
reported and no new writer thread is retained.
Shutdown closes only the owned file worker, not the global logger/subscriber;
stderr may still receive late records. Do not expect file output afterward or
attempt to initialize again. Keep the library loaded until host process exit;
DLL hot unloading/reloading is not supported after global logging installation.
Rust static linking can share a host's logger/subscriber, while a separately
loaded cdylib may have independent globals. When the host already owns logging
in the same Rust instance, omit these initialization/shutdown calls. A terminal
can still run without built-in logging initialized.
## Runtime Lifecycle
[RunningServer](src/runtime.rs) owns one multithreaded Tokio runtime, the Axum
@@ -117,9 +192,12 @@ registration failure the server is signaled to close.
Center communication uses ConnectRPC's gRPC protocol over plaintext HTTP/2.
Registration and deregistration each make at most three attempts, with 250 ms
and 500 ms waits before retries. Each RPC has a three-second timeout. Connection
setup occurs outside that timeout, so these values do not bound the total time
spent in start or stop. A new center connection is created for each attempt.
and 500 ms waits before retries. The shared RPC channel explicitly limits connection
establishment to three seconds, separately from each RPC's three-second deadline.
These are per-attempt budgets, not a three-second total for start/stop. The
transport already had default establishment bounds; the project now sets its
own explicit value. A new center connection is created for each attempt. No
short default deadline is imposed on status/Health subscriptions.
There is no background re-registration or center heartbeat after startup.
The [Registry](../registry/README.md) persists registrations and probes Terminal's
@@ -152,6 +230,10 @@ Terminal and standard Health RPCs share a single ConnectRPC router and Axum
listener. [rpc.rs](src/rpc.rs) adapts generated RPC traits to the domain service;
[callback.rs](src/callback.rs) bridges messages to the host ABI.
[proto::rpc](../proto/README.md) supplies client factories, server hosting,
snapshot streams and Health protocol behavior. Terminal still owns the Tokio
runtime, registration retries, lifecycle mapping and server shutdown timeout.
### Commands
`Execute` requires a ready service, a registered callback and a valid simulation
@@ -258,6 +340,11 @@ For Health, empty service names and `control.Terminal` are known. `Check` report
Streams terminate at shutdown. Health describes readiness, not simulation state,
and does not actively test the host callback or simulation engine.
The shared HealthReporter is the only health-state store. Terminal updates empty
name and `control.Terminal` together; each start constructs a new HealthService
bound to that run's shutdown signal. The common service supports later registration
of an unknown watched name, though Terminal currently registers only these two names.
TLS, authentication, terminal-side persistence, automatic callback cancellation,
automatic re-registration and process signal handling are not implemented here.
The host owns process lifetime and should deploy on a trusted network or use an
@@ -271,21 +358,38 @@ appropriately secured transport boundary.
| [src/runtime.rs](src/runtime.rs) | Tokio runtime, TCP binding, RPC hosting, center registration and stop. |
| [src/terminal.rs](src/terminal.rs) | Lifecycle, simulation state, callbacks, event instances and snapshots. |
| [src/rpc.rs](src/rpc.rs) | Terminal RPC adapters and shutdown-aware watch streams. |
| [src/health.rs](src/health.rs) | Standard Health Check/Watch adapters. |
| [src/callback.rs](src/callback.rs) | Host callback invocation and response sink validation. |
| [src/error.rs](src/error.rs) | Business error and event-handle response encoding. |
All test implementations and helpers are under `tests/`. Existing unit and runtime
integration modules are included by [src/lib.rs](src/lib.rs) through `#[cfg(test)]`
and `#[path]`. [tests/unit/mod.rs](tests/unit/mod.rs) declares the FFI, terminal and
Health unit tests. [tests/unit/health.rs](tests/unit/health.rs) uses explicit crate
imports and the crate-visible `TerminalHealth::responses` method; it is not loaded
separately by the production Health module. No public library API is added.
Health unit tests. [tests/unit/health.rs](tests/unit/health.rs) verifies lifecycle
mapping and restart isolation; common protocol semantics are tested in proto.
[src/logging.rs](src/logging.rs) delegates backend construction to flysim-log and
owns the explicit FFI logging lifecycle. Common filtering/retention tests are in
the shared log crate; [tests/integration/logging.rs](tests/integration/logging.rs)
uses isolated child processes for global state and real Terminal runtime logs.
On Windows, [tests/integration/logging_smoke.ps1](tests/integration/logging_smoke.ps1)
loads the actual DLL through a .NET host and verifies its exports, error codes,
one-time initialization, and flushed daily log file. Run it in a fresh PowerShell
7 process because installed module-wide logging cannot be initialized again:
```powershell
cargo build -p terminal
pwsh -NoProfile -File terminal/tests/integration/logging_smoke.ps1
```
The script keeps the DLL loaded until the host exits and removes only its own
temporary log directory. It does not start a terminal or contact a center.
```powershell
cargo test -p terminal
cargo test -p terminal --lib unit_tests::health
cargo test -p terminal --lib integration_tests::runtime
cargo test -p terminal logging
cargo test -p registry --lib integration_tests::runtime
```
+1 -1
View File
@@ -1,7 +1,7 @@
use std::ffi::c_void;
use buffa::Message;
use proto::proto::control::{Command, InvokeResponse, TerminalEvent};
use proto::control::{Command, InvokeResponse, TerminalEvent};
use crate::error::TerminalError;
+1 -1
View File
@@ -1,6 +1,6 @@
use buffa::MessageField;
use buffa_types::google::protobuf::{Any, StringValue};
use proto::proto::control::{InvokeResponse, TerminalEventHandle};
use proto::control::{InvokeResponse, TerminalEventHandle};
#[derive(Debug, Clone)]
pub(crate) struct TerminalError {
+32 -1
View File
@@ -4,7 +4,7 @@ use std::ptr;
use std::sync::Mutex;
use buffa::Message;
use proto::proto::control::{
use proto::control::{
InvokeResponse, TerminalEventHandle, TerminalEventInfo, TerminalInfo, TerminalStatus,
};
@@ -55,6 +55,37 @@ pub extern "C" fn terminal_service_create() -> *mut c_void {
Box::into_raw(Box::new(ServiceHandle::new())).cast::<c_void>()
}
/// Initializes module-wide console and daily rolling file logging once, before starting terminals.
/// `handle` is used only for error reporting. Does not replace an existing logger/subscriber.
/// # Safety
/// `handle` must be live; both non-null input pointers must reference their declared readable
/// UTF-8 byte lengths. Serialize logging initialization with other process logging setup.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_logging_init(
handle: *mut c_void,
log_level: *const u8,
log_level_len: usize,
log_dir: *const u8,
log_dir_len: usize,
max_log_files: u32,
) -> i32 {
ffi_call(handle, |_| {
let level = unsafe { input_str(log_level, log_level_len)? };
let directory = unsafe { input_str(log_dir, log_dir_len)? };
crate::logging::init(level, directory, max_log_files)
})
}
/// Flushes and closes the module-owned log worker. Repeated shutdown is harmless.
/// Does not uninstall global logging or permit reinitialization after shutdown.
/// # Safety
/// `handle` must be live. Stop all terminals and callbacks first, serialize logging lifecycle
/// calls, and keep the library loaded until process exit. Do not call from a callback.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn terminal_logging_shutdown(handle: *mut c_void) -> i32 {
ffi_call(handle, |_| crate::logging::shutdown())
}
/// # Safety
/// `handle` must be a live pointer returned by `terminal_service_create` and must not be used
/// after this function succeeds.
-67
View File
@@ -1,67 +0,0 @@
use connectrpc::{
ConnectError, ErrorCode, RequestContext, Response, ServiceRequest, ServiceResult, ServiceStream,
};
use futures_util::{StreamExt, stream};
use proto::proto::grpc::health::v1::{
Health, HealthCheckRequest, HealthCheckResponse, health_check_response::ServingStatus,
};
use crate::{rpc::watch_stream, terminal::Service};
pub(crate) struct TerminalHealth(pub(crate) Service);
fn known_service(name: &str) -> bool {
name.is_empty() || name == "control.Terminal"
}
impl TerminalHealth {
pub(crate) fn responses(
&self,
name: &str,
) -> futures_util::stream::BoxStream<'static, Result<HealthCheckResponse, ConnectError>> {
if known_service(name) {
return watch_stream(self.0.health_receiver(), self.0.shutdown_receiver()).boxed();
}
let mut shutdown = self.0.shutdown_receiver();
stream::once(async {
Ok(HealthCheckResponse {
status: ServingStatus::SERVICE_UNKNOWN.into(),
..Default::default()
})
})
.chain(stream::pending())
.take_until(async move {
if *shutdown.borrow() {
return;
}
while shutdown.changed().await.is_ok() {
if *shutdown.borrow() {
return;
}
}
})
.boxed()
}
}
#[allow(refining_impl_trait)]
impl Health for TerminalHealth {
async fn check(
&self,
_context: RequestContext,
request: ServiceRequest<'_, HealthCheckRequest>,
) -> ServiceResult<HealthCheckResponse> {
if !known_service(&request.to_owned_message().service) {
return Err(ConnectError::new(ErrorCode::NotFound, "unknown service"));
}
Response::ok(self.0.health_receiver().borrow().clone())
}
async fn watch(
&self,
_context: RequestContext,
request: ServiceRequest<'_, HealthCheckRequest>,
) -> ServiceResult<ServiceStream<HealthCheckResponse>> {
Response::stream_ok(self.responses(&request.to_owned_message().service))
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
mod callback;
mod error;
mod health;
mod logging;
mod rpc;
mod runtime;
+81
View File
@@ -0,0 +1,81 @@
use std::sync::Mutex;
use flysim_log::{LoggingConfig, LoggingError, LoggingGuard};
use crate::error::TerminalError;
enum LoggingState {
Uninitialized,
Active(LoggingGuard),
Closed,
}
static LOGGING: Mutex<LoggingState> = Mutex::new(LoggingState::Uninitialized);
pub(crate) fn init(level: &str, directory: &str, max_files: u32) -> Result<(), TerminalError> {
let mut state = LOGGING
.lock()
.map_err(|_| TerminalError::new("INTERNAL", "logging state lock is poisoned"))?;
if !matches!(*state, LoggingState::Uninitialized) {
return Err(TerminalError::new(
"INVALID_STATE",
"logging can only be initialized once",
));
}
if tracing::dispatcher::get_default(|subscriber| {
!subscriber.is::<tracing::subscriber::NoSubscriber>()
}) {
return Err(TerminalError::new(
"INVALID_STATE",
"a tracing subscriber is already installed",
));
}
let max_files = usize::try_from(max_files)
.map_err(|_| TerminalError::new("INVALID_ARGUMENT", "log file count is too large"))?;
let config = LoggingConfig {
level: flysim_log::parse_level(level).map_err(map_error)?,
directory: directory.into(),
file_prefix: "terminal".into(),
max_files,
};
let (subscriber, guard) = flysim_log::build_subscriber(&config).map_err(map_error)?;
flysim_log::install_log_bridge().map_err(map_error)?;
if let Err(error) = flysim_log::install_subscriber(subscriber) {
*state = LoggingState::Closed;
return Err(TerminalError::new(
"INVALID_STATE",
format!("subscriber installation failed after log bridge installation: {error}"),
));
}
*state = LoggingState::Active(guard);
drop(state);
log::info!("terminal logging initialized directory={directory} max_files={max_files}");
Ok(())
}
pub(crate) fn shutdown() -> Result<(), TerminalError> {
let guard = {
let mut state = LOGGING
.lock()
.map_err(|_| TerminalError::new("INTERNAL", "logging state lock is poisoned"))?;
if !matches!(*state, LoggingState::Active(_)) {
return Ok(());
}
match std::mem::replace(&mut *state, LoggingState::Closed) {
LoggingState::Active(guard) => guard,
_ => unreachable!(),
}
};
log::info!("terminal logging shutdown");
drop(guard);
Ok(())
}
fn map_error(error: LoggingError) -> TerminalError {
let code = match error {
LoggingError::InvalidConfig(_) => "INVALID_ARGUMENT",
LoggingError::Appender(_) => "INTERNAL",
_ => "INVALID_STATE",
};
TerminalError::new(code, error.to_string())
}
+3 -45
View File
@@ -1,13 +1,10 @@
use buffa_types::google::protobuf::Empty;
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::{
Command, InvokeResponse, Terminal, TerminalCancelEvent, TerminalEvent, TerminalMetaStatus,
TerminalStatus,
};
use tokio::sync::watch;
use proto::rpc::stream::watch_stream;
use crate::terminal::Service;
@@ -59,42 +56,3 @@ impl Terminal for Service {
))
}
}
pub(crate) fn watch_stream<T>(
receiver: watch::Receiver<T>,
shutdown: watch::Receiver<bool>,
) -> impl Stream<Item = Result<T, ConnectError>> + Send
where
T: Clone + Send + Sync + 'static,
{
stream::unfold(
(receiver, shutdown, true),
|(mut receiver, mut shutdown, initial)| async move {
if *shutdown.borrow() {
return None;
}
if initial {
let item = receiver.borrow_and_update().clone();
return Some((Ok(item), (receiver, shutdown, false)));
}
loop {
tokio::select! {
biased;
changed = shutdown.changed() => {
if changed.is_err() || *shutdown.borrow() {
return None;
}
}
changed = receiver.changed() => {
if changed.is_err() {
return None;
}
let item = receiver.borrow_and_update().clone();
return Some((Ok(item), (receiver, shutdown, false)));
}
}
}
},
)
}
+83 -45
View File
@@ -1,16 +1,18 @@
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use buffa_types::google::protobuf::StringValue;
use connectrpc::Protocol;
use connectrpc::client::{CallOptions, ClientConfig, Http2Connection};
use proto::proto::control::{CenterClient, TerminalInfo};
use proto::control::TerminalInfo;
use proto::rpc::{
Router,
client::{CallOptions, RpcChannel, RpcClientOptions, RpcEndpoint},
health::HealthService,
server,
};
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use crate::error::TerminalError;
use crate::health::TerminalHealth;
use crate::terminal::Service;
const CENTER_ATTEMPTS: usize = 3;
@@ -40,6 +42,7 @@ impl RunningServer {
}
let info = service.registration_info()?;
let runtime = Runtime::new().map_err(|error| {
log::error!("terminal runtime creation failed error={error}");
TerminalError::new("START_FAILED", format!("failed to create runtime: {error}"))
})?;
service.reset_shutdown()?;
@@ -56,6 +59,7 @@ impl RunningServer {
{
Ok(listener) => listener,
Err(error) => {
log::error!("terminal bind failed host={host} port={port} error={error}");
service.set_configured();
return Err(TerminalError::new(
"START_FAILED",
@@ -77,25 +81,34 @@ impl RunningServer {
service.set_configured();
return Err(error);
}
log::info!(
"terminal listening host={host} port={bound_port} center_host={center_host} center_port={center_port}"
);
let rpc = connectrpc::Router::new()
let rpc = Router::new()
.add_service(Arc::new(service.clone()))
.add_service(Arc::new(TerminalHealth(service.clone())));
let app = Router::new().fallback_service(rpc.into_axum_service());
.add_service(Arc::new(HealthService::new(
service.health_reporter(),
service.shutdown_receiver(),
)));
let mut shutdown = service.shutdown_receiver();
let server_task = runtime.spawn(async move {
axum::serve(listener, app)
.with_graceful_shutdown(async move {
log::debug!("terminal server task started port={bound_port}");
let result = server::serve(listener, rpc, async move {
if *shutdown.borrow() {
return;
}
while shutdown.changed().await.is_ok() {
if *shutdown.borrow() {
return;
}
while shutdown.changed().await.is_ok() {
if *shutdown.borrow() {
return;
}
}
})
.await
}
})
.await;
if let Err(error) = &result {
log::error!("terminal server task failed port={bound_port} error={error}");
}
result
});
let register_result = runtime.block_on(register_terminal(
@@ -106,6 +119,10 @@ impl RunningServer {
let terminal_id = match register_result {
Ok(terminal_id) => terminal_id,
Err(error) => {
log::error!(
"terminal registration failed center_host={center_host} center_port={center_port} error={}",
error.display_message()
);
service.signal_shutdown();
runtime.block_on(async {
let _ = tokio::time::timeout(SHUTDOWN_TIMEOUT, server_task).await;
@@ -114,7 +131,8 @@ impl RunningServer {
return Err(error);
}
};
service.set_ready(terminal_id)?;
service.set_ready(terminal_id.clone())?;
log::info!("terminal registered terminal_id={terminal_id} port={bound_port}");
Ok(Self {
runtime,
@@ -132,6 +150,10 @@ impl RunningServer {
pub(crate) fn stop(mut self, service: &Service) -> Result<(), TerminalError> {
service.set_stopping()?;
let terminal_id = service.terminal_id()?;
log::info!(
"terminal stopping terminal_id={terminal_id} port={}",
self.bound_port
);
let deregister_result = self.runtime.block_on(deregister_terminal(
&self.center_host,
self.center_port,
@@ -144,6 +166,11 @@ impl RunningServer {
.runtime
.block_on(async { tokio::time::timeout(SHUTDOWN_TIMEOUT, &mut task).await });
if completed.is_err() {
log::warn!(
"terminal server shutdown timed out port={} timeout_secs={}",
self.bound_port,
SHUTDOWN_TIMEOUT.as_secs()
);
task.abort();
self.runtime.block_on(async {
let _ = task.await;
@@ -151,6 +178,13 @@ impl RunningServer {
}
}
service.set_stopped();
if let Err(error) = &deregister_result {
log::warn!(
"terminal deregistration failed after retries error={}",
error.display_message()
);
}
log::info!("terminal stopped port={}", self.bound_port);
deregister_result
}
}
@@ -160,17 +194,12 @@ async fn register_terminal(
center_port: u16,
info: TerminalInfo,
) -> Result<String, TerminalError> {
let uri = center_uri(center_host, center_port)?;
let endpoint = center_endpoint(center_host, center_port)?;
let mut last_error = String::new();
for attempt in 0..CENTER_ATTEMPTS {
match Http2Connection::connect_plaintext(uri.clone()).await {
Ok(connection) => {
let client = CenterClient::new(
connection.shared(1024),
ClientConfig::new(uri.clone())
.with_protocol(Protocol::Grpc)
.with_default_timeout(CENTER_RPC_TIMEOUT),
);
match RpcChannel::connect(&endpoint, center_options()).await {
Ok(channel) => {
let client = channel.center_client();
match client
.register_terminal_with_options(
info.clone(),
@@ -194,6 +223,10 @@ async fn register_terminal(
}
Err(error) => last_error = error.to_string(),
}
log::warn!(
"center request failed operation=register attempt={} center_host={center_host} center_port={center_port} error={last_error}",
attempt + 1
);
if attempt + 1 < CENTER_ATTEMPTS {
tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await;
}
@@ -209,17 +242,12 @@ async fn deregister_terminal(
if terminal_id.is_empty() {
return Ok(());
}
let uri = center_uri(center_host, center_port)?;
let endpoint = center_endpoint(center_host, center_port)?;
let mut last_error = String::new();
for attempt in 0..CENTER_ATTEMPTS {
match Http2Connection::connect_plaintext(uri.clone()).await {
Ok(connection) => {
let client = CenterClient::new(
connection.shared(1024),
ClientConfig::new(uri.clone())
.with_protocol(Protocol::Grpc)
.with_default_timeout(CENTER_RPC_TIMEOUT),
);
match RpcChannel::connect(&endpoint, center_options()).await {
Ok(channel) => {
let client = channel.center_client();
let request = StringValue {
value: terminal_id.clone(),
..Default::default()
@@ -243,6 +271,10 @@ async fn deregister_terminal(
}
Err(error) => last_error = error.to_string(),
}
log::warn!(
"center request failed operation=deregister attempt={} center_host={center_host} center_port={center_port} terminal_id={terminal_id} error={last_error}",
attempt + 1
);
if attempt + 1 < CENTER_ATTEMPTS {
tokio::time::sleep(CENTER_RETRY_DELAY * (attempt as u32 + 1)).await;
}
@@ -250,13 +282,19 @@ async fn deregister_terminal(
Err(TerminalError::new("DEREGISTER_FAILED", last_error))
}
fn center_uri(center_host: &str, center_port: u16) -> Result<axum::http::Uri, TerminalError> {
format!("http://{center_host}:{center_port}")
.parse()
.map_err(|error| {
TerminalError::new(
"INVALID_ARGUMENT",
format!("invalid center address: {error}"),
)
})
fn center_endpoint(center_host: &str, center_port: u16) -> Result<RpcEndpoint, TerminalError> {
RpcEndpoint::from_host_port(center_host, center_port).map_err(|error| {
TerminalError::new(
"INVALID_ARGUMENT",
format!("invalid center address: {error}"),
)
})
}
fn center_options() -> RpcClientOptions {
RpcClientOptions {
connect_timeout: CENTER_RPC_TIMEOUT,
request_timeout: None,
buffer_capacity: 1024,
}
}
+16 -16
View File
@@ -2,11 +2,11 @@ use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use proto::proto::control::{
use proto::control::{
Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle,
TerminalEventInfo, TerminalInfo, TerminalMetaStatus, TerminalStatus,
};
use proto::proto::grpc::health::v1::{HealthCheckResponse, health_check_response::ServingStatus};
use proto::rpc::health::{HealthReporter, ServingStatus};
use tokio::sync::watch;
use crate::callback::{CommandCallback, EventCallback};
@@ -67,7 +67,7 @@ struct Inner {
callback_gate: Arc<Mutex<()>>,
status: watch::Sender<TerminalStatus>,
meta_status: watch::Sender<TerminalMetaStatus>,
health: watch::Sender<HealthCheckResponse>,
health: HealthReporter,
shutdown: Mutex<watch::Sender<bool>>,
}
@@ -91,10 +91,13 @@ impl Service {
let (status, _) = watch::channel(TerminalStatus::default());
let (meta_status, _) = watch::channel(TerminalMetaStatus::default());
let (shutdown, _) = watch::channel(false);
let (health, _) = watch::channel(HealthCheckResponse {
status: ServingStatus::NOT_SERVING.into(),
..Default::default()
});
let health = HealthReporter::new();
health
.set_statuses(&[
("", ServingStatus::NOT_SERVING),
("control.Terminal", ServingStatus::NOT_SERVING),
])
.expect("valid initial health statuses");
Self {
inner: Arc::new(Inner {
context: Mutex::new(Context {
@@ -342,8 +345,8 @@ impl Service {
.subscribe()
}
pub(crate) fn health_receiver(&self) -> watch::Receiver<HealthCheckResponse> {
self.inner.health.subscribe()
pub(crate) fn health_reporter(&self) -> &HealthReporter {
&self.inner.health
}
fn publish_health(&self, state: ServiceState) {
@@ -352,13 +355,10 @@ impl Service {
} else {
ServingStatus::NOT_SERVING
};
self.inner.health.send_if_modified(|response| {
if response.status == status {
return false;
}
response.status = status.into();
true
});
self.inner
.health
.set_statuses(&[("", status), ("control.Terminal", status)])
.expect("lifecycle maps to valid health statuses");
}
pub(crate) fn reset_shutdown(&self) -> Result<(), TerminalError> {
+23
View File
@@ -40,6 +40,29 @@ typedef int32_t (*TerminalEventCallback)(void *user_data,
void *terminal_service_create(void);
/**
* Initializes module-wide console and daily rolling file logging once, before starting terminals.
* `handle` is used only for error reporting. Does not replace an existing logger/subscriber.
* # Safety
* `handle` must be live; both non-null input pointers must reference their declared readable
* UTF-8 byte lengths. Serialize logging initialization with other process logging setup.
*/
int32_t terminal_logging_init(void *handle,
const uint8_t *log_level,
size_t log_level_len,
const uint8_t *log_dir,
size_t log_dir_len,
uint32_t max_log_files);
/**
* Flushes and closes the module-owned log worker. Repeated shutdown is harmless.
* Does not uninstall global logging or permit reinitialization after shutdown.
* # Safety
* `handle` must be live. Stop all terminals and callbacks first, serialize logging lifecycle
* calls, and keep the library loaded until process exit. Do not call from a callback.
*/
int32_t terminal_logging_shutdown(void *handle);
/**
* # Safety
* `handle` must be a live pointer returned by `terminal_service_create` and must not be used
+193
View File
@@ -0,0 +1,193 @@
use std::ffi::c_void;
use std::process::Command;
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::ffi::*;
static EXTERNAL_LOG_COUNT: AtomicUsize = AtomicUsize::new(0);
struct ExternalLogger;
impl log::Log for ExternalLogger {
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
true
}
fn log(&self, _: &log::Record<'_>) {
EXTERNAL_LOG_COUNT.fetch_add(1, Ordering::Relaxed);
}
fn flush(&self) {}
}
fn initialize(handle: *mut c_void, level: &[u8], directory: &[u8], count: u32) -> i32 {
unsafe {
terminal_logging_init(
handle,
level.as_ptr(),
level.len(),
directory.as_ptr(),
directory.len(),
count,
)
}
}
fn last_error(handle: *mut c_void) -> String {
let mut length = 0;
assert_eq!(
unsafe { terminal_service_last_error(handle, ptr::null_mut(), &mut length) },
TERMINAL_OK
);
let mut bytes = vec![0; length];
assert_eq!(
unsafe { terminal_service_last_error(handle, bytes.as_mut_ptr(), &mut length) },
TERMINAL_OK
);
String::from_utf8(bytes[..length - 1].to_vec()).unwrap()
}
#[test]
fn explicit_logging_lifecycle_and_conflicts() {
if let Ok(scenario) = std::env::var("TERMINAL_LOG_TEST_SCENARIO") {
let directory = std::env::var("TERMINAL_LOG_TEST_DIRECTORY").unwrap();
let handle = terminal_service_create();
assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK);
match scenario.as_str() {
"lifecycle" => {
for (level, path, count) in [
(&b""[..], directory.as_bytes(), 10),
(&b"invalid"[..], directory.as_bytes(), 10),
(&[0xff][..], directory.as_bytes(), 10),
(&b"info"[..], &b""[..], 10),
(&b"info"[..], &[0xff][..], 10),
(&b"info"[..], directory.as_bytes(), 0),
] {
assert_eq!(
initialize(handle, level, path, count),
TERMINAL_ERROR_INVALID_ARGUMENT
);
assert!(last_error(handle).starts_with("INVALID_ARGUMENT:"));
}
assert_eq!(
unsafe {
terminal_logging_init(
handle,
ptr::null(),
0,
directory.as_ptr(),
directory.len(),
10,
)
},
TERMINAL_ERROR_INVALID_ARGUMENT
);
let invalid_path = std::path::Path::new(&directory).join("ordinary-file");
std::fs::write(&invalid_path, b"keep").unwrap();
assert_eq!(
initialize(
handle,
b"info",
invalid_path.to_str().unwrap().as_bytes(),
10
),
TERMINAL_ERROR_INTERNAL
);
assert_eq!(
initialize(handle, b"debug", directory.as_bytes(), 10),
TERMINAL_OK
);
assert_eq!(
initialize(handle, b"debug", directory.as_bytes(), 10),
TERMINAL_ERROR_INVALID_STATE
);
log::info!(target: "terminal::log_test", "ffi-bridge-visible");
log::trace!("ffi-bridge-hidden");
tracing::info!(target: "terminal::log_test", terminal_id = "test-id", "ffi-structured-visible");
super::runtime::exercise_runtime();
assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK);
assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK);
assert_eq!(
initialize(handle, b"debug", directory.as_bytes(), 10),
TERMINAL_ERROR_INVALID_STATE
);
}
"logger-conflict" => {
log::set_logger(&ExternalLogger).unwrap();
log::set_max_level(log::LevelFilter::Trace);
assert_eq!(
initialize(handle, b"info", directory.as_bytes(), 10),
TERMINAL_ERROR_INVALID_STATE
);
assert!(last_error(handle).contains("logger is already installed"));
log::info!("external-logger-kept");
assert_eq!(EXTERNAL_LOG_COUNT.load(Ordering::Relaxed), 1);
assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK);
log::info!("external-logger-still-kept");
assert_eq!(EXTERNAL_LOG_COUNT.load(Ordering::Relaxed), 2);
}
"subscriber-conflict" => {
tracing::subscriber::set_global_default(
tracing_subscriber::fmt()
.with_writer(std::io::sink)
.finish(),
)
.unwrap();
assert_eq!(
initialize(handle, b"info", directory.as_bytes(), 10),
TERMINAL_ERROR_INVALID_STATE
);
assert!(last_error(handle).contains("subscriber is already installed"));
log::set_logger(&ExternalLogger).unwrap();
log::set_max_level(log::LevelFilter::Info);
assert_eq!(unsafe { terminal_logging_shutdown(handle) }, TERMINAL_OK);
}
_ => panic!("unexpected scenario"),
}
assert_eq!(unsafe { terminal_service_destroy(handle) }, TERMINAL_OK);
return;
}
for scenario in ["lifecycle", "logger-conflict", "subscriber-conflict"] {
let directory = tempfile::tempdir().unwrap();
let output = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"integration_tests::logging::explicit_logging_lifecycle_and_conflicts",
"--nocapture",
])
.env("TERMINAL_LOG_TEST_SCENARIO", scenario)
.env("TERMINAL_LOG_TEST_DIRECTORY", directory.path())
.output()
.unwrap();
assert!(
output.status.success(),
"scenario={scenario}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
if scenario == "lifecycle" {
let console = String::from_utf8(output.stderr).unwrap();
let files = 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!(files.len(), 1);
let text = std::fs::read_to_string(&files[0]).unwrap();
for contents in [&console, &text] {
for message in [
"ffi-bridge-visible",
"ffi-structured-visible",
"terminal registered",
"terminal server task started",
"terminal stopped",
"terminal logging shutdown",
] {
assert_eq!(contents.matches(message).count(), 1, "{contents}");
}
assert!(contents.contains("center-terminal-1"));
assert!(!contents.contains("ffi-bridge-hidden"));
assert!(!contents.contains('\u{1b}'));
}
}
}
}
@@ -0,0 +1,89 @@
param(
[string] $LibraryPath = (Join-Path $PSScriptRoot '../../../target/debug/terminal.dll')
)
$ErrorActionPreference = 'Stop'
$library = (Resolve-Path $LibraryPath).Path
$directory = Join-Path ([System.IO.Path]::GetTempPath()) ('terminal-logging-smoke-' + [guid]::NewGuid())
[System.IO.Directory]::CreateDirectory($directory) | Out-Null
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
using System.Text;
public static class TerminalLoggingSmokeHost
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr Create();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int HandleOperation(IntPtr handle);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int Initialize(IntPtr handle, byte[] level, UIntPtr levelLength,
byte[] directory, UIntPtr directoryLength, uint maxFiles);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int LastError(IntPtr handle, byte[] buffer, ref UIntPtr length);
private static void Expect(int actual, int expected, string operation)
{
if (actual != expected)
throw new InvalidOperationException(operation + ": expected " + expected + ", got " + actual);
}
public static void Run(string libraryPath, string directory)
{
IntPtr library = NativeLibrary.Load(libraryPath);
var create = Marshal.GetDelegateForFunctionPointer<Create>(NativeLibrary.GetExport(library, "terminal_service_create"));
var destroy = Marshal.GetDelegateForFunctionPointer<HandleOperation>(NativeLibrary.GetExport(library, "terminal_service_destroy"));
var initialize = Marshal.GetDelegateForFunctionPointer<Initialize>(NativeLibrary.GetExport(library, "terminal_logging_init"));
var shutdown = Marshal.GetDelegateForFunctionPointer<HandleOperation>(NativeLibrary.GetExport(library, "terminal_logging_shutdown"));
var lastError = Marshal.GetDelegateForFunctionPointer<LastError>(NativeLibrary.GetExport(library, "terminal_service_last_error"));
byte[] path = Encoding.UTF8.GetBytes(directory);
byte[] level = Encoding.UTF8.GetBytes("info");
byte[] invalid = Encoding.UTF8.GetBytes("invalid");
IntPtr handle = create();
if (handle == IntPtr.Zero) throw new InvalidOperationException("create returned null");
try
{
Expect(shutdown(IntPtr.Zero), -1, "null handle");
Expect(shutdown(handle), 0, "shutdown before init");
Expect(initialize(handle, invalid, (UIntPtr)invalid.Length, path, (UIntPtr)path.Length, 10), -2, "invalid level");
UIntPtr length = UIntPtr.Zero;
Expect(lastError(handle, null, ref length), 0, "last_error size");
byte[] error = new byte[checked((int)length.ToUInt64())];
Expect(lastError(handle, error, ref length), 0, "last_error text");
if (!Encoding.UTF8.GetString(error).StartsWith("INVALID_ARGUMENT:"))
throw new InvalidOperationException("unexpected last_error");
Expect(initialize(handle, level, (UIntPtr)level.Length, path, (UIntPtr)path.Length, 10), 0, "initialize");
Expect(initialize(handle, level, (UIntPtr)level.Length, path, (UIntPtr)path.Length, 10), -3, "duplicate initialize");
Expect(shutdown(handle), 0, "shutdown");
Expect(shutdown(handle), 0, "repeat shutdown");
Expect(initialize(handle, level, (UIntPtr)level.Length, path, (UIntPtr)path.Length, 10), -3, "initialize after shutdown");
}
finally
{
Expect(shutdown(handle), 0, "final shutdown");
Expect(destroy(handle), 0, "destroy");
}
}
}
'@
try {
[TerminalLoggingSmokeHost]::Run($library, $directory)
$files = @(Get-ChildItem -LiteralPath $directory -Filter 'terminal.*.log' -File)
if ($files.Count -ne 1) { throw "Expected one daily log file, got $($files.Count)" }
$contents = [System.IO.File]::ReadAllText($files[0].FullName)
foreach ($message in @('terminal logging initialized', 'terminal logging shutdown')) {
if ([regex]::Matches($contents, [regex]::Escape($message)).Count -ne 1) {
throw "Expected exactly one '$message' record in the flushed log"
}
}
if ($contents.Contains([char]27)) { throw 'File output contains ANSI escape characters' }
Write-Output "PASS: DLL exports, error codes, one-time initialization and shutdown flush ($($files[0].Name))"
} finally {
Remove-Item -LiteralPath $directory -Recurse -Force
}
+1
View File
@@ -1 +1,2 @@
mod logging;
mod runtime;
+43 -23
View File
@@ -1,20 +1,18 @@
use std::sync::atomic::{AtomicUsize, Ordering};
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,
ConnectError, 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 proto::control::{
Center, Command, InvokeResponse, TerminalInfo, TerminalInfos, TerminalRegisterResponse,
};
use proto::grpc::health::v1::{HealthCheckRequest, health_check_response::ServingStatus};
use proto::rpc::client::{RpcChannel, RpcClientOptions, RpcEndpoint};
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
@@ -27,6 +25,9 @@ const CENTER_ASSIGNED_ID: &str = "center-terminal-1";
struct FakeCenter {
registered: Mutex<Option<TerminalInfo>>,
deregistered_id: Mutex<Option<String>>,
failures: usize,
registrations: AtomicUsize,
deregistrations: AtomicUsize,
}
#[allow(refining_impl_trait)]
@@ -38,7 +39,7 @@ impl Center for FakeCenter {
) -> ServiceResult<TerminalRegisterResponse> {
*self.registered.lock().unwrap() = Some(request.to_owned_message());
Response::ok(TerminalRegisterResponse {
success: true,
success: self.registrations.fetch_add(1, Ordering::Relaxed) >= self.failures,
message: CENTER_ASSIGNED_ID.to_owned(),
..Default::default()
})
@@ -51,7 +52,7 @@ impl Center for FakeCenter {
) -> ServiceResult<InvokeResponse> {
*self.deregistered_id.lock().unwrap() = Some(request.to_owned_message().value);
Response::ok(InvokeResponse {
success: true,
success: self.deregistrations.fetch_add(1, Ordering::Relaxed) >= self.failures,
..Default::default()
})
}
@@ -67,7 +68,23 @@ impl Center for FakeCenter {
#[test]
fn start_registers_actual_port_and_stop_deregisters_same_id() {
let center = Arc::new(FakeCenter::default());
exercise_runtime();
}
pub(super) fn exercise_runtime() {
exercise_runtime_with_failures(0);
}
#[test]
fn registration_and_deregistration_retries_survive_transport_refactor() {
exercise_runtime_with_failures(2);
}
fn exercise_runtime_with_failures(failures: usize) {
let center = Arc::new(FakeCenter {
failures,
..Default::default()
});
let center_runtime = Runtime::new().unwrap();
let listener = center_runtime
.block_on(tokio::net::TcpListener::bind(("127.0.0.1", 0)))
@@ -107,18 +124,19 @@ fn start_registers_actual_port_and_stop_deregisters_same_id() {
CENTER_ASSIGNED_ID
);
let terminal_uri: axum::http::Uri = format!("http://127.0.0.1:{}", server.bound_port())
.parse()
.unwrap();
let endpoint = RpcEndpoint::from_host_port("127.0.0.1", server.bound_port()).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());
let channel = RpcChannel::connect(
&endpoint,
RpcClientOptions {
request_timeout: Some(Duration::from_secs(2)),
buffer_capacity: 32,
..Default::default()
},
)
.await
.unwrap();
let health = channel.health_client();
for name in ["", "control.Terminal"] {
let response = health
.check(HealthCheckRequest {
@@ -168,7 +186,7 @@ fn start_registers_actual_port_and_stop_deregisters_same_id() {
ServingStatus::SERVICE_UNKNOWN
);
drop(watcher);
let client = TerminalClient::new(connection, config);
let client = channel.terminal_client();
let response = client
.execute(Command {
id: "not-registered".to_owned(),
@@ -181,6 +199,8 @@ fn start_registers_actual_port_and_stop_deregisters_same_id() {
});
server.stop(&service).unwrap();
assert_eq!(center.registrations.load(Ordering::Relaxed), failures + 1);
assert_eq!(center.deregistrations.load(Ordering::Relaxed), failures + 1);
assert_eq!(
center.deregistered_id.lock().unwrap().as_deref(),
Some(CENTER_ASSIGNED_ID)
+87 -79
View File
@@ -1,79 +1,87 @@
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);
}
use std::ptr;
use buffa::Message;
use proto::control::TerminalInfo;
use crate::ffi::*;
#[test]
fn null_handles_are_rejected() {
assert_eq!(
unsafe { terminal_logging_init(ptr::null_mut(), ptr::null(), 0, ptr::null(), 0, 10) },
TERMINAL_ERROR_NULL
);
assert_eq!(
unsafe { terminal_logging_shutdown(ptr::null_mut()) },
TERMINAL_ERROR_NULL
);
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);
}
+125 -67
View File
@@ -1,67 +1,125 @@
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());
}
use crate::terminal::Service;
use proto::control::TerminalInfo;
use proto::grpc::health::v1::HealthCheckRequest;
use proto::rpc::{
Router,
client::{HealthRpcClient, RpcChannel, RpcClientOptions, RpcEndpoint},
health::{HealthService, ServingStatus},
server,
};
use std::{sync::Arc, time::Duration};
fn assert_status(service: &Service, status: ServingStatus) {
for name in ["", "control.Terminal"] {
assert_eq!(service.health_reporter().status(name), Some(status));
}
}
#[test]
fn lifecycle_health_mapping() {
let service = Service::new_value();
assert_status(&service, 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_status(&service, ServingStatus::NOT_SERVING);
service.set_ready("id".into()).unwrap();
assert_status(&service, ServingStatus::SERVING);
service.set_stopping().unwrap();
assert_status(&service, ServingStatus::NOT_SERVING);
service.set_stopped();
service.set_starting().unwrap();
service.set_configured();
assert_status(&service, ServingStatus::NOT_SERVING);
}
async fn serve_health(
service: &Service,
) -> (
HealthRpcClient,
tokio::task::JoinHandle<std::io::Result<()>>,
) {
let listener = tokio::net::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 mut shutdown = service.shutdown_receiver();
let router = Router::new().add_service(Arc::new(HealthService::new(
service.health_reporter(),
shutdown.clone(),
)));
let task = tokio::spawn(server::serve(listener, router, async move {
let _ = shutdown.wait_for(|stopped| *stopped).await;
}));
let channel = RpcChannel::connect(&endpoint, RpcClientOptions::default())
.await
.unwrap();
(channel.health_client(), task)
}
#[tokio::test]
async fn restart_uses_new_shutdown_channel() {
tokio::time::timeout(Duration::from_secs(5), async {
let service = Service::new_value();
service
.configure(TerminalInfo {
terminal_host: "127.0.0.1".into(),
terminal_mac: "test".into(),
..Default::default()
})
.unwrap();
service.set_starting().unwrap();
service.set_ready("first".into()).unwrap();
let (client, task) = serve_health(&service).await;
let mut first = client.watch(HealthCheckRequest::default()).await.unwrap();
assert_eq!(
first
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVING
);
service.signal_shutdown();
assert!(first.message().await.unwrap().is_none());
task.await.unwrap().unwrap();
service.set_stopped();
service.reset_shutdown().unwrap();
service.set_starting().unwrap();
let (client, task) = serve_health(&service).await;
let mut second = client.watch(HealthCheckRequest::default()).await.unwrap();
assert_eq!(
second
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::NOT_SERVING
);
service.set_ready("second".into()).unwrap();
assert_eq!(
second
.message()
.await
.unwrap()
.unwrap()
.to_owned_message()
.status,
ServingStatus::SERVING
);
assert!(first.message().await.unwrap().is_none());
service.signal_shutdown();
assert!(second.message().await.unwrap().is_none());
task.await.unwrap().unwrap();
})
.await
.unwrap();
}
+1 -1
View File
@@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use buffa::Message;
use proto::proto::control::{
use proto::control::{
Command, InvokeResponse, TerminalCancelEvent, TerminalEvent, TerminalEventHandle,
TerminalEventInfo, TerminalInfo, TerminalStatus,
};