moongraphql_builder 0.1.1

Type-state GraphQL query and selector builder with compile-time AST deduplication, complexity budgeting, and Project Fluent i18n.
Documentation
//! Dynamic internationalization (i18n) and localized diagnostic engine for GraphQL builders.
//!
//! Provides a thread-safe message formatting environment, Tokio Task-Local execution contexts,
//! and an extensible registry for external translation dictionaries.
//!
//! ### Multi-Tier Locale Resolution Cascade
//!
//! When formatting validation messages or metric errors, the active locale is resolved via:
//! 1. **Tokio Task-Local Context ([`TASK_LOCALE`]):** Isolated per asynchronous task (requires `"tokio"` feature).
//! 2. **Global Process Override ([`set_global_locale`]):** Useful in tests and monolithic CLI tools.
//! 3. **Host OS Regional Settings ([`sys_locale::get_locale`](https://docs.rs/sys-locale)):** Auto-detected from OS environment.
//! 4. **Canonical Default (`"en"`):** Guaranteed to contain 100% of all keys.
//!
//! ### BiDi Isolation Suppression
//!
//! Project Fluent defaults to wrapping interpolated values with invisible Unicode First Strong
//! isolate markers (`\u{2068}` and `\u{2069}`). While intended for mixed-direction GUI text,
//! these characters corrupt raw GraphQL query documents and JSON payloads.
//! All bundles generated by this engine explicitly disable directional isolation via
//! [`FluentBundle::set_use_isolating(false)`](https://docs.rs/fluent/latest/fluent/bundle/struct.FluentBundle.html#method.set_use_isolating).
//!
//! ### Quick Example
//!
//! ```rust
//! use moongraphql_builder::{set_global_locale, tr};
//!
//! // English diagnostic formatting
//! set_global_locale("en");
//! let msg_en = tr!("err-gql-complexity-exceeded", "calculated" => 250, "limit" => 190);
//! println!("{}", msg_en);
//!
//! // Russian diagnostic formatting
//! set_global_locale("ru");
//! let msg_ru = tr!("err-gql-complexity-exceeded", "calculated" => 250, "limit" => 190);
//! println!("{}", msg_ru);
//! ```

pub use fluent::FluentArgs;
use fluent::FluentResource;
use fluent::bundle::FluentBundle;
use std::collections::HashMap;
use std::sync::{LazyLock, RwLock};
use unic_langid::LanguageIdentifier;

/// Default system locale identifier applied when requested translations are missing.
const DEFAULT_LOCALE: &str = "en";

/// Canonical fallback locale code guaranteed to contain an exhaustive set of all translation keys.
const FALLBACK_LOCALE: &str = "en";

#[cfg(feature = "tokio")]
tokio::task_local! {
    /// Asynchronous task-local storage for isolating locale resolution per task.
    ///
    /// Allows concurrent asynchronous tasks (e.g. parallel GraphQL batch dispatches)
    /// to format errors in different languages simultaneously without global locks.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[cfg(feature = "tokio")]
    /// # async fn doc_example() {
    /// use moongraphql_builder::i18n::TASK_LOCALE;
    ///
    /// TASK_LOCALE.scope("ru".to_string(), async {
    ///     let localized = moongraphql_builder::tr!("err-val-required", "arg" => "page", "query" => "animes");
    ///     println!("Task-isolated Russian error: {}", localized);
    /// }).await;
    /// # }
    /// ```
    pub static TASK_LOCALE: String;
}

/// Global language context for synchronous environments, CLI tools, and unit tests.
static GLOBAL_LOCALE: RwLock<String> = RwLock::new(String::new());

/// Concurrent Fluent bundle type alias with thread-safe memoization support.
type ConcurrentBundle = FluentBundle<FluentResource, intl_memoizer::concurrent::IntlLangMemoizer>;

