v0.1.4-pre.016

This commit is contained in:
2026-08-16 19:00:49 +02:00
parent d92eb01bc2
commit 5aa538ed5d
29 changed files with 994 additions and 73 deletions

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-logging-lib/src/error.rs
// version: 3
// version: 4
/// Error code used when runtime logging settings are invalid.
pub const ERROR_CODE_INVALID_SETTINGS: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("logging", "invalid_settings");
@@ -9,3 +9,5 @@ pub const ERROR_CODE_ALREADY_INITIALIZED: ksp_core_lib::ErrorCode = ksp_core_lib
pub const ERROR_CODE_RELOAD_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("logging", "reload_failed");
/// Error code used when the rolling file output cannot be initialized.
pub const ERROR_CODE_FILE_OUTPUT_INITIALIZATION_FAILED: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("logging", "file_output_initialization_failed");
/// Error code used when an application Logging runtime identity is invalid.
pub const ERROR_CODE_INVALID_RUNTIME_IDENTITY: ksp_core_lib::ErrorCode = ksp_core_lib::ErrorCode::new("logging", "invalid_runtime_identity");

View File

@@ -0,0 +1,71 @@
// file: crates/ksp-logging-lib/src/identity.rs
// version: 1
//! Stable runtime identity used to separate persistent file outputs between application launches.
/// Identity attached to one installed KSP Logging runtime for the lifetime of an application launch.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LoggingRuntimeIdentity {
application_id: std::string::String,
launch_timestamp: std::string::String,
}
impl LoggingRuntimeIdentity {
/// Creates a validated runtime identity from an application identifier and launch timestamp token.
pub fn new(
application_id: impl std::convert::Into<std::string::String>,
launch_timestamp: impl std::convert::Into<std::string::String>,
) -> ksp_core_lib::Result<Self> {
let application_id = application_id.into();
let launch_timestamp = launch_timestamp.into();
let application_validation = validate_identity_component(application_id.as_str(), "application_id");
if let std::result::Result::Err(error) = application_validation {
return std::result::Result::Err(error);
}
let timestamp_validation = validate_identity_component(launch_timestamp.as_str(), "launch_timestamp");
if let std::result::Result::Err(error) = timestamp_validation {
return std::result::Result::Err(error);
}
return std::result::Result::Ok(Self { application_id, launch_timestamp });
}
/// Returns the application identifier embedded in persistent runtime file names.
#[must_use]
pub fn application_id(&self) -> &str {
return self.application_id.as_str();
}
/// Returns the stable launch timestamp token embedded in persistent runtime file names.
#[must_use]
pub fn launch_timestamp(&self) -> &str {
return self.launch_timestamp.as_str();
}
pub(crate) fn file_name_prefix(&self, configured_prefix: &str) -> std::string::String {
return format!("{}.{}.{}", self.application_id, self.launch_timestamp, configured_prefix);
}
}
fn validate_identity_component(value: &str, field: &'static str) -> ksp_core_lib::Result<()> {
if value.is_empty() || value.len() > 160 {
return invalid_identity(field);
}
for byte in value.bytes() {
let accepted = byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-');
if !accepted {
return invalid_identity(field);
}
}
return std::result::Result::Ok(());
}
fn invalid_identity(field: &'static str) -> ksp_core_lib::Result<()> {
return std::result::Result::Err(
ksp_core_lib::Error::new(crate::ERROR_CODE_INVALID_RUNTIME_IDENTITY, "KSP Logging runtime identity contains an invalid component")
.with_context("field", field),
);
}
#[cfg(test)]
#[path = "../unit_tests/identity.rs"]
mod tests;

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-logging-lib/src/lib.rs
// version: 7
// version: 8
#![warn(missing_docs)]
#![deny(unreachable_pub)]
#![forbid(unsafe_code)]
@@ -7,12 +7,13 @@
//! KSP-owned logging and tracing facade.
//!
//! This crate owns the KSP runtime logging contract. Behavioral KSP crates emit events and spans through this facade rather than depending directly on the
//! `tracing` stack. The crate owns the single global subscriber, KSP takeover filtering, hot reload and non-blocking outputs. `0.1.3-pre.006` supports
//! multiple simultaneous outputs with per-output level/target/domain routing, selectable formats, console ANSI and per-file dropped-line accounting. Structured
//! `domain` routing remains distinct from targets and follows explicit event domains or inherited span domains.
//! `tracing` stack. The crate owns the single global subscriber, KSP takeover filtering, transactional hot reload, non-blocking outputs, structured
//! level/target/domain routing and optional per-launch identities used to isolate persistent file outputs. Structured `domain` routing remains distinct from
//! targets and follows explicit event domains or inherited span domains.
mod domain;
mod error;
mod identity;
mod macros;
mod runtime;
mod settings;
@@ -23,16 +24,24 @@ mod writer;
pub use self::error::ERROR_CODE_ALREADY_INITIALIZED;
/// Error code used when the rolling file output cannot be initialized.
pub use self::error::ERROR_CODE_FILE_OUTPUT_INITIALIZATION_FAILED;
/// Error code used when an application Logging runtime identity is invalid.
pub use self::error::ERROR_CODE_INVALID_RUNTIME_IDENTITY;
/// Error code used when runtime logging settings are invalid.
pub use self::error::ERROR_CODE_INVALID_SETTINGS;
/// Error code used when a hot reload cannot replace the active runtime layers.
pub use self::error::ERROR_CODE_RELOAD_FAILED;
/// Stable application/launch identity used to isolate persistent Logging file outputs.
pub use self::identity::LoggingRuntimeIdentity;
/// Cumulative number of log lines dropped by non-blocking KSP outputs.
pub use self::runtime::DroppedLines;
/// Guard owning the mutable runtime state and non-blocking writers of the installed KSP logging subscriber.
pub use self::runtime::LoggingGuard;
/// Metadata for one active persistent Logging file output.
pub use self::runtime::RuntimeFileMetadata;
/// Installs the global KSP tracing subscriber.
pub use self::runtime::initialize;
/// Installs the global KSP tracing subscriber with a stable per-launch runtime identity.
pub use self::runtime::initialize_with_identity;
/// Replaces the active KSP logging settings without reinstalling the global subscriber.
pub use self::runtime::reinitialize;
/// Console stream selected for human-readable logs.

