glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
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
//! The request's locale, as Rails' `I18n.locale`.
//!
//! The [`Locales`] middleware picks it: the `locale` param
//! (`/faqs?locale=he`, remembered in a `locale` cookie), else that cookie,
//! else the best of the browser's `Accept-Language`, else the first
//! locale listed; an unknown param is a `400 Bad Request`. [`set_locale`]
//! changes it for the rest of the request (a signed-in user's own).
//! [`locale()`] reads it anywhere in the request, so a query can scope by
//! it:
//!
//! ```text
//! FaqSection.where(locale: locale())!
//! ```
//!
//! Translations come from Rails-style YAML files in `config/locales/`,
//! compiled into the app by `glacier::app!()` (or loaded with [`load`]);
//! [`t`] looks a key up in the current locale:
//! `t("versions.ios.warning")`. A missing one reads
//! `Translation missing: en.versions.ios.warning`, as in Rails.
//! [`t_count`] picks a plural form (`one`, `few`, `other`, …) by the
//! locale's rules, as `t("apples", count: n)` does in `.glacier`.

use std::cell::RefCell;
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::RwLock;

use crate::context::Context;
use crate::error::Error;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::{IntoResponse, Response};

/// The locale when no [`Locales`] middleware set one.
pub const DEFAULT: &str = "en";

tokio::task_local! {
    static LOCALE: RefCell<String>;
}

/// The current locale: the request's, or [`DEFAULT`] outside one.
pub fn locale() -> String {
    LOCALE
        .try_with(|locale| locale.borrow().clone())
        .unwrap_or_else(|_| DEFAULT.to_owned())
}

/// The locale set for this request or block, if one was: what a job
/// queued here takes with it.
pub(crate) fn chosen() -> Option<String> {
    LOCALE.try_with(|locale| locale.borrow().clone()).ok()
}

/// Runs `fut` with `locale` as the current locale, e.g. in a job or test.
pub async fn with_locale<F: Future>(locale: impl Into<String>, fut: F) -> F::Output {
    LOCALE.scope(RefCell::new(locale.into()), fut).await
}

/// Changes the current locale for the rest of the request (or
/// [`with_locale`] block): a signed-in user's own, say, after
/// [`Locales`] picked one. Outside either, it does nothing.
pub fn set_locale(locale: impl Into<String>) {
    let locale = locale.into();
    let _ = LOCALE.try_with(|current| *current.borrow_mut() = locale);
}

static TRANSLATIONS: RwLock<Option<HashMap<String, String>>> = RwLock::new(None);

/// Loads every `*.yml` file in `dir` (Rails' `config/locales`), merging
/// them, for [`t`]. Call it once at startup; calling it again replaces
/// what was loaded.
///
/// # Errors
///
/// If the folder or a file can't be read, or a file isn't YAML.
pub fn load(dir: impl AsRef<Path>) -> crate::Result<()> {
    let dir = dir.as_ref();
    let mut files: Vec<_> = std::fs::read_dir(dir)
        .map_err(|e| Error::internal(format!("reading {}: {e}", dir.display())))?
        .filter_map(|entry| entry.ok().map(|e| e.path()))
        .filter(|path| {
            path.extension()
                .is_some_and(|ext| ext == "yml" || ext == "yaml")
        })
        .collect();
    files.sort();
    let mut sources = Vec::new();
    for file in files {
        let text = std::fs::read_to_string(&file)
            .map_err(|e| Error::internal(format!("reading {}: {e}", file.display())))?;
        sources.push((file.display().to_string(), text));
    }
    let sources: Vec<(&str, &str)> = sources
        .iter()
        .map(|(name, text)| (name.as_str(), text.as_str()))
        .collect();
    load_sources(&sources)
}

/// Loads translations from YAML texts, each with its file's name (for
/// errors), merging them in order. `glacier::app!()` calls it with
/// `config/locales/`'s files, compiled in.
///
/// # Errors
///
/// If a text isn't YAML.
pub fn load_sources(sources: &[(&str, &str)]) -> crate::Result<()> {
    let mut translations = HashMap::new();
    for (name, text) in sources {
        let yaml: serde_yaml::Value =
            serde_yaml::from_str(text).map_err(|e| Error::internal(format!("{name}: {e}")))?;
        flatten(String::new(), &yaml, &mut translations);
    }
    *TRANSLATIONS.write().unwrap_or_else(|e| e.into_inner()) = Some(translations);
    Ok(())
}

