Skip to main content

saola_kit/i18n/
store.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3use std::sync::{Arc, RwLock};
4use std::time::UNIX_EPOCH;
5
6use serde::Serialize;
7
8use super::json::LanguageJson;
9use super::tree::{I18nError, LanguageNode, LanguageTree};
10
11#[derive(Debug, Clone, Default, Serialize)]
12pub struct LanguageSnapshot {
13    pub revision: i64,
14    pub messages: BTreeMap<String, LanguageNode>,
15}
16
17/// Source of locale translation snapshots.
18pub trait LanguageStore: Send + Sync {
19    fn snapshot(&self, locale: &str) -> LanguageSnapshot;
20}
21
22/// In-memory translation store, useful for tests and bundled dictionaries.
23#[derive(Debug, Clone, Default)]
24pub struct MemoryLanguageStore {
25    locales: Arc<RwLock<BTreeMap<String, LanguageSnapshot>>>,
26}
27
28impl MemoryLanguageStore {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    pub fn insert(
34        &self,
35        locale: impl Into<String>,
36        revision: i64,
37        messages: BTreeMap<String, LanguageNode>,
38    ) -> &Self {
39        if let Ok(mut map) = self.locales.write() {
40            map.insert(locale.into(), LanguageSnapshot { revision, messages });
41        }
42        self
43    }
44
45    pub fn insert_json(
46        &self,
47        locale: impl Into<String>,
48        revision: i64,
49        json: &str,
50    ) -> Result<&Self, I18nError> {
51        let messages = LanguageJson::decode_default(json)?;
52        Ok(self.insert(locale, revision, messages))
53    }
54}
55
56impl LanguageStore for MemoryLanguageStore {
57    fn snapshot(&self, locale: &str) -> LanguageSnapshot {
58        self.locales
59            .read()
60            .ok()
61            .and_then(|map| map.get(locale).cloned())
62            .unwrap_or_default()
63    }
64}
65
66/// Directory-backed JSON translation store (`<dir>/<locale>.json`).
67#[derive(Debug, Clone)]
68pub struct FileLanguageStore {
69    dir: PathBuf,
70    cache: Arc<RwLock<BTreeMap<String, LanguageSnapshot>>>,
71}
72
73impl FileLanguageStore {
74    pub fn new(dir: impl AsRef<Path>) -> Self {
75        Self {
76            dir: dir.as_ref().to_path_buf(),
77            cache: Arc::new(RwLock::new(BTreeMap::new())),
78        }
79    }
80
81    pub fn reload(&self) {
82        if let Ok(mut cache) = self.cache.write() {
83            cache.clear();
84        }
85    }
86
87    fn load_locale(&self, locale: &str) -> LanguageSnapshot {
88        if !is_safe_locale(locale) {
89            return LanguageSnapshot::default();
90        }
91        let path = self.dir.join(format!("{locale}.json"));
92        let Ok(contents) = std::fs::read_to_string(&path) else {
93            return LanguageSnapshot::default();
94        };
95        let messages = match LanguageJson::decode_default(&contents) {
96            Ok(tree) => tree,
97            Err(error) => {
98                tracing::error!(locale, path = %path.display(), error = %error, "Failed to parse language JSON");
99                return LanguageSnapshot::default();
100            }
101        };
102        let revision = std::fs::metadata(&path)
103            .and_then(|m| m.modified())
104            .ok()
105            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
106            .map(|d| d.as_secs() as i64)
107            .unwrap_or(1);
108
109        LanguageSnapshot { revision, messages }
110    }
111}
112
113impl LanguageStore for FileLanguageStore {
114    fn snapshot(&self, locale: &str) -> LanguageSnapshot {
115        if let Ok(cache) = self.cache.read()
116            && let Some(snapshot) = cache.get(locale)
117        {
118            return snapshot.clone();
119        }
120        let snapshot = self.load_locale(locale);
121        if let Ok(mut cache) = self.cache.write() {
122            cache.insert(locale.to_owned(), snapshot.clone());
123        }
124        snapshot
125    }
126}
127
128fn is_safe_locale(locale: &str) -> bool {
129    !locale.is_empty()
130        && locale
131            .chars()
132            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
133}
134
135#[derive(Debug, Clone, Serialize)]
136pub struct ClientI18nConfig {
137    pub locale: String,
138    #[serde(rename = "fallbackLocale")]
139    pub fallback_locale: String,
140    pub catalogs: BTreeMap<String, LanguageSnapshot>,
141}
142
143/// Resolves localized strings and builds base client i18n configurations.
144#[derive(Clone)]
145pub struct TextResolver {
146    store: Arc<dyn LanguageStore>,
147    default_locale: String,
148    fallback_locale: String,
149}
150
151impl std::fmt::Debug for TextResolver {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("TextResolver")
154            .field("default_locale", &self.default_locale)
155            .field("fallback_locale", &self.fallback_locale)
156            .finish()
157    }
158}
159
160impl TextResolver {
161    pub fn new(
162        store: Arc<dyn LanguageStore>,
163        default_locale: impl Into<String>,
164        fallback_locale: impl Into<String>,
165    ) -> Self {
166        Self {
167            store,
168            default_locale: default_locale.into(),
169            fallback_locale: fallback_locale.into(),
170        }
171    }
172
173    pub fn default_locale(&self) -> &str {
174        &self.default_locale
175    }
176
177    pub fn fallback_locale(&self) -> &str {
178        &self.fallback_locale
179    }
180
181    pub fn snapshot(&self, locale: &str) -> LanguageSnapshot {
182        self.store.snapshot(locale)
183    }
184
185    pub fn text(
186        &self,
187        key: &str,
188        replace: &[(&str, &str)],
189        default: Option<&str>,
190        locale: Option<&str>,
191    ) -> String {
192        let active = locale.unwrap_or(&self.default_locale);
193        let primary_snap = self.snapshot(active);
194        let mut resolved = LanguageTree::get(&primary_snap.messages, key).map(str::to_owned);
195
196        if resolved.is_none() && active != self.fallback_locale {
197            let fallback_snap = self.snapshot(&self.fallback_locale);
198            resolved = LanguageTree::get(&fallback_snap.messages, key).map(str::to_owned);
199        }
200
201        let template = resolved
202            .or_else(|| default.map(str::to_owned))
203            .unwrap_or_else(|| key.to_owned());
204
205        if replace.is_empty() {
206            return template;
207        }
208
209        apply_replacements(&template, replace)
210    }
211
212    pub fn client_config(&self, locale: Option<&str>) -> ClientI18nConfig {
213        let active = locale.unwrap_or(&self.default_locale).to_owned();
214        let mut catalogs = BTreeMap::new();
215        catalogs.insert(active.clone(), self.snapshot(&active));
216        if self.fallback_locale != active {
217            catalogs.insert(
218                self.fallback_locale.clone(),
219                self.snapshot(&self.fallback_locale),
220            );
221        }
222        ClientI18nConfig {
223            locale: active,
224            fallback_locale: self.fallback_locale.clone(),
225            catalogs,
226        }
227    }
228}
229
230fn apply_replacements(template: &str, replace: &[(&str, &str)]) -> String {
231    let mut pairs: Vec<(String, String)> = Vec::with_capacity(replace.len() * 3);
232    for &(name, val) in replace {
233        pairs.push((format!(":{name}"), val.to_owned()));
234        pairs.push((format!(":{}", ucfirst_unicode(name)), ucfirst_unicode(val)));
235        pairs.push((format!(":{}", name.to_uppercase()), val.to_uppercase()));
236    }
237    // Longest-key-first single-pass scan (matches PHP strtr semantics).
238    pairs.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
239
240    let mut out = String::with_capacity(template.len());
241    let mut idx = 0;
242    while idx < template.len() {
243        let rest = &template[idx..];
244        if rest.starts_with(':')
245            && let Some((needle, replacement)) =
246                pairs.iter().find(|(needle, _)| rest.starts_with(needle.as_str()))
247        {
248            out.push_str(replacement);
249            idx += needle.len();
250            continue;
251        }
252        if let Some(ch) = rest.chars().next() {
253            out.push(ch);
254            idx += ch.len_utf8();
255        } else {
256            break;
257        }
258    }
259    out
260}
261
262fn ucfirst_unicode(s: &str) -> String {
263    let mut chars = s.chars();
264    let Some(first) = chars.next() else {
265        return String::new();
266    };
267    let mut out = String::with_capacity(s.len());
268    for upper in first.to_uppercase() {
269        out.push(upper);
270    }
271    out.push_str(chars.as_str());
272    out
273}