sdforge 0.5.0-rc.2

Multi-protocol SDK framework with unified macro configuration
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! ICU4X-backed internationalization formatting for HTTP responses.
//!
//! Provides locale-aware number formatting, date formatting, plural rules,
//! string collation, and **Accept-Language HTTP header parsing** via the
//! `icu` crate (ICU4X 2.x). Useful for generating locale-sensitive HTTP
//! error messages (e.g. "1 error" vs "2 errors"), formatting status codes
//! and counters in responses, displaying timestamps, sorting HTTP headers
//! by locale-specific collation rules, and selecting the best locale from
//! an incoming `Accept-Language` header.
//!
//! Enable with the `i18n` cargo feature:
//! ```toml
//! [dependencies]
//! sdforge = { version = "...", features = ["i18n"] }
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use sdforge::i18n::{HttpI18nFormatter, parse_accept_language};
//!
//! // From a direct locale tag
//! let fmt = HttpI18nFormatter::new("en-US")?;
//! let msg = fmt.format_error_message(404, 2)?; // "HTTP 404: 2 errors (Other)"
//!
//! // From an Accept-Language header
//! let fmt = HttpI18nFormatter::from_accept_language("en-US,en;q=0.9,zh-CN;q=0.8")?;
//! let locales = parse_accept_language("en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
//! assert_eq!(locales, vec!["en-US", "en", "zh-CN", "zh"]);
//! ```

// ============================================================================
// Translation registry — always compiled (no ICU4X dependency).
//
// Provides a global (locale, i18n_key) → translation lookup used by
// protocol consumption points (MCP, CLI, OpenAPI, gRPC) to translate
// proc-macro attribute `description` strings at runtime.
// ============================================================================

use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};

/// Global translation state: active locale + translation map.
struct TranslationRegistry {
    locale: String,
    translations: HashMap<(String, String), String>,
}

static REGISTRY: LazyLock<Mutex<TranslationRegistry>> = LazyLock::new(|| {
    Mutex::new(TranslationRegistry {
        locale: String::new(),
        translations: HashMap::new(),
    })
});

/// Register a translation for a specific locale and i18n key.
///
/// Call this at application startup to populate the translation table.
/// Protocol consumption points (MCP tool descriptions, CLI `--help`,
/// OpenAPI specs, gRPC metadata) look up translations via
/// [`translate_or_fallback`] at build time.
///
/// # Examples
///
/// ```rust,ignore
/// use sdforge::i18n::{register_translation, set_locale};
///
/// register_translation("zh-CN", "forge.embed.description",
///     "为输入文本生成嵌入向量");
/// set_locale("zh-CN");
/// ```
pub fn register_translation(locale: &str, key: &str, value: &str) {
    let mut reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
    reg.translations
        .insert((locale.to_string(), key.to_string()), value.to_string());
}

/// Set the active locale for translation lookups.
///
/// Defaults to `"en"` when no locale has been set. Protocol consumption
/// points call [`translate_or_fallback`] which uses this locale to
/// resolve i18n keys.
pub fn set_locale(locale: &str) {
    let mut reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
    reg.locale = locale.to_string();
}

/// Get the currently active locale.
pub fn get_locale() -> String {
    let reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
    if reg.locale.is_empty() {
        "en".to_string()
    } else {
        reg.locale.clone()
    }
}

/// Look up a translation for the active locale, falling back to `default`
/// when no translation is found or `i18n_key` is `None`.
///
/// The active locale is only initialized by `set_locale`. Before the first
/// `set_locale` call the registry has no active locale and this function
/// returns `default` directly without consulting the table — translations
/// registered for `"en"` stay dormant until `set_locale("en")` is called.
///
/// This is the function called by protocol consumption points — MCP
/// `build_tool_model` and CLI `build_subcommand` are wired up today
/// (OpenAPI `build` and the gRPC info response are planned) — to translate
/// compile-time `description` literals at runtime.
///
/// # Examples
///
/// ```rust,ignore
/// use sdforge::i18n::translate_or_fallback;
///
/// // Without any translation registered:
/// assert_eq!(
///     translate_or_fallback("Generate embedding", Some("forge.embed")),
///     "Generate embedding"  // fallback to default
/// );
/// ```
pub fn translate_or_fallback(default: &str, i18n_key: Option<&str>) -> String {
    let key = match i18n_key {
        Some(k) if !k.is_empty() => k,
        _ => return default.to_string(),
    };
    let locale = {
        let reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
        if reg.locale.is_empty() {
            return default.to_string();
        }
        reg.locale.clone()
    };
    let reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
    reg.translations
        .get(&(locale, key.to_string()))
        .cloned()
        .unwrap_or_else(|| default.to_string())
}

