tgqe 0.0.1

The Great Qin Empire —— A centralized system for integrating and summarizing common compiler front-end library errors and span error output libraries, with optional Ariadne integration.
/**

 *  - Copyright (c) 星灿长风v(Starwindv) 2026/08/03
 *  - License: BSD-3
 *  - Author: 星灿长风v(StarWindv)
 *  - Location: tgqe/src/modules/channel/configure.rs
 */
/**

 * Env:
 * - `TGQE_RENDER_LIMIT`: Default `30`
 * - `TGQE_COMPACT`: Default `false`
 * - `TGQE_DB_FILE_FORMAT`: Default `tgqe_record_%h-%M-%s`
 * - `TGQE_DB_MAX_CONNECTIONS`: Default `5`
 */
use std::str::FromStr;

/**

 * ## I. What
 *
 * ### 1.1 Description
 *
 * This structure is the runtime configuration of this library,
 * loaded from environment variables (or a `.env` file).
 *
 * ---
 *
 * ## II. Memory Layout
 *
 * ### 2.1 Analyze
 *
 * ```text
 * TgqeConfig <
 *     render_limit      : u64,    // 8
 *     compact           : bool,   // 1
 *     db_file_format    : String, // 24
 *     db_max_connections: u32,    // 4
 *     padding           : 3 bytes,// 3
 * > // 40
 * ```
 *
 * ---
 *
 * ### 2.2 Note
 *
 * - The fields are feature-gated:
 * `render_limit` and `compact` only exist with the `renderer` feature,
 * while the other two only exist with the `store-to-db` feature.
 *
 * ---
 *
 * ## III. Default Value:
 * - render_limit      : 30
 * - compact           : false
 * - db_file_format    : `tgqe_record_%h-%M-%s`
 * - db_max_connections: 5
 */
pub(crate) struct TgqeConfig {
    #[cfg(feature = "renderer")]
    pub render_limit: u64,

    #[cfg(feature = "renderer")]
    pub compact: bool,

    #[cfg(feature = "store-to-db")]
    pub db_file_format: String,

    #[cfg(feature = "store-to-db")]
    pub db_max_connections: u32,
}

impl TgqeConfig {
    pub(crate) fn load() -> Self {
        dotenvy::dotenv().ok();

        Self {
            #[cfg(feature = "renderer")]
            render_limit: Self::env_parsed(
                "TGQE_RENDER_LIMIT",
                30u64,
            ),
            #[cfg(feature = "renderer")]
            compact: Self::env_parsed(
                "TGQE_COMPACT",
                false,
            ),
            #[cfg(feature = "store-to-db")]
            db_file_format: Self::env_string(
                "TGQE_DB_FILE_FORMAT",
                "tgqe_record_%h-%M-%s",
            ),
            #[cfg(feature = "store-to-db")]
            db_max_connections:
                Self::env_parsed(
                    "TGQE_DB_MAX_CONNECTIONS",
                    5u32,
                ),
        }
    }

    #[cfg(feature = "store-to-db")]
    pub(crate) fn env_string(
        key: &str,
        default: &str,
    ) -> String {
        std::env::var(key).unwrap_or_else(
            |_| default.to_string(),
        )
    }

    pub(crate) fn env_parsed<T: FromStr>(
        key: &str,
        default: T,
    ) -> T {
        std::env::var(key)
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(default)
    }
}