glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! The request's locale, as Rails' `I18n.locale`.
//!
//! The [`Locales`] middleware takes it from the `locale` param
//! (`/faqs?locale=he`), falling back to the first locale listed; an unknown
//! one is a `400 Bad Request`. [`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 (`config/locales/*.yml`,
//! 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.

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: String;
}

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

/// 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(locale.into(), fut).await
}

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 translations = HashMap::new();
    for file in files {
        let text = std::fs::read_to_string(&file)
            .map_err(|e| Error::internal(format!("reading {}: {e}", file.display())))?;
        let yaml: serde_yaml::Value = serde_yaml::from_str(&text)
            .map_err(|e| Error::internal(format!("{}: {e}", file.display())))?;
        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 translation of `key` in the current locale, with `%{name}`
/// placeholders left as written.
pub fn t(key: impl AsRef<str>) -> String {
    let locale = locale();
    let full = format!("{locale}.{}", key.as_ref());
    TRANSLATIONS
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .as_ref()
        .and_then(|translations| translations.get(&full).cloned())
        .unwrap_or_else(|| format!("Translation missing: {full}"))
}

/// 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 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 {
            None => self.available[0].clone(),
            Some(locale) if self.available.contains(&locale) => locale,
            Some(locale) => {
                let error = Error::bad_request(format!("\"{locale}\" is not a valid locale"));
                return Box::pin(async move { error.into_response() });
            }
        };
        Box::pin(LOCALE.scope(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");
    }

    #[tokio::test]
    async fn translates_from_rails_locale_files() {
        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();
    }
}