/// Clear all registered translations and reset the locale.
///
/// Primarily useful for testing.
pub fn clear_translations() {
    let mut reg = REGISTRY.lock().unwrap_or_else(|e| e.into_inner());
    reg.translations.clear();
    reg.locale.clear();
}

// ============================================================================
// ICU4X-backed HTTP formatter — only compiled with the `i18n` feature.
// ============================================================================

#[cfg(feature = "i18n")]
#[cfg(test)]
use std::cmp::Ordering;

#[cfg(feature = "i18n")]
use icu::collator::CollatorBorrowed;
#[cfg(feature = "i18n")]
use icu::decimal::DecimalFormatter;
#[cfg(feature = "i18n")]
use icu::locale::Locale;
#[cfg(feature = "i18n")]
use icu::plurals::PluralRules;
#[cfg(feature = "i18n")]
use thiserror::Error;

/// Default quality value for Accept-Language entries without an explicit `q`.
#[cfg(feature = "i18n")]
pub(crate) const DEFAULT_Q_VALUE: f64 = 1.0;

#[cfg(feature = "i18n")]
mod i18n_impl;
#[cfg(feature = "i18n")]
pub use i18n_impl::parse_accept_language;

/// Errors returned by [`HttpI18nFormatter`] operations.
#[cfg(feature = "i18n")]
#[derive(Debug, Error)]
pub enum I18nError {
    /// BCP-47 locale string could not be parsed.
    #[error("invalid locale '{input}': {reason}")]
    InvalidLocale {
        /// The locale string that failed to parse.
        input: String,
        /// The parse error reason.
        reason: String,
    },
    /// Number value could not be formatted (e.g. NaN, Infinity, or parse failure).
    #[error("invalid number '{input}': {reason}")]
    InvalidNumber {
        /// The number string that failed to format.
        input: String,
        /// The formatting error reason.
        reason: String,
    },
    /// Date component out of range or otherwise invalid.
    #[error("date error: {0}")]
    DateError(String),
    /// Underlying ICU4X data or formatting failure.
    #[error("formatting error: {0}")]
    FormatError(String),
    /// Accept-Language header contained no usable locale.
    #[error("no valid locale found in Accept-Language header '{header}'")]
    NoValidLocale {
        /// The original Accept-Language header value.
        header: String,
    },
}

/// Locale-aware HTTP formatter backed by ICU4X compiled data.
///
/// Construct with [`HttpI18nFormatter::new`] using a BCP-47 locale tag
/// (e.g. `"en-US"`, `"zh-CN"`), or with [`HttpI18nFormatter::from_accept_language`]
/// to select the best locale from an HTTP `Accept-Language` header. All
/// formatters are created eagerly so that repeated formatting calls are
/// allocation-light.
#[cfg(feature = "i18n")]
pub struct HttpI18nFormatter {
    locale: Locale,
    decimal_formatter: DecimalFormatter,
    plural_rules: PluralRules,
    collator: CollatorBorrowed<'static>,
}

// ============================================================================
// Translation registry tests (always compiled, no ICU4X needed)
// ============================================================================

#[cfg(test)]
mod translation_tests {
    use super::*;

    /// `REGISTRY` 的逻辑状态(locale + 翻译表)是进程级全局的,Mutex 只保证
    /// 内存安全、不隔离逻辑状态;并行 harness 下各用例互相踩踏(实测
    /// `cargo test --lib translation_tests` 约 4/10 概率失败)→ 以进程级锁
    /// 将触碰全局状态的用例串行化。锁顺序恒为 `REGISTRY_LOCK` → `REGISTRY`
    /// (用例内先取本锁再调 `clear_translations` 等),无反向获取,无死锁面。
    static REGISTRY_LOCK: Mutex<()> = Mutex::new(());

