Files
lain bbb67a68ab 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.
2026-10-09 15:57:35 +08:00

194 lines
7.6 KiB
Rust

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}'));
}
}
}
}