moonclient 0.1.1

Resilient, enterprise-grade HTTP client engine with autonomous Token Bucket rate limiting, lifecycle hooks, and Project Fluent i18n.
Documentation
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
//! Dynamic internationalization (i18n) and diagnostic localization engine powered by Project Fluent.
//!
//! Provides a thread-safe message formatting environment, multi-tier runtime locale resolution,
//! task-isolated execution contexts via Tokio Task-Local storage, and an extensible registry
//! for external downstream crate translation bundles.
//!
//! ### Multi-Tier Locale Resolution Hierarchy
//!
//! When resolving the active translation, the engine queries four priority tiers in descending order:
//!
//! ```text
//! 1. Tokio Task-Local Context (TASK_LOCALE)  <-- Isolated per asynchronous task (e.g. per-user bot requests)
//!                    │
//!                    ▼ (if absent or empty)
//! 2. Global Process Override (GLOBAL_LOCALE) <-- Set via set_global_locale("ru") (CLI / tests)
//!                    │
//!                    ▼ (if absent or empty)
//! 3. Host OS Regional Settings (sys-locale)  <-- Discovered from operating system environment
//!                    │
//!                    ▼ (if unsupported)
//! 4. Canonical Fallback Locale ("en")        <-- Guaranteed to contain 100% of all keys
//! ```
//!
//! ### Unicode BiDi Isolation Suppression
//!
//! By default, Project Fluent injects invisible Unicode First Strong directional isolation
//! characters (`\u{2068}` and `\u{2069}`) around interpolated terms. While helpful in mixed-script
//! desktop GUIs, these markers corrupt Markdown syntax, break HTML tags, and invalidate URL paths.
//! 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 moonclient::{set_global_locale, tr};
//!
//! // 1. Format in default locale (en)
//! let msg_en = tr!("api-error", "code" => 404, "message" => "Not Found");
//! println!("English: {}", msg_en);
//!
//! // 2. Switch global locale to Russian
//! set_global_locale("ru");
//! let msg_ru = tr!("api-error", "code" => 404, "message" => "Не найдено");
//! println!("Russian: {}", 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;

/// Primary default language code (`"en"`) applied when requested locales are unavailable.
const DEFAULT_LOCALE: &str = "en";

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

// Tokio task-local storage macro. Allows isolating language context
// across independent asynchronous execution tasks (e.g., individual user locales in bots or web requests).
tokio::task_local! {
    /// Asynchronous task-local storage for isolating locale resolution per task.
    ///
    /// Enables multi-user applications (such as Telegram bots or microservices)
    /// to handle concurrent requests in different languages simultaneously.
    ///
    /// # Example
    ///
    /// ```rust
    /// use moonclient::i18n::{TASK_LOCALE, translate};
    ///
    /// # async fn doc_example() {
    /// // Run an async task isolated to the Russian locale
    /// TASK_LOCALE.scope("ru".to_string(), async {
    ///     let localized = moonclient::tr!("err-network", "error" => "Timeout");
    ///     println!("Task-isolated Russian error: {}", localized);
    /// }).await;
    /// # }
    /// ```
    pub static TASK_LOCALE: String;
}

/// Global process-wide language context for CLI applications, monoliths, and test suites.
static GLOBAL_LOCALE: RwLock<String> = RwLock::new(String::new());

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

/// Global lazy-initialized storage of compiled language dictionaries protected by an [`std::sync::RwLock`].
///
/// Compiles the embedded core network translations (`en-US` and `ru-RU`) upon first access.
static BUNDLES: LazyLock<RwLock<HashMap<String, ConcurrentBundle>>> = LazyLock::new(|| {
    let mut bundles = HashMap::new();

    // Compile embedded core translations for moonclient
    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 instantiate an isolated, thread-safe Fluent bundle.
///
/// # Implementation Details
///
/// 1. Parses raw FTL source text into a [`FluentResource`](https://docs.rs/fluent/latest/fluent/struct.FluentResource.html).
/// 2. Parses the BCP-47 language tag into a [`LanguageIdentifier`](https://docs.rs/unic-langid/latest/unic_langid/struct.LanguageIdentifier.html).
/// 3. Disables bidirectional text isolation markers via `set_use_isolating(false)` to prevent string corruption.
/// 4. Registers the resource into the bundle.
///
/// # Arguments
///
/// * `lang` ([`&str`]) — BCP-47 language tag (e.g. `"en-US"`, `"ru-RU"`).
/// * `source` ([`&str`]) — Raw FTL resource syntax text.
///
/// # Returns
///
/// Returns a compiled [`ConcurrentBundle`] ready for message formatting.
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]);

    // Disable invisible Unicode BiDi formatting characters (\u{2068} and \u{2069})
    bundle.set_use_isolating(false);

    bundle
        .add_resource(resource)
        .expect("Failed to add resource to core bundle");

    bundle
}

