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
+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,
};