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
17pub trait LanguageStore: Send + Sync {
19 fn snapshot(&self, locale: &str) -> LanguageSnapshot;
20}
21
22#[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#[derive(Debug, Clone)]
70pub struct FileLanguageStore {
71 dir: PathBuf,
72 cache: Arc<RwLock<BTreeMap<String, LanguageSnapshot>>>,
73}
74
75impl FileLanguageStore {
76 pub fn new(dir: impl AsRef<Path>) -> Self {
77 Self {
78 dir: dir.as_ref().to_path_buf(),
79 cache: Arc::new(RwLock::new(BTreeMap::new())),
80 }
81 }
82
83 pub fn reload(&self) {
84 if let Ok(mut cache) = self.cache.write() {
85 cache.clear();
86 }
87 }
88
89 fn load_locale(&self, locale: &str) -> LanguageSnapshot {
90 if !is_safe_locale(locale) {
91 return LanguageSnapshot::default();
92 }
93 let mut files = vec![self.dir.join(format!("{locale}.json"))];
94 let mut groups: Vec<PathBuf> = std::fs::read_dir(self.dir.join(locale))
95 .map(|rd| rd.filter_map(Result::ok).map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "json")).collect())
96 .unwrap_or_default();
97 groups.sort();
98 files.extend(groups.iter().cloned());
99
100 let mut tree = serde_json::Map::new();
101 let mut revision = 0_i64;
102 let mut found = false;
103 for path in &files {
104 let Ok(contents) = std::fs::read_to_string(path) else { continue };
105 let value: serde_json::Value = match serde_json::from_str(&contents) {
106 Ok(v) => v,
107 Err(error) => {
108 tracing::error!(locale, path = %path.display(), error = %error, "Failed to parse language JSON");
109 return LanguageSnapshot::default();
110 }
111 };
112 let is_group = path.parent().is_some_and(|p| p != self.dir);
113 match (is_group, value) {
114 (true, v) => { tree.insert(path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(), v); }
115 (false, serde_json::Value::Object(map)) => tree.extend(map),
116 (false, _) => return LanguageSnapshot::default(),
117 }
118 found = true;
119 revision = revision.max(
120 std::fs::metadata(path).and_then(|m| m.modified()).ok()
121 .and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs() as i64).unwrap_or(1),
122 );
123 }
124 if !found {
125 return LanguageSnapshot::default();
126 }
127 match LanguageJson::decode_default(&serde_json::Value::Object(tree).to_string()) {
128 Ok(messages) => LanguageSnapshot { revision, messages },
129 Err(error) => {
130 tracing::error!(locale, error = %error, "Failed to parse language tree");
131 LanguageSnapshot::default()
132 }
133 }
134 }
135}
136
137impl LanguageStore for FileLanguageStore {
138 fn snapshot(&self, locale: &str) -> LanguageSnapshot {
139 if let Ok(cache) = self.cache.read()
140 && let Some(snapshot) = cache.get(locale)
141 {
142 return snapshot.clone();
143 }
144 let snapshot = self.load_locale(locale);
145 if let Ok(mut cache) = self.cache.write() {
146 cache.insert(locale.to_owned(), snapshot.clone());
147 }
148 snapshot
149 }
150}
151
152fn is_safe_locale(locale: &str) -> bool {
153 !locale.is_empty()
154 && locale
155 .chars()
156 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
157}
158
159#[derive(Debug, Clone, Serialize)]
160pub struct ClientI18nConfig {
161 pub locale: String,
162 #[serde(rename = "fallbackLocale")]
163 pub fallback_locale: String,
164 pub catalogs: BTreeMap<String, LanguageSnapshot>,
165}
166
167#[derive(Clone)]
169pub struct TextResolver {
170 store: Arc<dyn LanguageStore>,
171 default_locale: String,
172 fallback_locale: String,
173}
174
175impl std::fmt::Debug for TextResolver {
176 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177 f.debug_struct("TextResolver")
178 .field("default_locale", &self.default_locale)
179 .field("fallback_locale", &self.fallback_locale)
180 .finish()
181 }
182}
183
184impl TextResolver {
185 pub fn new(
186 store: Arc<dyn LanguageStore>,
187 default_locale: impl Into<String>,
188 fallback_locale: impl Into<String>,
189 ) -> Self {
190 Self {
191 store,
192 default_locale: default_locale.into(),
193 fallback_locale: fallback_locale.into(),
194 }
195 }
196
197 pub fn default_locale(&self) -> &str {
198 &self.default_locale
199 }
200
201 pub fn fallback_locale(&self) -> &str {
202 &self.fallback_locale
203 }
204
205 pub fn snapshot(&self, locale: &str) -> LanguageSnapshot {
206 self.store.snapshot(locale)
207 }
208
209 pub fn text(
210 &self,
211 key: &str,
212 replace: &[(&str, &str)],
213 default: Option<&str>,
214 locale: Option<&str>,
215 ) -> String {
216 let active = locale.unwrap_or(&self.default_locale);
217 let primary_snap = self.snapshot(active);
218 let mut resolved = LanguageTree::get(&primary_snap.messages, key).map(str::to_owned);
219
220 if resolved.is_none() && active != self.fallback_locale {
221 let fallback_snap = self.snapshot(&self.fallback_locale);
222 resolved = LanguageTree::get(&fallback_snap.messages, key).map(str::to_owned);
223 }
224
225 let template = resolved
226 .or_else(|| default.map(str::to_owned))
227 .unwrap_or_else(|| key.to_owned());
228
229 if replace.is_empty() {
230 return template;
231 }
232
233 apply_replacements(&template, replace)
234 }
235
236 pub fn client_config(&self, locale: Option<&str>) -> ClientI18nConfig {
237 let active = locale.unwrap_or(&self.default_locale).to_owned();
238 let mut catalogs = BTreeMap::new();
239 catalogs.insert(active.clone(), self.snapshot(&active));
240 if self.fallback_locale != active {
241 catalogs.insert(
242 self.fallback_locale.clone(),
243 self.snapshot(&self.fallback_locale),
244 );
245 }
246 ClientI18nConfig {
247 locale: active,
248 fallback_locale: self.fallback_locale.clone(),
249 catalogs,
250 }
251 }
252}
253
254fn apply_replacements(template: &str, replace: &[(&str, &str)]) -> String {
255 let mut pairs: Vec<(String, String)> = Vec::with_capacity(replace.len() * 3);
256 for &(name, val) in replace {
257 pairs.push((format!(":{name}"), val.to_owned()));
258 pairs.push((format!(":{}", ucfirst_unicode(name)), ucfirst_unicode(val)));
259 pairs.push((format!(":{}", name.to_uppercase()), val.to_uppercase()));
260 }
261 pairs.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
263
264 let mut out = String::with_capacity(template.len());
265 let mut idx = 0;
266 while idx < template.len() {
267 let rest = &template[idx..];
268 if rest.starts_with(':')
269 && let Some((needle, replacement)) =
270 pairs.iter().find(|(needle, _)| rest.starts_with(needle.as_str()))
271 {
272 out.push_str(replacement);
273 idx += needle.len();
274 continue;
275 }
276 if let Some(ch) = rest.chars().next() {
277 out.push(ch);
278 idx += ch.len_utf8();
279 } else {
280 break;
281 }
282 }
283 out
284}
285
286fn ucfirst_unicode(s: &str) -> String {
287 let mut chars = s.chars();
288 let Some(first) = chars.next() else {
289 return String::new();
290 };
291 let mut out = String::with_capacity(s.len());
292 for upper in first.to_uppercase() {
293 out.push(upper);
294 }
295 out.push_str(chars.as_str());
296 out
297}