/// Registers an external FTL resource bundle from a dependent downstream crate.
///
/// Allows external libraries (such as `shikimori_api` or domain plugins) to inject
/// their own localization dictionaries into the shared engine pool without exposing
/// direct dependencies on the underlying Fluent crates.
///
/// If the target language already exists in memory, new keys will extend the bundle,
/// overriding duplicate keys. If absent, a new bundle is dynamically allocated.
///
/// # Arguments
///
/// * `lang` ([`&str`]) — BCP-47 language identifier tag (e.g. `"en"`, `"ru"`, `"ja-JP"`).
/// * `source` (`&'static str`) — Static source string containing Project Fluent dictionary definitions.
///
/// # Example
///
/// ```rust
/// use moonclient::{register_resource, set_global_locale, tr};
///
/// // Register custom translations from an external domain crate
/// register_resource("en", "welcome-msg = Welcome to our service, {$name}!");
/// register_resource("ru", "welcome-msg = Добро пожаловать, {$name}!");
///
/// set_global_locale("ru");
/// let greeting = tr!("welcome-msg", "name" => "Dina");
/// assert_eq!(greeting, "Добро пожаловать, Dina!");
/// ```
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 encountered while parsing external FTL resource for locale '{}': {:?}",
                lang,
                errors
            );
            res
        }
    };

    // Normalize the language code to a compact two-letter map key
    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) {
            // Safely extend the existing bundle with new keys, overriding duplicates
            let _ = bundle.add_resource_overriding(resource);
        } else {
            // Construct a new language bundle for a previously unregistered locale
            let lang_id: LanguageIdentifier = match lang.parse() {
                Ok(id) => id,
                Err(_) => {
                    log::error!(
                        "Failed to parse language identifier '{}', falling back to default locale",
                        lang
                    );
                    DEFAULT_LOCALE
                        .parse()
                        .expect("Failed to initialize fallback locale")
                }
            };

            let mut bundle = FluentBundle::new_concurrent(vec![lang_id]);
            bundle.set_use_isolating(false);

            if let Err(errors) = bundle.add_resource(resource) {
                log::error!(
                    "Errors attaching FTL resource to new bundle '{}': {:?}",
                    short_lang,
                    errors
                );
            }

            bundles.insert(short_lang, bundle);
        }
    } else {
        log::error!("Failed to acquire write lock for FTL resource registration");
    }
}

/// Sets the process-wide global default locale override.
///
/// Overrides host OS regional settings for monolithic runtimes, CLI applications,
/// and automated integration test suites where task-local isolation is unnecessary.
///
/// # Arguments
///
/// * `locale` ([`&str`]) — Target language code (e.g. `"en"`, `"ru"`).
///
/// # Example
///
/// ```rust
/// use moonclient::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();
    }
}

/// Normalizes an incoming raw language tag string to the core engine standard.
///
/// Inspects language tag prefixes and maps them to primary two-letter forms,
/// falling back to `DEFAULT_LOCALE` (`"en"`) if no match is found.
///
/// # Arguments
///
/// * `code` ([`Option<&str>`]) — Optional raw language code string (e.g. `Some("ru-RU")`, `Some("en_US")`).
///
/// # Returns
///
/// Normalized two-letter lowercase language identifier string (`"en"` or `"ru"`).
///
/// # Example
///
/// ```rust
/// use moonclient::i18n::normalize_language_code;
///
/// assert_eq!(normalize_language_code(Some("ru-RU")), "ru");
/// assert_eq!(normalize_language_code(Some("en-US")), "en");
/// assert_eq!(normalize_language_code(None), "en");
/// ```
pub fn normalize_language_code(code: Option<&str>) -> String {
    match code {
        Some(c) if c.to_lowercase().starts_with("en") => "en".to_string(),
        Some(c) if c.to_lowercase().starts_with("ru") => "ru".to_string(),
        _ => DEFAULT_LOCALE.to_string(),
    }
}

/// Resolves the currently active locale code based on the priority hierarchy.
///
/// # Implementation Details
///
/// 1. Inspects the active [`TASK_LOCALE`] Tokio context. If set and non-empty, returns it immediately.
/// 2. Inspects [`GLOBAL_LOCALE`]. If configured, returns the global override string.
/// 3. Queries host operating system settings via [`sys_locale::get_locale`](https://docs.rs/sys-locale/latest/sys_locale/fn.get_locale.html).
/// 4. Defaults to [`DEFAULT_LOCALE`] (`"en"`).
///
/// # Returns
///
/// A normalized two-letter language code string representing the current execution context.
fn get_current_locale() -> String {
    // Check Tokio task-local context
    let task_locale = TASK_LOCALE.try_with(|locale| locale.clone()).ok();
    if let Some(locale) = task_locale {
        if !locale.is_empty() {
            return locale;
        }
    }

    // Check process-wide global override
    if let Ok(global) = GLOBAL_LOCALE.read() {
        if !global.is_empty() {
            return global.clone();
        }
    }

    // Query host operating system locale
    sys_locale::get_locale()
        .and_then(|l| l.split('-').next().map(|s| s.to_string()))
        .unwrap_or_else(|| DEFAULT_LOCALE.to_string())
}

