Skip to main content

es_fluent_manager_embedded/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use es_fluent::{
4    FluentArgs, FluentLocalizer, FluentLocalizerExt, FluentLocalizerLookup, FluentMessage,
5    registry::StaticFluentMessageKey,
6};
7use es_fluent_manager_core::{FluentManager, ModuleDiscoveryError};
8use std::sync::{Arc, RwLock};
9use tracing::info;
10use unic_langid::LanguageIdentifier;
11
12#[doc(hidden)]
13pub use es_fluent::__inventory;
14
15#[doc(hidden)]
16pub use es_fluent_manager_core as __manager_core;
17
18#[doc(hidden)]
19pub use unic_langid as __unic_langid;
20
21#[cfg(feature = "macros")]
22pub use es_fluent_manager_macros::define_embedded_i18n_module as define_i18n_module;
23
24pub use es_fluent_manager_core::LocalizationError;
25
26#[derive(Debug)]
27pub enum EmbeddedInitError {
28    ModuleDiscovery(Vec<ModuleDiscoveryError>),
29    LanguageSelection(LocalizationError),
30}
31
32impl std::fmt::Display for EmbeddedInitError {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        match self {
35            Self::ModuleDiscovery(errors) => {
36                f.write_str("failed strict i18n module discovery")?;
37                for error in errors {
38                    write!(f, "\n- {error}")?;
39                }
40                Ok(())
41            },
42            Self::LanguageSelection(error) => {
43                write!(f, "failed to select the requested language: {error}")
44            },
45        }
46    }
47}
48
49impl std::error::Error for EmbeddedInitError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Self::ModuleDiscovery(_) => None,
53            Self::LanguageSelection(error) => Some(error),
54        }
55    }
56}
57
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59enum EmbeddedSelectionPolicy {
60    BestEffort,
61    Strict,
62}
63
64#[derive(Clone, Debug, Eq, PartialEq)]
65struct ActiveSelection {
66    language: LanguageIdentifier,
67    policy: EmbeddedSelectionPolicy,
68}
69
70/// Explicit embedded localization context.
71///
72/// Construct this once during application startup, keep it in application state,
73/// and pass it to code that needs localization.
74#[derive(Clone)]
75pub struct EmbeddedI18n {
76    manager: Arc<FluentManager>,
77    active_selection: Arc<RwLock<Option<ActiveSelection>>>,
78}
79
80impl EmbeddedI18n {
81    fn from_manager(manager: FluentManager) -> Self {
82        Self::from_manager_with_active_selection(manager, None)
83    }
84
85    fn from_manager_with_active_selection(
86        manager: FluentManager,
87        active_selection: Option<ActiveSelection>,
88    ) -> Self {
89        Self {
90            manager: Arc::new(manager),
91            active_selection: Arc::new(RwLock::new(active_selection)),
92        }
93    }
94
95    fn select_language_with_policy(
96        &self,
97        lang: LanguageIdentifier,
98        policy: EmbeddedSelectionPolicy,
99    ) -> Result<(), LocalizationError> {
100        // Keep the cache check, manager transition, and cache commit in one
101        // critical section shared by every clone and both selection policies.
102        let mut active_selection = self
103            .active_selection
104            .write()
105            .unwrap_or_else(|error| error.into_inner());
106        if active_selection
107            .as_ref()
108            .is_some_and(|selection| selection.language == lang && selection.policy == policy)
109        {
110            return Ok(());
111        }
112
113        info!("Changing locale to: {}", lang);
114        match policy {
115            EmbeddedSelectionPolicy::BestEffort => self.manager.select_language(&lang)?,
116            EmbeddedSelectionPolicy::Strict => self.manager.select_language_strict(&lang)?,
117        }
118        #[cfg(test)]
119        tests::after_manager_selection();
120        *active_selection = Some(ActiveSelection {
121            language: lang,
122            policy,
123        });
124        Ok(())
125    }
126
127    /// Builds an embedded context without selecting a language.
128    pub fn try_new() -> Result<Self, EmbeddedInitError> {
129        FluentManager::try_new_with_discovered_modules()
130            .map(Self::from_manager)
131            .map_err(EmbeddedInitError::ModuleDiscovery)
132    }
133
134    /// Builds an embedded context and selects the initial active language.
135    pub fn try_new_with_language<L: Into<LanguageIdentifier>>(
136        lang: L,
137    ) -> Result<Self, EmbeddedInitError> {
138        let lang = lang.into();
139        let manager = FluentManager::try_new_with_discovered_modules()
140            .map_err(EmbeddedInitError::ModuleDiscovery)?;
141        manager
142            .select_language(&lang)
143            .map_err(EmbeddedInitError::LanguageSelection)?;
144        Ok(Self::from_manager_with_active_selection(
145            manager,
146            Some(ActiveSelection {
147                language: lang,
148                policy: EmbeddedSelectionPolicy::BestEffort,
149            }),
150        ))
151    }
152
153    /// Builds an embedded context and selects the initial active language,
154    /// failing if any runtime module rejects the requested locale.
155    pub fn try_new_with_language_strict<L: Into<LanguageIdentifier>>(
156        lang: L,
157    ) -> Result<Self, EmbeddedInitError> {
158        let lang = lang.into();
159        let manager = FluentManager::try_new_with_discovered_modules()
160            .map_err(EmbeddedInitError::ModuleDiscovery)?;
161        manager
162            .select_language_strict(&lang)
163            .map_err(EmbeddedInitError::LanguageSelection)?;
164        Ok(Self::from_manager_with_active_selection(
165            manager,
166            Some(ActiveSelection {
167                language: lang,
168                policy: EmbeddedSelectionPolicy::Strict,
169            }),
170        ))
171    }
172
173    /// Selects the active language for this context.
174    ///
175    /// Concurrent selections through cloned handles are serialized. A failed
176    /// selection preserves the previously active language and selection policy.
177    pub fn select_language<L: Into<LanguageIdentifier>>(
178        &self,
179        lang: L,
180    ) -> Result<(), LocalizationError> {
181        self.select_language_with_policy(lang.into(), EmbeddedSelectionPolicy::BestEffort)
182    }
183
184    /// Selects the active language for this context and fails if any runtime
185    /// module rejects the requested locale.
186    ///
187    /// Shares the same serialized transition as [`Self::select_language`].
188    pub fn select_language_strict<L: Into<LanguageIdentifier>>(
189        &self,
190        lang: L,
191    ) -> Result<(), LocalizationError> {
192        self.select_language_with_policy(lang.into(), EmbeddedSelectionPolicy::Strict)
193    }
194
195    /// Renders a derived typed message through this context.
196    pub fn localize_message<T>(&self, message: &T) -> String
197    where
198        T: FluentMessage + ?Sized,
199    {
200        FluentLocalizerExt::localize_message(self, message)
201    }
202}
203
204impl FluentLocalizer for EmbeddedI18n {
205    fn localize<'a>(
206        &self,
207        key: StaticFluentMessageKey,
208        args: Option<&FluentArgs<'a>>,
209    ) -> Option<String> {
210        FluentManager::localize(self.manager.as_ref(), key, args.map(FluentArgs::as_raw))
211    }
212
213    fn with_lookup(&self, f: &mut dyn FnMut(&mut FluentLocalizerLookup<'_>)) {
214        FluentManager::with_lookup(self.manager.as_ref(), &mut |lookup| {
215            let mut typed_lookup = |key: StaticFluentMessageKey, args: Option<&FluentArgs<'_>>| {
216                lookup(key, args.map(FluentArgs::as_raw))
217            };
218            f(&mut typed_lookup);
219        });
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    use es_fluent_manager_core::{
227        I18nModule, I18nModuleDescriptor, I18nModuleRegistration, Localizer, ModuleData,
228    };
229    use std::cell::RefCell;
230    use std::sync::{Once, mpsc};
231    use std::time::Duration;
232    use unic_langid::langid;
233
234    thread_local! {
235        static AFTER_MANAGER_SELECTION: RefCell<Option<Box<dyn FnOnce()>>> = RefCell::new(None);
236    }
237
238    pub(super) fn after_manager_selection() {
239        let hook = AFTER_MANAGER_SELECTION.with_borrow_mut(Option::take);
240        if let Some(hook) = hook {
241            hook();
242        }
243    }
244
245    static TEST_SUPPORTED_LANGUAGES: &[LanguageIdentifier] = &[langid!("en-US"), langid!("fr")];
246    static TEST_MODULE_DATA: ModuleData = ModuleData {
247        name: "embedded-test-module",
248        owner: es_fluent_manager_core::__macro::static_domain("embedded-test-module"),
249        supported_languages: TEST_SUPPORTED_LANGUAGES,
250        domains: &[es_fluent_manager_core::ModuleDomain {
251            domain: es_fluent_manager_core::__macro::static_domain("embedded-test-module"),
252            namespaces: &[],
253        }],
254    };
255
256    struct TestModule;
257
258    struct TestLocalizer {
259        selected: LanguageIdentifier,
260    }
261
262    impl I18nModuleDescriptor for TestModule {
263        fn data(&self) -> &'static ModuleData {
264            &TEST_MODULE_DATA
265        }
266    }
267
268    impl I18nModule for TestModule {
269        fn create_localizer(
270            &self,
271            lang: &LanguageIdentifier,
272        ) -> Result<Box<dyn Localizer>, LocalizationError> {
273            if !TEST_SUPPORTED_LANGUAGES.contains(lang) {
274                return Err(LocalizationError::LanguageNotSupported(lang.clone()));
275            }
276            Ok(Box::new(TestLocalizer {
277                selected: lang.clone(),
278            }))
279        }
280    }
281
282    impl Localizer for TestLocalizer {
283        fn localize<'a>(
284            &self,
285            key: StaticFluentMessageKey,
286            _args: Option<&es_fluent_manager_core::FluentArgumentMap<'a>>,
287        ) -> Option<String> {
288            if key.owner() != "embedded-test-module" || key.domain() != "embedded-test-module" {
289                return None;
290            }
291            let selected = self.selected.to_string();
292            let value = match (selected.as_str(), key.id().as_str()) {
293                ("en-US", "hello") => "Hello",
294                ("fr", "hello") => "Bonjour",
295                _ => return None,
296            };
297
298            Some(value.to_string())
299        }
300    }
301
302    struct TestMessage;
303
304    impl FluentMessage for TestMessage {
305        fn to_fluent_string_with(
306            &self,
307            localize: &mut es_fluent::FluentMessageLookup<'_>,
308        ) -> String {
309            localize(
310                es_fluent::registry::__macro::static_message_key(
311                    "embedded-test-module",
312                    es_fluent::registry::__macro::static_domain("embedded-test-module"),
313                    es_fluent::registry::__macro::static_entry_id("hello"),
314                ),
315                None,
316            )
317        }
318    }
319
320    static TEST_MODULE: TestModule = TestModule;
321    static INVENTORY_ONCE: Once = Once::new();
322
323    crate::__inventory::submit!(&TEST_MODULE as &dyn I18nModuleRegistration);
324
325    fn force_inventory_link() {
326        INVENTORY_ONCE.call_once(|| {
327            let _ = &TEST_MODULE;
328        });
329    }
330
331    fn static_key(id: &'static str) -> StaticFluentMessageKey {
332        es_fluent::registry::__macro::static_message_key(
333            "embedded-test-module",
334            es_fluent::registry::__macro::static_domain("embedded-test-module"),
335            es_fluent::registry::__macro::static_entry_id(id),
336        )
337    }
338
339    fn select_with_policy(
340        i18n: &EmbeddedI18n,
341        language: LanguageIdentifier,
342        policy: EmbeddedSelectionPolicy,
343    ) -> Result<(), LocalizationError> {
344        match policy {
345            EmbeddedSelectionPolicy::BestEffort => i18n.select_language(language),
346            EmbeddedSelectionPolicy::Strict => i18n.select_language_strict(language),
347        }
348    }
349
350    #[test]
351    fn concurrent_selections_keep_cached_and_rendered_languages_consistent() {
352        force_inventory_link();
353        for first_policy in [
354            EmbeddedSelectionPolicy::BestEffort,
355            EmbeddedSelectionPolicy::Strict,
356        ] {
357            let second_policy = match first_policy {
358                EmbeddedSelectionPolicy::BestEffort => EmbeddedSelectionPolicy::Strict,
359                EmbeddedSelectionPolicy::Strict => EmbeddedSelectionPolicy::BestEffort,
360            };
361            let i18n = EmbeddedI18n::try_new().unwrap();
362            select_with_policy(&i18n, langid!("en-US"), first_policy).unwrap();
363            let (committed_tx, committed_rx) = mpsc::channel();
364            let (resume_tx, resume_rx) = mpsc::channel();
365            let (finished_tx, finished_rx) = mpsc::channel();
366            let timeout = Duration::from_secs(10);
367
368            std::thread::scope(|scope| {
369                let first_i18n = i18n.clone();
370                let first = scope.spawn(move || {
371                    AFTER_MANAGER_SELECTION.set(Some(Box::new(move || {
372                        committed_tx.send(()).unwrap();
373                        resume_rx.recv_timeout(timeout).unwrap();
374                    })));
375                    select_with_policy(&first_i18n, langid!("fr"), first_policy)
376                });
377                committed_rx.recv_timeout(timeout).unwrap();
378
379                // If the cache is unlocked after the manager commit, expose the old
380                // race by completing the second selection before the first caches it.
381                // Otherwise release the serialized first selection so the second runs.
382                let selection_is_locked = i18n.active_selection.try_write().is_err();
383                let second_i18n = i18n.clone();
384                let second = scope.spawn(move || {
385                    let result = select_with_policy(&second_i18n, langid!("en-US"), second_policy);
386                    finished_tx.send(()).unwrap();
387                    result
388                });
389                if selection_is_locked {
390                    resume_tx.send(()).unwrap();
391                    finished_rx.recv_timeout(timeout).unwrap();
392                } else {
393                    finished_rx.recv_timeout(timeout).unwrap();
394                    resume_tx.send(()).unwrap();
395                }
396                first.join().unwrap().unwrap();
397                second.join().unwrap().unwrap();
398            });
399
400            assert_eq!(i18n.localize_message(&TestMessage), "Hello");
401            select_with_policy(&i18n, langid!("fr"), first_policy).unwrap();
402            assert_eq!(i18n.localize_message(&TestMessage), "Bonjour");
403        }
404    }
405
406    #[test]
407    fn rejected_selections_preserve_the_active_language_and_policy() {
408        force_inventory_link();
409        let i18n = EmbeddedI18n::try_new_with_language(langid!("en-US")).unwrap();
410        let initial = i18n.active_selection.read().unwrap().clone();
411        for policy in [
412            EmbeddedSelectionPolicy::BestEffort,
413            EmbeddedSelectionPolicy::Strict,
414        ] {
415            std::assert_matches!(
416                select_with_policy(&i18n, langid!("de"), policy),
417                Err(LocalizationError::LanguageNotSupported(language)) if language == langid!("de")
418            );
419            assert_eq!(i18n.localize_message(&TestMessage), "Hello");
420            assert_eq!(*i18n.active_selection.read().unwrap(), initial);
421        }
422    }
423
424    #[test]
425    fn embedded_i18n_instances_select_languages_independently() {
426        force_inventory_link();
427        let en = EmbeddedI18n::try_new_with_language(langid!("en-US"))
428            .expect("en embedded i18n should initialize");
429        let fr = EmbeddedI18n::try_new_with_language(langid!("fr"))
430            .expect("fr embedded i18n should initialize");
431
432        assert_eq!(
433            es_fluent::FluentLocalizer::localize(&en, static_key("hello"), None),
434            Some("Hello".to_string())
435        );
436        assert_eq!(
437            es_fluent::FluentLocalizer::localize(&fr, static_key("hello"), None),
438            Some("Bonjour".to_string())
439        );
440
441        en.select_language(langid!("fr"))
442            .expect("en manager should switch to fr");
443
444        assert_eq!(
445            es_fluent::FluentLocalizer::localize(&en, static_key("hello"), None),
446            Some("Bonjour".to_string())
447        );
448        assert_eq!(
449            es_fluent::FluentLocalizer::localize(&fr, static_key("hello"), None),
450            Some("Bonjour".to_string())
451        );
452
453        fr.select_language(langid!("en-US"))
454            .expect("fr manager should switch to en-US");
455
456        assert_eq!(
457            es_fluent::FluentLocalizer::localize(&en, static_key("hello"), None),
458            Some("Bonjour".to_string())
459        );
460        assert_eq!(
461            es_fluent::FluentLocalizer::localize(&fr, static_key("hello"), None),
462            Some("Hello".to_string())
463        );
464    }
465
466    #[test]
467    fn embedded_i18n_facade_methods_delegate_to_manager_and_typed_lookup() {
468        force_inventory_link();
469        let i18n = EmbeddedI18n::try_new_with_language(langid!("en-US"))
470            .expect("embedded i18n should initialize");
471
472        assert_eq!(
473            es_fluent::FluentLocalizer::localize(&i18n, static_key("hello"), None),
474            Some("Hello".to_string())
475        );
476        assert_eq!(i18n.localize_message(&TestMessage), "Hello");
477        assert!(
478            i18n.select_language_strict(langid!("de")).is_err(),
479            "strict selection should reject unsupported locales"
480        );
481    }
482
483    #[test]
484    fn embedded_i18n_strict_initialization_tracks_active_language() {
485        force_inventory_link();
486        let i18n = EmbeddedI18n::try_new_with_language_strict(langid!("en-US"))
487            .expect("strict embedded i18n should initialize");
488
489        i18n.select_language_strict(langid!("en-US"))
490            .expect("strictly selecting the active language should be a no-op");
491        assert_eq!(
492            es_fluent::FluentLocalizer::localize(&i18n, static_key("hello"), None),
493            Some("Hello".to_string())
494        );
495        assert_eq!(
496            es_fluent::FluentLocalizer::localize(&i18n, static_key("unknown"), None),
497            None
498        );
499
500        i18n.select_language(langid!("en-US"))
501            .expect("best-effort selection should store its own active policy");
502        i18n.select_language(langid!("en-US"))
503            .expect("best-effort selecting the active language should be a no-op");
504    }
505
506    #[test]
507    fn embedded_i18n_try_new_builds_context_before_language_selection() {
508        force_inventory_link();
509        let i18n = EmbeddedI18n::try_new().expect("embedded i18n should initialize");
510        let cloned = i18n.clone();
511
512        assert_eq!(
513            es_fluent::FluentLocalizer::localize(&i18n, static_key("hello"), None),
514            None
515        );
516        assert_eq!(i18n.try_localize_message(&TestMessage), None);
517        cloned
518            .select_language(langid!("fr"))
519            .expect("language selection should work after initialization");
520        assert_eq!(i18n.localize_message(&TestMessage), "Bonjour");
521        assert_eq!(
522            es_fluent::FluentLocalizer::localize(&i18n, static_key("hello"), None),
523            Some("Bonjour".to_string())
524        );
525    }
526
527    #[test]
528    fn embedded_init_error_display_and_source_match_error_kind() {
529        use es_fluent_manager_core::{ModuleDiscoveryError, ModuleRegistrationKind};
530        use std::error::Error as _;
531
532        let discovery = EmbeddedInitError::ModuleDiscovery(vec![
533            ModuleDiscoveryError::DuplicateModuleRegistration {
534                name: "app".to_string(),
535                owner: "app".to_string(),
536                kind: ModuleRegistrationKind::MetadataOnly,
537                count: 2,
538            },
539        ]);
540        assert!(
541            discovery
542                .to_string()
543                .contains("failed strict i18n module discovery")
544        );
545        assert!(discovery.source().is_none());
546
547        let selection = EmbeddedInitError::LanguageSelection(
548            LocalizationError::LanguageNotSupported(langid!("de")),
549        );
550        assert!(
551            selection
552                .to_string()
553                .contains("failed to select the requested language")
554        );
555        assert!(selection.source().is_some());
556    }
557}