/// Global lazy-initialized storage of compiled language bundles protected by an [`std::sync::RwLock`].
static BUNDLES: LazyLock<RwLock<HashMap<String, ConcurrentBundle>>> = LazyLock::new(|| {
    let mut bundles = HashMap::new();

    let en_bundle = create_bundle("en-US", include_str!("../locales/en-US/main.ftl"));
    let ru_bundle = create_bundle("ru-RU", include_str!("../locales/ru-RU/main.ftl"));

    bundles.insert("en".to_string(), en_bundle);
    bundles.insert("ru".to_string(), ru_bundle);

    RwLock::new(bundles)
});

/// Internal helper function to compile an isolated Fluent bundle with BiDi isolation disabled.
///
/// # Arguments
///
/// * `lang` ([`&str`]) — BCP-47 language tag (e.g. `"en-US"`, `"ru-RU"`).
/// * `source` ([`&str`]) — Raw FTL resource syntax text.
///
/// # Returns
///
/// Returns an initialized, thread-safe [`ConcurrentBundle`].
fn create_bundle(lang: &str, source: &str) -> ConcurrentBundle {
    let resource = FluentResource::try_new(source.to_string())
        .expect("Failed to parse embedded core FTL resource");
    let lang_id: LanguageIdentifier = lang
        .parse()
        .expect("Invalid language identifier for bundle creation");

    let mut bundle = FluentBundle::new_concurrent(vec![lang_id]);
    bundle.set_use_isolating(false);
    bundle
        .add_resource(resource)
        .expect("Failed to add resource to core bundle");

    bundle
}

/// Registers an external FTL translation resource from a dependent downstream crate.
///
/// Allows external libraries using `moongraphql_builder` to register custom error messages
/// or localized domain keys into the shared bundle pool.
///
/// # Arguments
///
/// * `lang` ([`&str`]) — Language identifier tag (e.g. `"en-US"` or `"ru-RU"`).
/// * `source` (`&'static str`) — Static source string containing Project Fluent dictionary syntax.
///
/// # Example
///
/// ```rust
/// use moongraphql_builder::{register_resource, set_global_locale, tr};
///
/// register_resource("ru", "custom-err = Ошибка в запросе {$query}!");
/// set_global_locale("ru");
///
/// let msg = tr!("custom-err", "query" => "characters");
/// assert_eq!(msg, "Ошибка в запросе characters!");
/// ```
pub fn register_resource(lang: &str, source: &'static str) {
    let resource = match FluentResource::try_new(source.to_string()) {
        Ok(res) => res,
        Err((res, errors)) => {
            log::error!(
                "Syntax errors parsing external FTL for locale '{}': {:?}",
                lang,
                errors
            );
            res
        }
    };

    let short_lang = lang.split('-').next().unwrap_or(lang).to_lowercase();

    if let Ok(mut bundles) = BUNDLES.write() {
        if let Some(bundle) = bundles.get_mut(&short_lang) {
            let _ = bundle.add_resource_overriding(resource);
        } else {
            let lang_id: LanguageIdentifier = match lang.parse() {
                Ok(id) => id,
                Err(_) => DEFAULT_LOCALE.parse().expect("Failed fallback lang_id"),
            };

            let mut bundle = FluentBundle::new_concurrent(vec![lang_id]);
            bundle.set_use_isolating(false);
            let _ = bundle.add_resource(resource);
            bundles.insert(short_lang, bundle);
        }
    }
}

/// Sets the process-wide global default locale override.
///
/// # Arguments
///
/// * `locale` ([`&str`]) — Target language code (e.g. `"en"` or `"ru"`).
///
/// # Example
///
/// ```rust
/// use moongraphql_builder::set_global_locale;
///
/// set_global_locale("ru");
/// println!("Global locale switched to Russian");
/// ```
pub fn set_global_locale(locale: &str) {
    if let Ok(mut global) = GLOBAL_LOCALE.write() {
        *global = locale.to_lowercase();
    }
}