    fn registry_guard() -> std::sync::MutexGuard<'static, ()> {
        REGISTRY_LOCK.lock().unwrap_or_else(|e| e.into_inner())
    }

    #[test]
    fn test_translate_or_fallback_no_key() {
        assert_eq!(translate_or_fallback("default text", None), "default text");
    }

    #[test]
    fn test_translate_or_fallback_empty_key() {
        assert_eq!(
            translate_or_fallback("default text", Some("")),
            "default text"
        );
    }

    #[test]
    fn test_translate_or_fallback_no_locale_set() {
        let _guard = registry_guard();
        clear_translations();
        assert_eq!(
            translate_or_fallback("default text", Some("some.key")),
            "default text"
        );
    }

    #[test]
    fn test_translate_or_fallback_with_translation() {
        let _guard = registry_guard();
        clear_translations();
        register_translation("zh-CN", "forge.embed", "生成嵌入向量");
        set_locale("zh-CN");
        assert_eq!(
            translate_or_fallback("Generate embedding", Some("forge.embed")),
            "生成嵌入向量"
        );
        clear_translations();
    }

    #[test]
    fn test_translate_or_fallback_missing_translation() {
        let _guard = registry_guard();
        clear_translations();
        set_locale("zh-CN");
        assert_eq!(
            translate_or_fallback("Generate embedding", Some("forge.nonexistent")),
            "Generate embedding"
        );
        clear_translations();
    }

    #[test]
    fn test_translate_or_fallback_wrong_locale() {
        let _guard = registry_guard();
        clear_translations();
        register_translation("zh-CN", "forge.embed", "生成嵌入向量");
        set_locale("ja-JP");
        // Translation registered for zh-CN, but active locale is ja-JP
        assert_eq!(
            translate_or_fallback("Generate embedding", Some("forge.embed")),
            "Generate embedding"
        );
        clear_translations();
    }

    #[test]
    fn test_set_and_get_locale() {
        let _guard = registry_guard();
        clear_translations();
        assert_eq!(get_locale(), "en"); // default
        set_locale("zh-CN");
        assert_eq!(get_locale(), "zh-CN");
        clear_translations();
    }

    #[test]
    fn test_clear_translations() {
        let _guard = registry_guard();
        register_translation("en", "key1", "value1");
        set_locale("en");
        assert_eq!(translate_or_fallback("default", Some("key1")), "value1");
        clear_translations();
        assert_eq!(translate_or_fallback("default", Some("key1")), "default");
        assert_eq!(get_locale(), "en"); // default after clear
    }

    #[test]
    fn test_multiple_locales() {
        let _guard = registry_guard();
        clear_translations();
        register_translation("zh-CN", "greet", "你好");
        register_translation("ja-JP", "greet", "こんにちは");

        set_locale("zh-CN");
        assert_eq!(translate_or_fallback("Hello", Some("greet")), "你好");

        set_locale("ja-JP");
        assert_eq!(translate_or_fallback("Hello", Some("greet")), "こんにちは");

        clear_translations();
    }
}

// ============================================================================
// ICU4X HTTP formatter tests — only compiled with the `i18n` feature.
// ============================================================================

#[cfg(all(test, feature = "i18n"))]
mod tests {
    use super::*;

    #[test]
    fn test_locale_parsing_en() {
        let fmt = HttpI18nFormatter::new("en-US");
        assert!(fmt.is_ok(), "en-US should parse successfully");
    }

    #[test]
    fn test_locale_parsing_zh() {
        let fmt = HttpI18nFormatter::new("zh-CN");
        assert!(fmt.is_ok(), "zh-CN should parse successfully");
    }

