rlg/config.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
// config.rs
// Copyright © 2024 RustLogs (RLG). All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! Configuration module for RustLogs (RLG).
//!
//! This module provides structures and implementations for managing
//! the configuration of the RustLogs library. It includes functionality
//! for loading, saving, and manipulating configuration settings, as well
//! as handling environment variables, error management, and log rotation.
use crate::LogLevel;
use config::{
Config as ConfigSource, ConfigError as SourceConfigError,
File as ConfigFile,
};
use envy;
use log::{error, info, warn};
use notify::{Event, EventKind, RecursiveMode, Watcher};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
env, fmt,
fs::{self, OpenOptions},
net::{SocketAddr, ToSocketAddrs},
num::NonZeroU64,
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
};
use thiserror::Error;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use tokio::sync::mpsc;
const CURRENT_CONFIG_VERSION: &str = "1.0";
/// Custom error types for configuration management.
#[derive(Debug, Error)]
pub enum ConfigError {
/// Error occurred while parsing an environment variable.
#[error("Environment variable parse error: {0}")]
EnvVarParseError(#[from] envy::Error),
/// Error occurred while parsing the configuration file.
#[error("Configuration parsing error: {0}")]
ConfigParseError(#[from] SourceConfigError),
/// Invalid file path was provided for configuration.
#[error("Invalid file path: {0}")]
InvalidFilePath(String),
/// Error reading from a file.
#[error("File read error: {0}")]
FileReadError(String),
/// Error writing to a file.
#[error("File write error: {0}")]
FileWriteError(String),
/// Error validating the configuration settings.
#[error("Configuration validation error: {0}")]
ValidationError(String),
/// Configuration version mismatch.
#[error("Configuration version error: {0}")]
VersionError(String),
/// Required field is missing in the configuration.
#[error("Missing required field: {0}")]
MissingFieldError(String),
/// Error setting up the file watcher.
#[error("Watcher error: {0}")]
WatcherError(#[from] notify::Error),
}
/// Enum representing log rotation options.
#[derive(
Clone,
Copy,
Debug,
Deserialize,
Serialize,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
)]
pub enum LogRotation {
/// Size-based log rotation.
Size(NonZeroU64),
/// Time-based log rotation.
Time(NonZeroU64),
/// Date-based log rotation.
Date,
/// Count-based log rotation.
Count(u32),
}
impl FromStr for LogRotation {
type Err = ConfigError;
/// Parses a string into a `LogRotation` enum variant.
///
/// # Arguments
///
/// * `s` - A string slice representing the log rotation type and associated value.
///
/// # Returns
///
/// A `Result<LogRotation, ConfigError>` indicating the log rotation option or an error.
///
/// # Errors
///
/// This function will return an error if the string format is invalid or if the values
/// provided (e.g. size, time, count) are not valid.
///
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.trim().splitn(2, ':').collect();
match parts[0].to_lowercase().as_str() {
"size" => parse_nonzero_u64(parts.get(1).copied(), "size")
.map(LogRotation::Size),
"time" => parse_nonzero_u64(parts.get(1).copied(), "time")
.map(LogRotation::Time),
"date" => Ok(LogRotation::Date),
"count" => {
let count = parts
.get(1)
.ok_or_else(|| ConfigError::ValidationError("Missing count value for log rotation".to_string()))?
.parse()
.map_err(|_| ConfigError::ValidationError(format!("Invalid count value for log rotation: '{}'", parts[1])))?;
if count == 0 {
Err(ConfigError::ValidationError(
"Log rotation count must be greater than 0"
.to_string(),
))
} else {
Ok(LogRotation::Count(count))
}
}
_ => Err(ConfigError::ValidationError(format!(
"Invalid log rotation option: '{}'",
s
))),
}
}
}
/// Helper function to parse a `NonZeroU64` from a string value.
///
/// # Arguments
///
/// * `value` - An optional string slice that contains the value to parse.
/// * `context` - A string slice providing context about what is being parsed.
///
/// # Returns
///
/// A `Result<NonZeroU64, ConfigError>` representing the parsed value or an error.
///
/// # Errors
///
/// This function will return an error if the value is not a valid number or is missing.
///
fn parse_nonzero_u64(
value: Option<&str>,
context: &str,
) -> Result<NonZeroU64, ConfigError> {
let size = value
.ok_or_else(|| {
ConfigError::ValidationError(format!(
"Missing {} value for log rotation",
context
))
})?
.parse::<u64>()
.map_err(|_| {
ConfigError::ValidationError(format!(
"Invalid {} value for log rotation",
context
))
})?;
NonZeroU64::new(size).ok_or_else(|| {
ConfigError::ValidationError(format!(
"{} value must be greater than 0",
context
))
})
}
/// Enum representing different logging destinations.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum LoggingDestination {
/// Log to a file.
File(PathBuf),
/// Log to standard output.
Stdout,
/// Log to a network destination.
Network(String), // Expects format like "127.0.0.1:8080" or "example.com:8080"
}
// Configuration structure for the logging system.
///
/// This structure holds the configuration for logging, including log file paths,
/// log rotation settings, logging format, and environment variables.
///
/// # Fields
///
/// - `version`: The version of the configuration.
/// - `profile`: The profile name for the configuration.
/// - `log_file_path`: The path to the log file.
/// - `log_level`: The logging level.
/// - `log_rotation`: Optional log rotation settings.
/// - `log_format`: The format for log messages.
/// - `logging_destinations`: List of destinations where logs will be sent.
/// - `env_vars`: Environment variables that apply to the logging system.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// Version of the configuration.
#[serde(default = "default_version")]
pub version: String,
/// Profile name for the configuration.
#[serde(default = "default_profile")]
pub profile: String,
/// Path to the log file.
#[serde(default = "default_log_file_path")]
pub log_file_path: PathBuf,
/// Log level for the system.
#[serde(default)]
pub log_level: LogLevel,
/// Log rotation settings.
pub log_rotation: Option<LogRotation>,
/// Log format string.
#[serde(default = "default_log_format")]
pub log_format: String,
/// Logging destinations for the system.
#[serde(default = "default_logging_destinations")]
pub logging_destinations: Vec<LoggingDestination>,
/// Environment variables for the system.
#[serde(default)]
pub env_vars: HashMap<String, String>,
}
/// Default values for configuration fields.
fn default_version() -> String {
CURRENT_CONFIG_VERSION.to_string()
}
fn default_profile() -> String {
"default".to_string()
}
fn default_log_file_path() -> PathBuf {
PathBuf::from("RLG.log")
}
fn default_log_format() -> String {
"%level - %message".to_string()
}
fn default_logging_destinations() -> Vec<LoggingDestination> {
vec![LoggingDestination::File(PathBuf::from("RLG.log"))]
}
impl Default for Config {
fn default() -> Self {
Config {
version: default_version(),
profile: default_profile(),
log_file_path: default_log_file_path(),
log_level: LogLevel::INFO,
log_rotation: NonZeroU64::new(10 * 1024 * 1024)
.map(LogRotation::Size),
log_format: default_log_format(),
logging_destinations: default_logging_destinations(),
env_vars: HashMap::new(),
}
}
}
impl Config {
/// Loads configuration from a file or environment variables.
pub async fn load_async<P: AsRef<Path>>(
config_path: Option<P>,
) -> Result<Arc<RwLock<Config>>, ConfigError> {
let config = if let Some(path) = config_path {
let mut file = File::open(&path).await.map_err(|e| {
ConfigError::FileReadError(e.to_string())
})?;
let mut contents = String::new();
file.read_to_string(&mut contents).await.map_err(|e| {
ConfigError::FileReadError(e.to_string())
})?;
let config_source = ConfigSource::builder()
.add_source(ConfigFile::from_str(
&contents,
config::FileFormat::Toml,
))
.build()?;
let version: String = config_source.get("version")?;
if version != CURRENT_CONFIG_VERSION {
return Err(ConfigError::VersionError(format!(
"Unsupported configuration version: {}",
version
)));
}
config_source.try_deserialize()?
} else {
Config::default()
};
config.validate()?;
Ok(Arc::new(RwLock::new(config)))
}
/// Retrieves a value from the configuration based on the specified key.
pub fn get<T>(&self, key: &str) -> Option<T>
where
T: serde::de::DeserializeOwned,
{
let value = match key {
"version" => serde_json::to_value(&self.version).ok()?,
"profile" => serde_json::to_value(&self.profile).ok()?,
"log_file_path" => {
serde_json::to_value(&self.log_file_path).ok()?
}
"log_level" => serde_json::to_value(self.log_level).ok()?,
"log_rotation" => {
serde_json::to_value(self.log_rotation).ok()?
}
"log_format" => {
serde_json::to_value(&self.log_format).ok()?
}
"logging_destinations" => {
serde_json::to_value(&self.logging_destinations).ok()?
}
"env_vars" => serde_json::to_value(&self.env_vars).ok()?,
_ => return None,
};
serde_json::from_value(value).ok()
}
/// Saves the current configuration to a file.
pub fn save_to_file<P: AsRef<Path>>(
&self,
path: P,
) -> Result<(), ConfigError> {
let config_string = serde_json::to_string_pretty(self)
.map_err(|e| {
ConfigError::FileWriteError(format!(
"Failed to serialize config: {}",
e
))
})?;
fs::write(path, config_string).map_err(|e| {
ConfigError::FileWriteError(format!(
"Failed to write config file: {}",
e
))
})?;
Ok(())
}
/// Sets a value in the configuration based on the specified key.
pub fn set<T: Serialize>(
&mut self,
key: &str,
value: T,
) -> Result<(), ConfigError> {
let serialize_value =
|v: T| -> Result<serde_json::Value, ConfigError> {
serde_json::to_value(v).map_err(|e| {
ConfigError::ValidationError(e.to_string())
})
};
match key {
"version" => {
self.version = serialize_value(value)?
.as_str()
.ok_or_else(|| {
ConfigError::ValidationError(
"Invalid version format".to_string(),
)
})?
.to_string()
}
"profile" => {
self.profile = serialize_value(value)?
.as_str()
.ok_or_else(|| {
ConfigError::ValidationError(
"Invalid profile format".to_string(),
)
})?
.to_string()
}
"log_file_path" => {
self.log_file_path =
serde_json::from_value(serialize_value(value)?)
.map_err(|e| {
ConfigError::ConfigParseError(
SourceConfigError::Message(
e.to_string(),
),
)
})?
}
"log_level" => {
self.log_level =
serde_json::from_value(serialize_value(value)?)
.map_err(|e| {
ConfigError::ConfigParseError(
SourceConfigError::Message(
e.to_string(),
),
)
})?
}
"log_rotation" => {
self.log_rotation =
serde_json::from_value(serialize_value(value)?)
.map_err(|e| {
ConfigError::ConfigParseError(
SourceConfigError::Message(
e.to_string(),
),
)
})?
}
"log_format" => {
self.log_format = serialize_value(value)?
.as_str()
.ok_or_else(|| {
ConfigError::ValidationError(
"Invalid log format".to_string(),
)
})?
.to_string()
}
"logging_destinations" => {
self.logging_destinations =
serde_json::from_value(serialize_value(value)?)
.map_err(|e| {
ConfigError::ConfigParseError(
SourceConfigError::Message(
e.to_string(),
),
)
})?
}
"env_vars" => {
self.env_vars =
serde_json::from_value(serialize_value(value)?)
.map_err(|e| {
ConfigError::ConfigParseError(
SourceConfigError::Message(
e.to_string(),
),
)
})?
}
_ => {
return Err(ConfigError::ValidationError(format!(
"Unknown configuration key: {}",
key
)))
}
}
Ok(())
}
/// Validates the configuration settings.
pub fn validate(&self) -> Result<(), ConfigError> {
if self.version.trim().is_empty() {
return Err(ConfigError::ValidationError(
"Version cannot be empty".to_string(),
));
}
if self.profile.trim().is_empty() {
return Err(ConfigError::ValidationError(
"Profile cannot be empty".to_string(),
));
}
if self.log_file_path.as_os_str().is_empty() {
return Err(ConfigError::ValidationError(
"Log file path cannot be empty".to_string(),
));
}
if let Some(rotation) = &self.log_rotation {
match rotation {
LogRotation::Size(size) if size.get() == 0 => {
return Err(ConfigError::ValidationError(
"Log rotation size must be greater than 0"
.to_string(),
));
}
LogRotation::Time(time) if time.get() == 0 => {
return Err(ConfigError::ValidationError(
"Log rotation time must be greater than 0"
.to_string(),
));
}
LogRotation::Count(count) if *count == 0 => {
return Err(ConfigError::ValidationError(
"Log rotation count must be greater than 0"
.to_string(),
));
}
_ => {}
}
}
if self.log_format.trim().is_empty() {
return Err(ConfigError::ValidationError(
"Log format cannot be empty".to_string(),
));
}
if self.logging_destinations.is_empty() {
return Err(ConfigError::ValidationError(
"At least one logging destination must be specified"
.to_string(),
));
}
for destination in &self.logging_destinations {
if let LoggingDestination::Network(address) = destination {
self.validate_network_address(address)?;
}
}
for (key, value) in &self.env_vars {
if key.trim().is_empty() {
return Err(ConfigError::ValidationError(
"Environment variable key cannot be empty"
.to_string(),
));
}
if value.trim().is_empty() {
return Err(ConfigError::ValidationError(format!("Value for environment variable '{}' cannot be empty", key)));
}
}
if let LoggingDestination::File(path) =
&self.logging_destinations[0]
{
if let Some(parent_dir) = path.parent() {
fs::create_dir_all(parent_dir).map_err(|e| {
ConfigError::ValidationError(format!(
"Failed to create directory for log file: {}",
e
))
})?;
}
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)
.map_err(|e| {
ConfigError::ValidationError(format!(
"Log file is not writable: {}",
e
))
})?;
}
Ok(())
}
/// Validates a network address.
fn validate_network_address(
&self,
address: &str,
) -> Result<(), ConfigError> {
if address.trim().is_empty() {
return Err(ConfigError::ValidationError(
"Network logging destination address cannot be empty"
.to_string(),
));
}
if address.parse::<SocketAddr>().is_ok() {
return Ok(());
}
address
.to_socket_addrs()
.map_err(|e| {
ConfigError::ValidationError(format!(
"Invalid network address '{}': {}",
address, e
))
})?
.next()
.ok_or_else(|| {
ConfigError::ValidationError(format!(
"Could not resolve network address: '{}'",
address
))
})?;
Ok(())
}
/// Expands environment variables in the configuration values.
pub fn expand_env_vars(&self) -> Config {
let mut new_config = self.clone();
for (key, value) in &mut new_config.env_vars {
if let Ok(env_value) = env::var(key) {
*value = env_value;
}
}
new_config
}
/// Hot-reloads configuration on file change.
#[allow(clippy::incompatible_msrv)]
pub async fn hot_reload_async(
config_path: &str,
config: Arc<RwLock<Config>>,
) -> Result<mpsc::Sender<()>, ConfigError> {
let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1);
let (tx, mut rx) = mpsc::channel::<notify::Result<Event>>(100);
let mut watcher = notify::recommended_watcher(move |res| {
let _ = tx.blocking_send(res);
})?;
watcher.watch(
Path::new(config_path),
RecursiveMode::NonRecursive,
)?;
let config_path = config_path.to_string();
tokio::spawn(async move {
loop {
tokio::select! {
Some(res) = rx.recv() => {
match res {
Ok(Event { kind, .. }) => match kind {
EventKind::Modify(_) => {
info!("Configuration file changed, reloading...");
match Config::load_async(Some(&config_path)).await {
Ok(new_config) => {
let mut config_write = config.write();
*config_write = new_config.read().clone();
info!("Configuration reloaded successfully");
}
Err(e) => error!("Failed to reload configuration: {}", e),
}
}
EventKind::Create(_) => info!("Configuration file created"),
EventKind::Remove(_) => warn!("Configuration file removed"),
_ => {}
},
Err(e) => error!("Watch error: {:?}", e),
}
}
_ = stop_rx.recv() => {
info!("Stopping configuration hot reload");
break;
}
}
}
});
Ok(stop_tx)
}
/// Compares two configurations and returns the differences.
pub fn diff(
config1: &Config,
config2: &Config,
) -> HashMap<String, String> {
let mut differences = HashMap::new();
if config1.version != config2.version {
differences.insert(
"version".to_string(),
format!("{} -> {}", config1.version, config2.version),
);
}
if config1.profile != config2.profile {
differences.insert(
"profile".to_string(),
format!("{} -> {}", config1.profile, config2.profile),
);
}
if config1.log_file_path != config2.log_file_path {
differences.insert(
"log_file_path".to_string(),
format!(
"{} -> {}",
config1.log_file_path.display(),
config2.log_file_path.display()
),
);
}
if config1.log_level != config2.log_level {
differences.insert(
"log_level".to_string(),
format!(
"{:?} -> {:?}",
config1.log_level, config2.log_level
),
);
}
if config1.log_rotation != config2.log_rotation {
differences.insert(
"log_rotation".to_string(),
format!(
"{:?} -> {:?}",
config1.log_rotation, config2.log_rotation
),
);
}
if config1.log_format != config2.log_format {
differences.insert(
"log_format".to_string(),
format!(
"{} -> {}",
config1.log_format, config2.log_format
),
);
}
if config1.logging_destinations != config2.logging_destinations
{
differences.insert(
"logging_destinations".to_string(),
format!(
"{:?} -> {:?}",
config1.logging_destinations,
config2.logging_destinations
),
);
}
if config1.env_vars != config2.env_vars {
differences.insert(
"env_vars".to_string(),
format!(
"{:?} -> {:?}",
config1.env_vars, config2.env_vars
),
);
}
differences
}
/// Merges another configuration into the current configuration.
pub fn merge(&self, other: &Config) -> Config {
Config {
version: other.version.clone(),
profile: other.profile.clone(),
log_file_path: other.log_file_path.clone(),
log_level: other.log_level,
log_rotation: other.log_rotation,
log_format: other.log_format.clone(),
logging_destinations: other.logging_destinations.clone(),
env_vars: self
.env_vars
.iter()
.chain(other.env_vars.iter())
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
}
}
}
impl TryFrom<env::Vars> for Config {
type Error = ConfigError;
fn try_from(vars: env::Vars) -> Result<Self, Self::Error> {
envy::from_iter(vars)
.map_err(|e: envy::Error| ConfigError::EnvVarParseError(e))
}
}
impl fmt::Display for LogRotation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LogRotation::Size(size) => {
write!(f, "Size: {} bytes", size.get())
}
LogRotation::Time(seconds) => {
write!(f, "Time: {} seconds", seconds.get())
}
LogRotation::Date => write!(f, "Date-based rotation"),
LogRotation::Count(count) => {
write!(f, "Count: {} logs", count)
}
}
}
}