/// Resolves the currently active locale considering the priority hierarchy.
///
/// # Returns
///
/// Two-letter normalized language code string (`"en"` or `"ru"`).
fn get_current_locale() -> String {
    #[cfg(feature = "tokio")]
    {
        if let Ok(task_locale) = TASK_LOCALE.try_with(|l| l.clone()) {
            if !task_locale.is_empty() {
                return task_locale;
            }
        }
    }

    if let Ok(global) = GLOBAL_LOCALE.read() {
        if !global.is_empty() {
            return global.clone();
        }
    }

    sys_locale::get_locale()
        .and_then(|l| l.split('-').next().map(|s| s.to_string()))
        .unwrap_or_else(|| DEFAULT_LOCALE.to_string())
}

/// Internal helper function to retrieve and format a localized message pattern.
///
/// # Arguments
///
/// * `bundle` (`&ConcurrentBundle`) — Active compiled Fluent dictionary bundle.
/// * `key` ([`&str`]) — Message identifier key.
/// * `args` ([`Option<&FluentArgs>`]) — Optional variable arguments for template interpolation.
///
/// # Returns
///
/// Returns `Some(String)` if `key` exists in `bundle`, or `None` otherwise.
fn format_message(
    bundle: &ConcurrentBundle,
    key: &str,
    args: Option<&FluentArgs>,
) -> Option<String> {
    let msg = bundle.get_message(key)?;
    let pattern = msg.value()?;
    let mut errors = vec![];
    let formatted = bundle.format_pattern(pattern, args, &mut errors);

    if formatted.contains("\\n") {
        Some(formatted.replace("\\n", "\n"))
    } else {
        Some(formatted.into_owned())
    }
}

/// Translates and interpolates a localized message by its dictionary key.
///
/// Resolves the active locale through the priority cascade. Automatically falls back
/// to the canonical English bundle if the active locale lacks the key.
///
/// # Arguments
///
/// * `key` ([`&str`]) — Unique message identifier.
/// * `args` ([`Option<&FluentArgs>`]) — Optional interpolation variables.
///
/// # Returns
///
/// Formatted localized message string. Returns `"[key]"` if the key is missing across all bundles.
///
/// # Example
///
/// ```rust
/// use moongraphql_builder::i18n::translate;
///
/// let msg = translate("err-gql-validation", None);
/// println!("Validation message: {}", msg);
/// ```
pub fn translate(key: &str, args: Option<&FluentArgs>) -> String {
    let locale = get_current_locale();

    if let Ok(bundles) = BUNDLES.read() {
        let active_locale = if bundles.contains_key(&locale) {
            locale.as_str()
        } else {
            FALLBACK_LOCALE
        };

        if let Some(bundle) = bundles.get(active_locale) {
            if let Some(formatted) = format_message(bundle, key, args) {
                return formatted;
            }
        }

        if active_locale != FALLBACK_LOCALE {
            if let Some(fallback) = bundles.get(FALLBACK_LOCALE) {
                if let Some(formatted) = format_message(fallback, key, args) {
                    return formatted;
                }
            }
        }
    }

    format!("[{}]", key)
}

/// Primary declarative macro for formatting and interpolating `moongraphql_builder` messages.
///
/// # Syntax
///
/// * `tr!("key")` — Static key lookup without parameters.
/// * `tr!("key", "param" => value)` — Message with dynamic interpolation arguments.
///
/// # Examples
///
/// ```rust
/// use moongraphql_builder::tr;
///
/// // Dynamic argument interpolation
/// let error = tr!("err-val-range", "arg" => "limit", "query" => "animes", "range" => "1..=50", "got" => 100);
/// println!("{}", error);
/// ```
#[macro_export]
macro_rules! tr {
    ($key:expr) => {
        $crate::i18n::translate($key, None)
    };
    ($key:expr, $($name:expr => $val:expr),+ $(,)?) => {
        {
            let mut args = $crate::i18n::FluentArgs::new();
            $( args.set($name, $val.to_string()); )+
            $crate::i18n::translate($key, Some(&args))
        }
    };
}