use cirious_codex::codex_config::format::ConfigFormat;
use cirious_codex::codex_config::{ConfigBuilder, Deserialize};
use cirious_codex::codex_logger::{Dispatcher, Level, Record, StdoutDispatcher, StyledTerminalFormatter};
use cirious_codex::codex_result::{codex_ok, CodexError, Result};
use std::env;
#[derive(Debug, Deserialize)]
struct DatabaseConfig {
host: String,
port: u16,
}
#[derive(Debug, Deserialize)]
struct ServerConfig {
worker_threads: usize,
database: DatabaseConfig,
}
fn log(level: Level, message: std::fmt::Arguments) {
let dispatcher = StdoutDispatcher::new(StyledTerminalFormatter);
let record = Record { level, args: message };
dispatcher.dispatch(&record);
}
fn run_application(simulate_failure: bool) -> Result<()> {
log(Level::Info, format_args!("Bootstrapping the Cirious ecosystem..."));
let base_config = r#"{
"worker_threads": 4,
"database": {
"host": "localhost",
"port": 5432
}
}"#;
env::set_var("SERVER_WORKER_THREADS", "16");
log(Level::Debug, format_args!("Loading configuration sources..."));
let config = ConfigBuilder::new()
.add_source(base_config, ConfigFormat::Json)?
.value
.add_env_prefix("SERVER_")
.build::<ServerConfig>()?
.value;
log(
Level::Info,
format_args!(
"Configuration loaded successfully. Threads: {}, DB: {}:{}",
config.worker_threads, config.database.host, config.database.port
),
);
if simulate_failure {
log(
Level::Warn,
format_args!("Simulating a critical application failure..."),
);
return Err(
CodexError::builder("DB_CONN_ERR", "Failed to establish a connection with the database")
.with_suggestion("Check if the database host is reachable and the credentials are correct."),
);
}
log(
Level::Info,
format_args!("Application executed successfully with no errors."),
);
codex_ok!(())
}
fn main() {
let simulate_failure = false;
if let Err(e) = run_application(simulate_failure) {
log(
Level::Error,
format_args!("Application crashed with fatal error:\n{:#?}", e),
);
std::process::exit(1);
}
}