/// `{en: {versions: {ios: "…"}}}` → `"en.versions.ios" => "…"`.
fn flatten(prefix: String, value: &serde_yaml::Value, out: &mut HashMap<String, String>) {
    use serde_yaml::Value as Y;
    let text = match value {
        Y::Mapping(map) => {
            for (key, value) in map {
                let key = match key {
                    Y::String(s) => s.clone(),
                    Y::Bool(b) => b.to_string(),
                    Y::Number(n) => n.to_string(),
                    _ => continue,
                };
                let path = if prefix.is_empty() {
                    key
                } else {
                    format!("{prefix}.{key}")
                };
                flatten(path, value, out);
            }
            return;
        }
        Y::String(s) => s.clone(),
        Y::Bool(b) => b.to_string(),
        Y::Number(n) => n.to_string(),
        _ => return,
    };
    out.insert(prefix, text);
}

/// The text at `full` (`en.errors.not_found`), if loaded.
fn lookup(full: &str) -> Option<String> {
    TRANSLATIONS
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .as_ref()
        .and_then(|translations| translations.get(full).cloned())
}

/// The translation of `key` in the current locale, with `%{name}`
/// placeholders left as written.
pub fn t(key: impl AsRef<str>) -> String {
    let full = format!("{}.{}", locale(), key.as_ref());
    lookup(&full).unwrap_or_else(|| format!("Translation missing: {full}"))
}

/// The plural form of `key` for `count`, with `%{count}` filled in, as
/// Rails' `t(key, count: n)`: `key.zero` for 0 when there is one, else
/// the form the locale's rules pick (`one`, `two`, `few`, `many`), else
/// `key.other`.
///
/// ```yaml
/// en:
///   inbox:
///     zero: No messages
///     one: "%{count} message"
///     other: "%{count} messages"
/// ```
pub fn t_count(key: impl AsRef<str>, count: i64) -> String {
    t_args(key, &[("count", count.to_string())])
}

/// The translation of `key` with placeholders filled in from `args`,
/// pluralised by a `count` among them: what `t("inbox", count: n, name:
/// user.name)` in `.glacier` calls.
pub fn t_args(key: impl AsRef<str>, args: &[(&str, String)]) -> String {
    let key = key.as_ref();
    let locale = locale();
    let count = args
        .iter()
        .find(|(name, _)| *name == "count")
        .and_then(|(_, value)| value.parse::<i64>().ok());
    let full = format!("{locale}.{key}");
    let text = match count {
        Some(count) => {
            let forms = [
                (count == 0).then_some("zero"),
                Some(plural(&locale, count)),
                Some("other"),
            ];
            forms
                .into_iter()
                .flatten()
                .find_map(|form| lookup(&format!("{full}.{form}")))
                .or_else(|| lookup(&full))
        }
        None => lookup(&full),
    };
    let text = text.unwrap_or_else(|| format!("Translation missing: {full}"));
    args.iter().fold(text, |text, (name, value)| {
        text.replace(&format!("%{{{name}}}"), value)
    })
}

/// The plural form a locale uses for `n`, by the Unicode CLDR's rules for
/// whole numbers: `one` or `other` for English and most European
/// languages, more forms for Slavic and Arabic, one form for Chinese or
/// Japanese.
pub fn plural(locale: &str, n: i64) -> &'static str {
    let language = locale
        .split(['-', '_'])
        .next()
        .unwrap_or(locale)
        .to_ascii_lowercase();
    let n = n.unsigned_abs();
    let (ten, hundred) = (n % 10, n % 100);
    match language.as_str() {
        "ja" | "zh" | "ko" | "vi" | "th" | "id" | "ms" => "other",
        "fr" | "pt" | "hi" | "fa" => {
            if n <= 1 {
                "one"
            } else {
                "other"
            }
        }
        "ru" | "uk" | "be" | "sr" | "hr" | "bs" => {
            if ten == 1 && hundred != 11 {
                "one"
            } else if (2..=4).contains(&ten) && !(12..=14).contains(&hundred) {
                "few"
            } else {
                "many"
            }
        }
        "pl" => {
            if n == 1 {
                "one"
            } else if (2..=4).contains(&ten) && !(12..=14).contains(&hundred) {
                "few"
            } else {
                "many"
            }
        }
        "cs" | "sk" => match n {
            1 => "one",
            2..=4 => "few",
            _ => "other",
        },
        "he" => match n {
            1 => "one",
            2 => "two",
            _ => "other",
        },
        "ar" => match (n, hundred) {
            (0, _) => "zero",
            (1, _) => "one",
            (2, _) => "two",
            (_, 3..=10) => "few",
            (_, 11..=99) => "many",
            _ => "other",
        },
        _ => {
            if n == 1 {
                "one"
            } else {
                "other"
            }
        }
    }
}

