scouter_server/api/
setup.rs

1use anyhow::Context;
2use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
3use tracing::{error, info};
4
5use std::io;
6
7use tracing_subscriber;
8use tracing_subscriber::fmt::time::UtcTime;
9
10const DEFAULT_TIME_PATTERN: &str =
11    "[year]-[month]-[day]T[hour repr:24]:[minute]:[second]::[subsecond digits:4]";
12
13pub async fn setup_logging() -> Result<(), anyhow::Error> {
14    let time_format = time::format_description::parse(DEFAULT_TIME_PATTERN).unwrap();
15
16    tracing_subscriber::fmt()
17        .json()
18        .with_target(false)
19        .flatten_event(true)
20        .with_thread_ids(true)
21        .with_timer(UtcTime::new(time_format))
22        .with_writer(io::stdout)
23        .init();
24
25    Ok(())
26}
27
28/// Setup the application with the given database pool.
29
30pub async fn create_db_pool(database_url: Option<String>) -> Result<Pool<Postgres>, anyhow::Error> {
31    let database_url = match database_url {
32        Some(url) => url,
33        None => std::env::var("DATABASE_URL").with_context(|| "DATABASE_URL must be set")?,
34    };
35
36    // get max connections from env or set to 10
37    let max_connections = std::env::var("MAX_CONNECTIONS")
38        .unwrap_or_else(|_| "10".to_string())
39        .parse::<u32>()
40        .expect("MAX_CONNECTIONS must be a number");
41
42    let pool = match PgPoolOptions::new()
43        .max_connections(max_connections)
44        .connect(&database_url)
45        .await
46    {
47        Ok(pool) => {
48            info!("✅ Successfully connected to database");
49            pool
50        }
51        Err(err) => {
52            error!("🔥 Failed to connect to database {:?}", err);
53            std::process::exit(1);
54        }
55    };
56
57    Ok(pool)
58}