    #[test]
    fn test_invalid_locale() {
        let result = HttpI18nFormatter::new("not-a-valid-locale!!!");
        assert!(result.is_err(), "invalid locale should return error");
        match result.err().unwrap() {
            I18nError::InvalidLocale { input, .. } => assert_eq!(input, "not-a-valid-locale!!!"),
            other => panic!("expected InvalidLocale, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_accept_language() {
        let locales = parse_accept_language("en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
        assert_eq!(
            locales,
            vec!["en-US", "en", "zh-CN", "zh"],
            "locales should be sorted by q-value descending: got {locales:?}"
        );
    }

    #[test]
    fn test_parse_accept_language_default_q() {
        // Entry without q= gets default 1.0
        let locales = parse_accept_language("fr,en;q=0.9");
        assert_eq!(
            locales,
            vec!["fr", "en"],
            "entry without q= should get default 1.0: got {locales:?}"
        );
    }

    #[test]
    fn test_parse_accept_language_q_zero_excluded() {
        // q=0 means "not acceptable" per RFC 7231
        let locales = parse_accept_language("en;q=0,fr");
        assert_eq!(
            locales,
            vec!["fr"],
            "q=0 entries should be excluded: got {locales:?}"
        );
    }

    #[test]
    fn test_parse_accept_language_empty() {
        let locales = parse_accept_language("");
        assert!(locales.is_empty(), "empty header should return empty vec");
    }

    #[test]
    fn test_from_accept_language() {
        let fmt = HttpI18nFormatter::from_accept_language("en-US,en;q=0.9,zh-CN;q=0.8");
        assert!(fmt.is_ok(), "should create formatter from valid header");
    }

    #[test]
    fn test_from_accept_language_fallback() {
        // First locale invalid, second valid
        let fmt = HttpI18nFormatter::from_accept_language("not-a-locale!!!,en-US");
        assert!(fmt.is_ok(), "should fall back to valid locale");
    }

    #[test]
    fn test_from_accept_language_all_invalid() {
        let result = HttpI18nFormatter::from_accept_language("not-a-locale!!!");
        assert!(result.is_err(), "all-invalid header should error");
        match result.err().unwrap() {
            I18nError::NoValidLocale { header, .. } => {
                assert_eq!(header, "not-a-locale!!!");
            }
            other => panic!("expected NoValidLocale, got {other:?}"),
        }
    }

    #[test]
    fn test_format_error_message_singular() {
        let fmt = HttpI18nFormatter::new("en").expect("en locale");
        let msg = fmt.format_error_message(404, 1).expect("error message");
        assert!(
            msg.contains("One"),
            "count=1 should contain plural category One: got '{msg}'"
        );
        assert!(
            msg.contains("error"),
            "singular form should use 'error': got '{msg}'"
        );
        assert!(
            msg.contains("404"),
            "message should contain status code: got '{msg}'"
        );
    }

    #[test]
    fn test_format_error_message_plural() {
        let fmt = HttpI18nFormatter::new("en").expect("en locale");
        let msg = fmt.format_error_message(404, 2).expect("error message");
        assert!(
            msg.contains("Other"),
            "count=2 should contain plural category Other: got '{msg}'"
        );
        assert!(
            msg.contains("errors"),
            "plural form should use 'errors': got '{msg}'"
        );
    }

    #[test]
    fn test_format_number_en() {
        let fmt = HttpI18nFormatter::new("en-US").expect("en-US locale");
        let result = fmt.format_number(1_234_567.89_f64).expect("format number");
        assert!(
            result.contains(','),
            "en-US number should contain thousands separator: got '{result}'"
        );
        assert!(
            result.contains('.'),
            "en-US number should contain decimal point: got '{result}'"
        );
    }

    #[test]
    fn test_format_number_not_finite() {
        let fmt = HttpI18nFormatter::new("en-US").expect("en-US locale");
        assert!(fmt.format_number(f64::NAN).is_err());
        assert!(fmt.format_number(f64::INFINITY).is_err());
    }

    #[test]
    fn test_format_timestamp() {
        let fmt = HttpI18nFormatter::new("en-US").expect("en-US locale");
        let result = fmt.format_timestamp(2026, 7, 11).expect("format timestamp");
        assert!(
            result.contains("2026"),
            "timestamp should contain year: got '{result}'"
        );
        assert!(
            !result.is_empty(),
            "timestamp should be non-empty: got '{result}'"
        );
    }

    #[test]
    fn test_compare_headers() {
        let fmt = HttpI18nFormatter::new("en").expect("en locale");
        assert_eq!(
            fmt.compare_headers("apple", "banana").expect("compare"),
            Ordering::Less,
            "apple < banana"
        );
        assert_eq!(
            fmt.compare_headers("banana", "apple").expect("compare"),
            Ordering::Greater,
            "banana > apple"
        );
        assert_eq!(
            fmt.compare_headers("apple", "apple").expect("compare"),
            Ordering::Equal,
            "apple == apple"
        );
    }

    #[test]
    fn test_format_timestamp_invalid_date() {
        let fmt = HttpI18nFormatter::new("en-US").expect("en-US locale");
        assert!(
            fmt.format_timestamp(2026, 13, 1).is_err(),
            "month=13 should return date error"
        );
        assert!(
            fmt.format_timestamp(2026, 2, 30).is_err(),
            "Feb 30 should return date error"
        );
    }

    #[test]
    fn test_parse_accept_language_whitespace_entries() {
        let locales = parse_accept_language("  ,  en  ;  q=0.9  ,  ");
        assert_eq!(
            locales,
            vec!["en"],
            "should handle whitespace-only and trimmed entries: got {locales:?}"
        );
    }

    #[test]
    fn test_parse_accept_language_malformed_q() {
        let locales = parse_accept_language("fr;q=abc,en;q=0.5");
        assert_eq!(
            locales,
            vec!["fr", "en"],
            "malformed q= should fall back to default 1.0: got {locales:?}"
        );
    }

    #[test]
    fn test_parse_accept_language_q_zero_mixed() {
        let locales = parse_accept_language("en;q=0,fr;q=0.5,de");
        assert_eq!(
            locales,
            vec!["de", "fr"],
            "q=0 excluded, others sorted by q: got {locales:?}"
        );
    }
}