/// Retrieves, interpolates, and formats a localized message pattern from a bundle.
///
/// # Implementation Details
///
/// Looks up `key` in the bundle. If present, interpolates arguments via
/// [`FluentBundle::format_pattern`](https://docs.rs/fluent/latest/fluent/bundle/struct.FluentBundle.html#method.format_pattern).
/// Replaces escaped `\n` sequences with real newline characters only when detected,
/// minimizing redundant heap allocations.
///
/// # Arguments
///
/// * `bundle` (`&ConcurrentBundle`) — Reference to the target compiled Fluent bundle.
/// * `key` ([`&str`]) — Unique message identifier defined in the FTL dictionary.
/// * `args` ([`Option<&FluentArgs>`]) — Optional variable arguments for template interpolation.
///
/// # Returns
///
/// Returns `Some(String)` containing the formatted text, or `None` if `key` does not exist in `bundle`.
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);

    // Perform replacement only when escaped newlines are actually present
    if formatted.contains("\\n") {
        Some(formatted.replace("\\n", "\n"))
    } else {
        Some(formatted.into_owned())
    }
}

/// Translates and formats a localized message by its dictionary key.
///
/// Resolves the active locale through the multi-tier hierarchy, locates the target message,
/// and interpolates variables. If the active locale lacks the requested key, it automatically
/// falls back to the canonical `FALLBACK_LOCALE` bundle.
///
/// If the key is missing across all registered dictionaries, returns the raw key wrapped
/// in brackets (e.g. `"[missing-key]"`).
///
/// # Arguments
///
/// * `key` ([`&str`]) — Unique message identifier defined in FTL dictionaries.
/// * `args` ([`Option<&FluentArgs>`]) — Optional collection of named interpolation arguments.
///
/// # Returns
///
/// Formatted, localized string ready for logging or display.
///
/// # Example
///
/// ```rust
/// use moonclient::i18n::translate;
///
/// let message = translate("expect-invalid-base-url", None);
/// println!("Resolved message: {}", message);
/// ```
pub fn translate(key: &str, args: Option<&FluentArgs>) -> String {
    let locale = get_current_locale();

    if let Ok(bundles) = BUNDLES.read() {
        // Determine the target locale considering loaded bundles
        let active_locale = if bundles.contains_key(&locale) {
            locale.as_str()
        } else if bundles.contains_key(DEFAULT_LOCALE) {
            DEFAULT_LOCALE
        } else {
            FALLBACK_LOCALE
        };

        // Attempt formatting in the active locale
        if let Some(bundle) = bundles.get(active_locale) {
            if let Some(formatted) = format_message(bundle, key, args) {
                return formatted;
            }
        }

        // Fallback to the canonical locale if key was missing in active locale
        if active_locale != FALLBACK_LOCALE {
            if let Some(fallback_bundle) = bundles.get(FALLBACK_LOCALE) {
                if let Some(formatted) = format_message(fallback_bundle, key, args) {
                    return formatted;
                }
            }
        }
    }

    // Return the key itself if no translation could be resolved
    format!("[{}]", key)
}

/// Primary declarative macro for translating and interpolating localized messages.
///
/// Provides a concise syntax for formatting static translation keys as well as
/// templates requiring dynamic, named arguments implementing [`std::fmt::Display`].
///
/// # Syntax
///
/// * `tr!("key")` — Static key lookup without arguments.
/// * `tr!("key", "param1" => val1, "param2" => val2)` — Interpolated message with dynamic named parameters.
///
/// # Examples
///
/// ### Static Key Translation
/// ```rust
/// use moonclient::tr;
///
/// let err_msg = tr!("expect-invalid-base-url");
/// println!("Static message: {}", err_msg);
/// ```
///
/// ### Dynamic Named Argument Interpolation
/// ```rust
/// use moonclient::tr;
///
/// let error_detail = "Connection timed out";
/// let count = 3_u32;
///
/// let log_entry = tr!("err-network", "error" => error_detail, "retries" => count);
/// println!("Interpolated log entry: {}", log_entry);
/// ```
#[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))
        }
    };
}