View File

@@ -1,5 +1,5 @@
// file: crates/ksp-logging-lib/src/runtime.rs
// version: 11
// version: 12
use tracing_subscriber::Layer; // rust-rules: trait-import
use tracing_subscriber::layer::SubscriberExt; // rust-rules: trait-import
@@ -41,10 +41,46 @@ impl DroppedLines {
}
}
/// Metadata for one active persistent Logging file output.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeFileMetadata {
output_id: std::string::String,
directory: std::path::PathBuf,
file_name_prefix: std::string::String,
rotation: crate::FileRotation,
}
impl RuntimeFileMetadata {
/// Returns the stable output identifier.
#[must_use]
pub fn output_id(&self) -> &str {
return self.output_id.as_str();
}
/// Returns the resolved directory containing this launch's files.
#[must_use]
pub fn directory(&self) -> &std::path::Path {
return self.directory.as_path();
}
/// Returns the effective launch-specific filename prefix passed to the rolling appender.
#[must_use]
pub fn file_name_prefix(&self) -> &str {
return self.file_name_prefix.as_str();
}
/// Returns the configured rotation cadence.
#[must_use]
pub const fn rotation(&self) -> crate::FileRotation {
return self.rotation;
}
}
/// Guard owning the mutable runtime state and non-blocking writers of the installed KSP logging subscriber.
pub struct LoggingGuard {
reload_handle: RuntimeReloadHandle,
settings: crate::LoggingSettings,
runtime_identity: std::option::Option<crate::LoggingRuntimeIdentity>,
outputs: RuntimeOutputs,
retired_dropped_lines: crate::DroppedLines,
retired_file_dropped_lines: std::collections::HashMap<std::string::String, usize>,
@@ -57,6 +93,25 @@ impl LoggingGuard {
return &self.settings;
}
/// Returns the stable application/launch identity attached to this runtime, when one was supplied at initialization.
#[must_use]
pub const fn runtime_identity(&self) -> std::option::Option<&crate::LoggingRuntimeIdentity> {
return self.runtime_identity.as_ref();
}
/// Returns metadata for the currently active persistent file outputs.
#[must_use]
pub fn active_file_outputs(&self) -> std::vec::Vec<crate::RuntimeFileMetadata> {
return self
.outputs
.files
.iter()
.map(|output| -> crate::RuntimeFileMetadata {
return output.metadata.clone();
})
.collect();
}
/// Returns cumulative dropped-line counters across active and previously reloaded outputs.
#[must_use]
pub fn dropped_lines(&self) -> crate::DroppedLines {
@@ -110,7 +165,7 @@ impl RuntimeOutputs {
.files
.iter()
.find(|output| -> bool {
return output.output_id == output_id;
return output.metadata.output_id == output_id;
})
.map(|output| -> usize {
return output.output.dropped_lines();
@@ -120,7 +175,7 @@ impl RuntimeOutputs {
fn accumulate_file_dropped_lines(&self, destination: &mut std::collections::HashMap<std::string::String, usize>) {
for output in &self.files {
let dropped = output.output.dropped_lines();
match destination.entry(output.output_id.clone()) {
match destination.entry(output.metadata.output_id.clone()) {
std::collections::hash_map::Entry::Occupied(mut entry) => {
let cumulative = entry.get().saturating_add(dropped);
*entry.get_mut() = cumulative;
@@ -134,7 +189,7 @@ impl RuntimeOutputs {
}
struct RuntimeFileOutput {
output_id: std::string::String,
metadata: crate::RuntimeFileMetadata,
output: RuntimeOutput,
}
@@ -155,7 +210,7 @@ struct PreparedOutput {
}
struct PreparedFileOutput {
output_id: std::string::String,
metadata: crate::RuntimeFileMetadata,
layer: BoxedRuntimeLayer,
output: RuntimeOutput,
}
@@ -165,7 +220,19 @@ struct PreparedFileOutput {
/// This function may succeed only once for the lifetime of the process. The returned guard owns all non-blocking writer guards and is then used by
/// [`crate::reinitialize`] to replace the active KSP logging configuration without installing a second global subscriber.
pub fn initialize(settings: &crate::LoggingSettings) -> ksp_core_lib::Result<crate::LoggingGuard> {
return prepare_runtime(settings).and_then(|prepared| -> ksp_core_lib::Result<crate::LoggingGuard> {
return initialize_runtime(settings, std::option::Option::None);
}
/// Installs the global KSP tracing subscriber and isolates persistent file outputs with one stable application launch identity.
pub fn initialize_with_identity(settings: &crate::LoggingSettings, identity: &crate::LoggingRuntimeIdentity) -> ksp_core_lib::Result<crate::LoggingGuard> {
return initialize_runtime(settings, std::option::Option::Some(identity.clone()));
}
fn initialize_runtime(
settings: &crate::LoggingSettings,
runtime_identity: std::option::Option<crate::LoggingRuntimeIdentity>,
) -> ksp_core_lib::Result<crate::LoggingGuard> {
return prepare_runtime_with_identity(settings, runtime_identity.as_ref()).and_then(|prepared| -> ksp_core_lib::Result<crate::LoggingGuard> {
let PreparedRuntime { layers, outputs } = prepared;
let (reload_layer, reload_handle) = tracing_subscriber::reload::Layer::new(layers);
let subscriber = tracing_subscriber::registry().with(reload_layer);
@@ -174,6 +241,7 @@ pub fn initialize(settings: &crate::LoggingSettings) -> ksp_core_lib::Result<cra
std::result::Result::Ok(()) => std::result::Result::Ok(crate::LoggingGuard {
reload_handle,
settings: settings.clone(),
runtime_identity,
outputs,
retired_dropped_lines: crate::DroppedLines::zero(),
retired_file_dropped_lines: std::collections::HashMap::new(),
@@ -191,7 +259,7 @@ pub fn initialize(settings: &crate::LoggingSettings) -> ksp_core_lib::Result<cra
/// configuration remains unchanged. After a successful layer swap, dropped-line counters from the retired outputs are retained cumulatively. Retired
/// layers are then dropped before their worker guards so all retired `NonBlocking` senders are released before shutdown asks the workers to drain/flush.
pub fn reinitialize(guard: &mut crate::LoggingGuard, settings: &crate::LoggingSettings) -> ksp_core_lib::Result<()> {
return prepare_runtime(settings).and_then(|prepared| -> ksp_core_lib::Result<()> {
return prepare_runtime_with_identity(settings, guard.runtime_identity.as_ref()).and_then(|prepared| -> ksp_core_lib::Result<()> {
let PreparedRuntime { layers, outputs } = prepared;
let mut retired_layers = RuntimeLayers::new();
let reload_result = guard.reload_handle.modify(|active_layers| {
@@ -215,6 +283,13 @@ pub fn reinitialize(guard: &mut crate::LoggingGuard, settings: &crate::LoggingSe
}
fn prepare_runtime(settings: &crate::LoggingSettings) -> ksp_core_lib::Result<PreparedRuntime> {
return prepare_runtime_with_identity(settings, std::option::Option::None);
}
fn prepare_runtime_with_identity(
settings: &crate::LoggingSettings,
runtime_identity: std::option::Option<&crate::LoggingRuntimeIdentity>,
) -> ksp_core_lib::Result<PreparedRuntime> {
let validation_error = settings.validate().err();
if let std::option::Option::Some(error) = validation_error {
return std::result::Result::Err(error);
@@ -233,13 +308,13 @@ fn prepare_runtime(settings: &crate::LoggingSettings) -> ksp_core_lib::Result<Pr
outputs.console = std::option::Option::Some(prepared_console.output);
}
for file in enabled_files {
let prepared_file_result = build_file_output(file, settings);
let prepared_file_result = build_file_output(file, settings, runtime_identity);
let prepared_file = match prepared_file_result {
std::result::Result::Ok(output) => output,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
output_layers.push(prepared_file.layer);
outputs.files.push(RuntimeFileOutput { output_id: prepared_file.output_id, output: prepared_file.output });
outputs.files.push(RuntimeFileOutput { metadata: prepared_file.metadata, output: prepared_file.output });
}
if output_layers.is_empty() {
return std::result::Result::Ok(PreparedRuntime { layers: RuntimeLayers::new(), outputs });
@@ -272,10 +347,18 @@ fn build_console_output(console: &crate::ConsoleSettings, settings: &crate::Logg
};
}
fn build_file_output(file: &crate::FileSettings, settings: &crate::LoggingSettings) -> ksp_core_lib::Result<PreparedFileOutput> {
fn build_file_output(
file: &crate::FileSettings,
settings: &crate::LoggingSettings,
runtime_identity: std::option::Option<&crate::LoggingRuntimeIdentity>,
) -> ksp_core_lib::Result<PreparedFileOutput> {
let file_name_prefix = match runtime_identity {
std::option::Option::Some(identity) => identity.file_name_prefix(file.file_name_prefix()),
std::option::Option::None => file.file_name_prefix().to_owned(),
};
let appender_result = tracing_appender::rolling::RollingFileAppender::builder()
.rotation(map_file_rotation(file.rotation()))
.filename_prefix(file.file_name_prefix())
.filename_prefix(file_name_prefix.as_str())
.build(file.directory());
let appender = match appender_result {
std::result::Result::Ok(appender) => appender,
@@ -284,7 +367,7 @@ fn build_file_output(file: &crate::FileSettings, settings: &crate::LoggingSettin
ksp_core_lib::Error::new(crate::ERROR_CODE_FILE_OUTPUT_INITIALIZATION_FAILED, "unable to initialize the KSP rolling file appender")
.with_context("output_id", file.output_id())
.with_context("directory", file.directory().display().to_string())
.with_context("file_name_prefix", file.file_name_prefix())
.with_context("file_name_prefix", file_name_prefix.as_str())
.with_source(error),
);
},
@@ -292,7 +375,13 @@ fn build_file_output(file: &crate::FileSettings, settings: &crate::LoggingSettin
let stripped_writer = crate::writer::StripAnsiWriter::new(appender);
let thread_name = format!("ksp-logging-{}", file.output_id());
let prepared = build_non_blocking_output(stripped_writer, thread_name.as_str(), settings.span_events(), false, false, file.format(), file.filter());
return std::result::Result::Ok(PreparedFileOutput { output_id: file.output_id().to_string(), layer: prepared.layer, output: prepared.output });
let metadata = crate::RuntimeFileMetadata {
output_id: file.output_id().to_owned(),
directory: file.directory().to_path_buf(),
file_name_prefix,
rotation: file.rotation(),
};
return std::result::Result::Ok(PreparedFileOutput { metadata, layer: prepared.layer, output: prepared.output });
}
fn build_non_blocking_output<W>(