/// The translation of `key` with its `%{name}` placeholders filled in, as
/// Rails' `t(key, name: value)`:
/// `t_with("errors.taken", &[("device_name", "iPad")])`.
pub fn t_with(key: impl AsRef<str>, values: &[(&str, &str)]) -> String {
    values.iter().fold(t(key), |text, (name, value)| {
        text.replace(&format!("%{{{name}}}"), value)
    })
}

/// Sets each request's locale from its `locale` param. The first locale
/// is the default: `Locales::new(["en", "he"])`.
pub struct Locales {
    available: Vec<String>,
}

impl Locales {
    /// # Panics
    ///
    /// If no locales are given.
    pub fn new<S: Into<String>>(available: impl IntoIterator<Item = S>) -> Self {
        let available: Vec<String> = available.into_iter().map(Into::into).collect();
        assert!(
            !available.is_empty(),
            "Locales::new needs at least one locale"
        );
        Self { available }
    }
}

impl Locales {
    /// The available locale `tag` names (`he`, or `en` for `en-GB` when
    /// only `en` is available).
    fn matching(&self, tag: &str) -> Option<String> {
        let tag = tag.trim();
        self.available
            .iter()
            .find(|l| l.eq_ignore_ascii_case(tag))
            .or_else(|| {
                let language = tag.split(['-', '_']).next()?;
                self.available
                    .iter()
                    .find(|l| l.eq_ignore_ascii_case(language))
            })
            .cloned()
    }

    /// The best available locale in an `Accept-Language` header, by its
    /// `q` weights.
    fn best_accepted(&self, header: &str) -> Option<String> {
        let mut tags: Vec<(f32, &str)> = header
            .split(',')
            .filter_map(|part| {
                let mut pieces = part.split(';');
                let tag = pieces.next()?.trim();
                let q = pieces
                    .find_map(|p| p.trim().strip_prefix("q="))
                    .and_then(|q| q.parse::<f32>().ok())
                    .unwrap_or(1.0);
                (!tag.is_empty() && tag != "*" && q > 0.0).then_some((q, tag))
            })
            .collect();
        // Stable, so equal weights keep the header's order.
        tags.sort_by(|a, b| b.0.total_cmp(&a.0));
        tags.into_iter().find_map(|(_, tag)| self.matching(tag))
    }
}

