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:
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "flysim-log"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
log.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-log.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
tracing-appender.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,87 @@
|
||||
# FlySim Log
|
||||
|
||||
`flysim-log` is the shared logging infrastructure crate in the `log/` workspace
|
||||
directory. Import it as `flysim_log`; keep using the third-party `log` crate's
|
||||
`log::info!`, `warn!` and `error!` macros for business records.
|
||||
|
||||
It has no dependency on `proto`, Registry or Terminal, reads no environment
|
||||
variables, and performs no initialization merely by being linked.
|
||||
|
||||
## API And Ownership
|
||||
|
||||
```rust
|
||||
use flysim_log::{LoggingConfig, build_subscriber, install_log_bridge, install_subscriber, parse_level};
|
||||
|
||||
fn initialize() -> Result<flysim_log::LoggingGuard, flysim_log::LoggingError> {
|
||||
let config = LoggingConfig {
|
||||
level: parse_level("info")?,
|
||||
directory: "logs/my-service".into(),
|
||||
file_prefix: "my-service".into(),
|
||||
max_files: 10,
|
||||
};
|
||||
let (subscriber, guard) = build_subscriber(&config)?;
|
||||
install_log_bridge()?;
|
||||
install_subscriber(subscriber)?;
|
||||
Ok(guard)
|
||||
}
|
||||
```
|
||||
|
||||
Keep the returned guard alive until all producers have stopped and the final
|
||||
record has been emitted. Dropping it drains the file worker during normal exit;
|
||||
it does not uninstall global logging. Do not use `process::exit` to bypass it.
|
||||
|
||||
- `LoggingConfig` selects level, directory, filename prefix and retention count.
|
||||
Levels are `off/error/warn/info/debug/trace` (case-insensitive when parsed).
|
||||
The directory/prefix must be nonempty, the count positive, and the prefix a
|
||||
portable single filename component rather than a path.
|
||||
- `build_subscriber` constructs a `tracing::Dispatch` and `LoggingGuard` without
|
||||
installing globals. `build_with_writer` permits an injected console writer
|
||||
for scoped tests or embedding.
|
||||
- `install_log_bridge` installs `tracing-log::LogTracer` for `log` records;
|
||||
`install_subscriber` installs the prepared tracing subscriber. Native tracing
|
||||
fields and spans are supported as well. Do not also initialize `env_logger`.
|
||||
- `stderr_subscriber` constructs a temporary console-only dispatcher. Registry
|
||||
uses it after bridge installation to report failures before file logging is
|
||||
ready. The caller supplies the contextual message and exit policy.
|
||||
- `LoggingError` distinguishes invalid configuration, appender failure and
|
||||
already-installed globals, preserving backend error sources. Components map
|
||||
these errors into their own public/FFI error models.
|
||||
|
||||
The two global installations are not an atomic operation and cannot be rolled
|
||||
back. Serialize initialization with other host logging setup. A failed second
|
||||
installation can leave the first global installed; drop the new guard on failure,
|
||||
report the conflict, and never silently replace an existing logger/subscriber.
|
||||
|
||||
## Output Contract
|
||||
|
||||
Each record is written to stderr and a daily UTC file named
|
||||
`<prefix>.YYYY-MM-DD.log`. Both include timestamp, level and target; files never
|
||||
contain ANSI codes. The default console writer detects terminal color support.
|
||||
The chosen level filters both outputs.
|
||||
|
||||
Retention removes old matching prefix/suffix files at initialization or rotation.
|
||||
`max_files` is an upper bound, not an exact count or a number of days. Use a
|
||||
dedicated directory per process. Daily rotation does not limit individual file
|
||||
size and is driven by arriving records rather than an idle timer.
|
||||
|
||||
File output uses an 8192-entry bounded queue with `lossy(false)`. Full queues
|
||||
block producers; stderr is synchronous. Slow output can delay RPC or host
|
||||
threads. Guard cleanup is not a durability guarantee against forced exit, disk
|
||||
failure, a stalled writer or power loss.
|
||||
|
||||
Registry retains the guard in its process entry point. Terminal retains it in
|
||||
its FFI lifecycle state until explicit logging shutdown. Extracting this crate
|
||||
does not make independently linked DLLs share Rust globals; keep a DLL that
|
||||
installed global logging loaded until host process exit.
|
||||
|
||||
## Tests
|
||||
|
||||
Tests live under [tests/unit](tests/unit) and are loaded by the library's test-only
|
||||
entry. They cover configuration, filtering, retention, append/flush and queue
|
||||
backpressure. Registry keeps the end-to-end `log` bridge/dual-output test;
|
||||
Terminal keeps isolated initialization-conflict and real DLL ABI tests.
|
||||
|
||||
```powershell
|
||||
cargo test -p flysim-log
|
||||
cargo test -p registry -p terminal logging
|
||||
```
|
||||
@@ -0,0 +1,43 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::LoggingError;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LoggingConfig {
|
||||
pub level: log::LevelFilter,
|
||||
pub directory: PathBuf,
|
||||
pub file_prefix: String,
|
||||
pub max_files: usize,
|
||||
}
|
||||
|
||||
impl LoggingConfig {
|
||||
pub fn validate(&self) -> Result<(), LoggingError> {
|
||||
if self.directory.as_os_str().is_empty() || self.max_files == 0 {
|
||||
return Err(LoggingError::InvalidConfig(
|
||||
"log directory must be nonempty and file count positive",
|
||||
));
|
||||
}
|
||||
if self.file_prefix.trim().is_empty()
|
||||
|| self.file_prefix == "."
|
||||
|| self.file_prefix == ".."
|
||||
|| self
|
||||
.file_prefix
|
||||
.chars()
|
||||
.any(|character| character.is_control() || "/\\:*?\"<>|".contains(character))
|
||||
{
|
||||
return Err(LoggingError::InvalidConfig(
|
||||
"log prefix must be a nonempty portable filename component",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_level(value: &str) -> Result<log::LevelFilter, LoggingError> {
|
||||
if value.trim().is_empty() {
|
||||
return Err(LoggingError::InvalidConfig("log level must not be empty"));
|
||||
}
|
||||
value.trim().parse().map_err(|_| {
|
||||
LoggingError::InvalidConfig("log level must be off, error, warn, info, debug or trace")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LoggingError {
|
||||
InvalidConfig(&'static str),
|
||||
Appender(tracing_appender::rolling::InitError),
|
||||
BridgeAlreadyInstalled(log::SetLoggerError),
|
||||
SubscriberAlreadyInstalled(tracing::dispatcher::SetGlobalDefaultError),
|
||||
}
|
||||
|
||||
impl fmt::Display for LoggingError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidConfig(message) => formatter.write_str(message),
|
||||
Self::Appender(error) => {
|
||||
write!(formatter, "failed to initialize file logging: {error}")
|
||||
}
|
||||
Self::BridgeAlreadyInstalled(error) => {
|
||||
write!(formatter, "a log logger is already installed: {error}")
|
||||
}
|
||||
Self::SubscriberAlreadyInstalled(error) => write!(
|
||||
formatter,
|
||||
"a tracing subscriber is already installed: {error}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LoggingError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
Self::InvalidConfig(_) => None,
|
||||
Self::Appender(error) => Some(error),
|
||||
Self::BridgeAlreadyInstalled(error) => Some(error),
|
||||
Self::SubscriberAlreadyInstalled(error) => Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
mod config;
|
||||
mod error;
|
||||
|
||||
use std::io::{self, IsTerminal};
|
||||
|
||||
use tracing::Dispatch;
|
||||
use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};
|
||||
use tracing_appender::rolling::{RollingFileAppender, Rotation};
|
||||
use tracing_log::AsTrace;
|
||||
use tracing_subscriber::{fmt::MakeWriter, prelude::*};
|
||||
|
||||
pub use config::{LoggingConfig, parse_level};
|
||||
pub use error::LoggingError;
|
||||
|
||||
#[must_use = "keep this guard alive until all logging has finished"]
|
||||
pub struct LoggingGuard {
|
||||
_worker: WorkerGuard,
|
||||
}
|
||||
|
||||
pub fn install_log_bridge() -> Result<(), LoggingError> {
|
||||
tracing_log::LogTracer::init().map_err(LoggingError::BridgeAlreadyInstalled)
|
||||
}
|
||||
|
||||
pub fn install_subscriber(subscriber: Dispatch) -> Result<(), LoggingError> {
|
||||
tracing::dispatcher::set_global_default(subscriber)
|
||||
.map_err(LoggingError::SubscriberAlreadyInstalled)
|
||||
}
|
||||
|
||||
pub fn stderr_subscriber() -> Dispatch {
|
||||
Dispatch::new(
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(io::stderr)
|
||||
.with_ansi(io::stderr().is_terminal())
|
||||
.finish(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn build_subscriber(config: &LoggingConfig) -> Result<(Dispatch, LoggingGuard), LoggingError> {
|
||||
build_with_writer(config, io::stderr, io::stderr().is_terminal())
|
||||
}
|
||||
|
||||
pub fn build_with_writer<W>(
|
||||
config: &LoggingConfig,
|
||||
console: W,
|
||||
ansi: bool,
|
||||
) -> Result<(Dispatch, LoggingGuard), LoggingError>
|
||||
where
|
||||
W: for<'writer> MakeWriter<'writer> + Send + Sync + 'static,
|
||||
{
|
||||
config.validate()?;
|
||||
let appender = RollingFileAppender::builder()
|
||||
.rotation(Rotation::DAILY)
|
||||
.filename_prefix(&config.file_prefix)
|
||||
.filename_suffix("log")
|
||||
.max_log_files(config.max_files)
|
||||
.build(&config.directory)
|
||||
.map_err(LoggingError::Appender)?;
|
||||
let (writer, guard) = file_writer(
|
||||
appender,
|
||||
8192,
|
||||
&format!("{}-log-writer", config.file_prefix),
|
||||
);
|
||||
let subscriber = tracing_subscriber::registry()
|
||||
.with(config.level.as_trace())
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_ansi(ansi)
|
||||
.with_writer(console),
|
||||
)
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_ansi(false)
|
||||
.with_writer(writer),
|
||||
);
|
||||
Ok((Dispatch::new(subscriber), guard))
|
||||
}
|
||||
|
||||
pub(crate) fn file_writer<W: io::Write + Send + 'static>(
|
||||
writer: W,
|
||||
capacity: usize,
|
||||
thread_name: &str,
|
||||
) -> (NonBlocking, LoggingGuard) {
|
||||
let (writer, worker) = tracing_appender::non_blocking::NonBlockingBuilder::default()
|
||||
.buffered_lines_limit(capacity)
|
||||
.lossy(false)
|
||||
.thread_name(thread_name)
|
||||
.finish(writer);
|
||||
(writer, LoggingGuard { _worker: worker })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/unit/mod.rs"]
|
||||
mod unit_tests;
|
||||
@@ -0,0 +1,160 @@
|
||||
use crate::{LoggingConfig, build_with_writer, parse_level};
|
||||
use std::{io, path::Path};
|
||||
|
||||
fn config(directory: &Path, level: &str, max_files: usize) -> LoggingConfig {
|
||||
LoggingConfig {
|
||||
level: parse_level(level).unwrap(),
|
||||
directory: directory.into(),
|
||||
file_prefix: "registry".into(),
|
||||
max_files,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_configuration_and_flushes_without_installing_globals() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut config = LoggingConfig {
|
||||
level: parse_level("INFO").unwrap(),
|
||||
directory: directory.path().into(),
|
||||
file_prefix: "test".into(),
|
||||
max_files: 10,
|
||||
};
|
||||
let (subscriber, guard) = build_with_writer(&config, std::io::sink, false).unwrap();
|
||||
tracing::dispatcher::with_default(&subscriber, || {
|
||||
tracing::info!("visible-record");
|
||||
tracing::debug!("hidden-record");
|
||||
});
|
||||
drop(guard);
|
||||
let path = std::fs::read_dir(directory.path())
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.path();
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
assert_eq!(text.matches("visible-record").count(), 1);
|
||||
assert!(!text.contains("hidden-record"));
|
||||
for prefix in ["", " ", "..", "../escape", "a\\b", "a:b"] {
|
||||
config.file_prefix = prefix.into();
|
||||
assert!(config.validate().is_err());
|
||||
}
|
||||
assert!(parse_level("").is_err());
|
||||
assert!(parse_level("verbose").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn rotation_retention_off_and_reopen() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
for day in 1..=12 {
|
||||
std::fs::write(
|
||||
directory
|
||||
.path()
|
||||
.join(format!("registry.2000-01-{day:02}.log")),
|
||||
b"old",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let unrelated = directory.path().join("terminal.keep.log");
|
||||
std::fs::write(&unrelated, b"keep").unwrap();
|
||||
let (subscriber, guard) =
|
||||
crate::build_with_writer(&config(directory.path(), "info", 3), io::sink, false).unwrap();
|
||||
tracing::dispatcher::with_default(&subscriber, || tracing::info!("first-session"));
|
||||
drop(guard);
|
||||
let (subscriber, guard) =
|
||||
crate::build_with_writer(&config(directory.path(), "info", 3), io::sink, false).unwrap();
|
||||
tracing::dispatcher::with_default(&subscriber, || tracing::info!("second-session"));
|
||||
drop(guard);
|
||||
let (subscriber, guard) =
|
||||
crate::build_with_writer(&config(directory.path(), "off", 3), io::sink, false).unwrap();
|
||||
tracing::dispatcher::with_default(&subscriber, || tracing::error!("off-hidden"));
|
||||
drop(guard);
|
||||
let files = std::fs::read_dir(directory.path())
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().path())
|
||||
.filter(|path| {
|
||||
path.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.starts_with("registry.")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(files.len() <= 3);
|
||||
assert_eq!(std::fs::read(unrelated).unwrap(), b"keep");
|
||||
let text = files
|
||||
.iter()
|
||||
.map(|path| std::fs::read_to_string(path).unwrap())
|
||||
.collect::<String>();
|
||||
assert_eq!(text.matches("first-session").count(), 1);
|
||||
assert_eq!(text.matches("second-session").count(), 1);
|
||||
assert!(!text.contains("off-hidden"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_logging_configuration_is_rejected() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
assert!(crate::parse_level("invalid").is_err());
|
||||
assert!(
|
||||
crate::build_with_writer(&config(directory.path(), "info", 0), io::sink, false).is_err()
|
||||
);
|
||||
let file = directory.path().join("not-a-directory");
|
||||
std::fs::write(&file, b"file").unwrap();
|
||||
assert!(crate::build_with_writer(&config(&file, "info", 10), io::sink, false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_file_queue_applies_backpressure_without_dropping() {
|
||||
use std::io::Write;
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
struct PausedWriter {
|
||||
bytes: Arc<Mutex<Vec<u8>>>,
|
||||
entered: mpsc::Sender<()>,
|
||||
release: Option<mpsc::Receiver<()>>,
|
||||
}
|
||||
|
||||
impl Write for PausedWriter {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
if let Some(release) = self.release.take() {
|
||||
self.entered.send(()).unwrap();
|
||||
release.recv_timeout(Duration::from_secs(3)).unwrap();
|
||||
}
|
||||
self.bytes.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = Arc::new(Mutex::new(Vec::new()));
|
||||
let (entered, wait_entered) = mpsc::channel();
|
||||
let (release, wait_release) = mpsc::channel();
|
||||
let (mut writer, guard) = crate::file_writer(
|
||||
PausedWriter {
|
||||
bytes: bytes.clone(),
|
||||
entered,
|
||||
release: Some(wait_release),
|
||||
},
|
||||
1,
|
||||
"test-log-writer",
|
||||
);
|
||||
writer.write_all(b"first\n").unwrap();
|
||||
wait_entered.recv_timeout(Duration::from_secs(1)).unwrap();
|
||||
writer.write_all(b"second\n").unwrap();
|
||||
let (started, wait_started) = mpsc::channel();
|
||||
let (completed, wait_completed) = mpsc::channel();
|
||||
let producer = std::thread::spawn(move || {
|
||||
started.send(()).unwrap();
|
||||
writer.write_all(b"third\n").unwrap();
|
||||
completed.send(()).unwrap();
|
||||
});
|
||||
wait_started.recv_timeout(Duration::from_secs(1)).unwrap();
|
||||
let blocked = wait_completed
|
||||
.recv_timeout(Duration::from_millis(30))
|
||||
.is_err();
|
||||
release.send(()).unwrap();
|
||||
producer.join().unwrap();
|
||||
drop(guard);
|
||||
assert!(blocked);
|
||||
assert_eq!(&*bytes.lock().unwrap(), b"first\nsecond\nthird\n");
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
mod logging;
|
||||
Reference in New Issue
Block a user