impl Middleware for Locales {
    fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
        let requested = ctx.params().get("locale").map(str::to_owned);
        let locale = match requested {
            // Asked for: used, and remembered for the next requests.
            Some(locale) if self.available.contains(&locale) => {
                ctx.cookies().add(
                    crate::cookies::Cookie::build(("locale", locale.clone()))
                        .path("/")
                        .max_age(cookie::time::Duration::days(365))
                        .same_site(crate::cookies::SameSite::Lax),
                );
                locale
            }
            Some(locale) => {
                let error = Error::bad_request(format!("\"{locale}\" is not a valid locale"));
                return Box::pin(async move { error.into_response() });
            }
            None => ctx
                .cookies()
                .get("locale")
                .filter(|locale| self.available.contains(locale))
                .or_else(|| {
                    ctx.header(http::header::ACCEPT_LANGUAGE)
                        .and_then(|header| self.best_accepted(header))
                })
                .unwrap_or_else(|| self.available[0].clone()),
        };
        Box::pin(LOCALE.scope(RefCell::new(locale), next.run(ctx)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::App;
    use crate::testing::TestClient;

    #[tokio::test]
    async fn sets_the_locale_from_the_param() {
        let app = App::new()
            .middleware(Locales::new(["en", "he"]))
            .routes(|r| {
                r.get("/", |_ctx| async { locale() });
            });
        let client = TestClient::new(app);
        assert_eq!(client.get("/").await.body_text(), "en");
        assert_eq!(client.get("/?locale=he").await.body_text(), "he");
        let unknown = client.get("/?locale=xx").await;
        assert_eq!(unknown.status(), 400);
        assert_eq!(locale(), DEFAULT, "outside a request");
        assert_eq!(with_locale("he", async { locale() }).await, "he");
    }

    /// The tests that load translations, one at a time: they share them.
    static LOADING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

    #[tokio::test]
    async fn translates_from_rails_locale_files() {
        let _loading = LOADING.lock().await;
        let dir = std::env::temp_dir().join(format!("glacier-i18n-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("en.yml"),
            "en:\n  versions:\n    ios:\n      warning: Update soon\n  errors:\n    not_found: Not found\n    busy: \"In use on %{device} (%{device})\"\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("he.yml"),
            "he:\n  errors:\n    not_found: \"לא נמצא\"\n",
        )
        .unwrap();
        load(&dir).unwrap();
        assert_eq!(t("versions.ios.warning"), "Update soon");
        assert_eq!(
            t_with("errors.busy", &[("device", "iPad")]),
            "In use on iPad (iPad)"
        );
        assert_eq!(
            with_locale("he", async { t("errors.not_found") }).await,
            "לא נמצא"
        );
        assert_eq!(
            with_locale("he", async { t("versions.ios.warning") }).await,
            "Translation missing: he.versions.ios.warning"
        );
        std::fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn plural_forms_follow_each_language() {
        assert_eq!(plural("en", 1), "one");
        assert_eq!(plural("en-GB", 2), "other");
        assert_eq!(plural("fr", 0), "one");
        assert_eq!(plural("ja", 1), "other");
        assert_eq!(plural("ru", 21), "one");
        assert_eq!(plural("ru", 3), "few");
        assert_eq!(plural("ru", 12), "many");
        assert_eq!(plural("pl", 22), "few");
        assert_eq!(plural("pl", 5), "many");
        assert_eq!(plural("ar", 0), "zero");
        assert_eq!(plural("ar", 105), "few");
    }

    #[tokio::test]
    async fn counts_pick_plural_forms() {
        let _loading = LOADING.lock().await;
        load_sources(&[(
            "en.yml",
            "en:\n  inbox:\n    zero: No messages\n    one: \"%{count} message\"\n    other: \"%{count} messages for %{name}\"\n  plain: \"%{count} things\"\nru:\n  files:\n    one: \"%{count} файл\"\n    few: \"%{count} файла\"\n    many: \"%{count} файлов\"\n",
        )])
        .unwrap();
        assert_eq!(t_count("inbox", 0), "No messages");
        assert_eq!(t_count("inbox", 1), "1 message");
        assert_eq!(
            t_args("inbox", &[("count", "3".into()), ("name", "Ada".into())]),
            "3 messages for Ada"
        );
        assert_eq!(t_count("plain", 2), "2 things", "a key without forms");
        assert_eq!(
            with_locale("ru", async { t_count("files", 3) }).await,
            "3 файла"
        );
        assert_eq!(
            with_locale("ru", async { t_count("files", 11) }).await,
            "11 файлов"
        );
    }

    #[tokio::test]
    async fn picks_the_locale_from_cookie_header_or_user() {
        let app = App::new()
            .middleware(Locales::new(["en", "he", "fr"]))
            .routes(|r| {
                r.get("/", |_ctx| async { locale() })
                    .get("/mine", |_ctx| async {
                        // A signed-in user's own locale, say.
                        set_locale("he");
                        locale()
                    });
            });
        let client = TestClient::new(app);
        client.header("accept-language", "de-DE, fr-CA;q=0.8, en;q=0.5");
        assert_eq!(client.get("/").await.body_text(), "fr", "the best match");
        // Asked for once, remembered after.
        assert_eq!(client.get("/?locale=he").await.body_text(), "he");
        assert_eq!(client.get("/").await.body_text(), "he");
        assert_eq!(client.get("/mine").await.body_text(), "he");
        assert_eq!(client.get("/?locale=en").await.body_text(), "en");
        assert_eq!(client.get("/mine").await.body_text(), "he");
    }
}