ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
//! Localization (feature `lang`): translation files, `:name` placeholders, simple pluralization
//! and `Accept-Language` negotiation. No extra dependencies.
//!
//! Files are flat JSON objects, one per locale: `lang/en.json`, `lang/fr.json`, ...
//!
//! ```
//! use ryuk::lang::Lang;
//!
//! let mut lang = Lang::new("en");
//! lang.insert("en", [("welcome", "Welcome, :name!"), ("apples", ":count apple|:count apples")]);
//! lang.insert("fr", [("welcome", "Bienvenue, :name !")]);
//!
//! assert_eq!(lang.trans_in("fr", "welcome", &[("name", "Zoe")]), "Bienvenue, Zoe !");
//! // missing key in "fr" falls back to the fallback locale, then to the key itself
//! assert_eq!(lang.trans_in("fr", "apples", &[]), ":count apple|:count apples");
//! assert_eq!(lang.trans_choice_in("fr", "apples", 3, &[]), "3 apples");
//! assert_eq!(lang.trans_in("en", "nope", &[]), "nope");
//!
//! // per request: pick the best supported locale from the Accept-Language header
//! assert_eq!(lang.negotiate("de;q=0.9, fr-CA;q=0.8, en;q=0.5"), "fr");
//! ```
use std::collections::HashMap;
use std::path::Path;

/// Loading failure.
#[derive(Debug, thiserror::Error)]
pub enum LangError {
    /// File or directory could not be read.
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
    /// The file is not a flat JSON object of strings.
    #[error("{file}: {source}")]
    Json {
        /// Offending file name.
        file: String,
        /// Parse error.
        source: serde_json::Error,
    },
    /// The locale name is not a plain tag like `en` or `pt-BR`.
    #[error("invalid locale name {0:?}")]
    BadLocale(String),
}

/// A locale tag is 1 to 35 ASCII letters, digits, `-` or `_`, starting with a letter or digit.
/// Anything else (`..`, `/`, `\`, NUL) is refused so a locale taken from a request or a file
/// name can never leave the lang directory.
pub fn valid_locale(s: &str) -> bool {
    !s.is_empty()
        && s.len() <= 35
        && s.starts_with(|c: char| c.is_ascii_alphanumeric())
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

/// Lowercase, `_` -> `-`, so `pt_BR`, `pt-br` and `pt-BR` are one locale.
fn norm(s: &str) -> String {
    s.to_ascii_lowercase().replace('_', "-")
}

/// Translation store with a default locale and a fallback locale.
#[derive(Debug, Clone)]
pub struct Lang {
    messages: HashMap<String, HashMap<String, String>>,
    locale: String,
    fallback: String,
}

impl Lang {
    /// Empty store; `fallback` is also the initial locale.
    pub fn new(fallback: &str) -> Self {
        Self {
            messages: HashMap::new(),
            locale: norm(fallback),
            fallback: norm(fallback),
        }
    }

    /// Load every `<locale>.json` in `dir` (files with an invalid locale name are skipped).
    pub fn load_dir(dir: impl AsRef<Path>, fallback: &str) -> Result<Self, LangError> {
        let mut l = Self::new(fallback);
        for e in std::fs::read_dir(dir.as_ref())? {
            let p = e?.path();
            if p.extension().is_some_and(|x| x == "json")
                && let Some(stem) = p.file_stem().and_then(|s| s.to_str())
            {
                if valid_locale(stem) {
                    l.load_file(&p, stem)?;
                } else {
                    tracing::warn!("lang: skipping file with invalid locale name {stem:?}");
                }
            }
        }
        Ok(l)
    }

    /// Load `dir/<locale>.json`; `locale` is validated first, so it may come from user input.
    pub fn load_locale(&mut self, dir: impl AsRef<Path>, locale: &str) -> Result<(), LangError> {
        if !valid_locale(locale) {
            return Err(LangError::BadLocale(locale.into()));
        }
        self.load_file(&dir.as_ref().join(format!("{locale}.json")), locale)
    }

    fn load_file(&mut self, path: &Path, locale: &str) -> Result<(), LangError> {
        let text = std::fs::read_to_string(path)?;
        let map: HashMap<String, String> =
            serde_json::from_str(&text).map_err(|source| LangError::Json {
                file: path.display().to_string(),
                source,
            })?;
        self.messages.entry(norm(locale)).or_default().extend(map);
        Ok(())
    }

    /// Add or replace messages for `locale` (handy in tests and for built-in defaults).
    pub fn insert<'a>(&mut self, locale: &str, msgs: impl IntoIterator<Item = (&'a str, &'a str)>) {
        self.messages
            .entry(norm(locale))
            .or_default()
            .extend(msgs.into_iter().map(|(k, v)| (k.into(), v.into())));
    }

    /// Set the default locale used by [`trans`](Self::trans). Any string is accepted; an
    /// unknown locale just falls back.
    pub fn set_locale(&mut self, locale: &str) {
        self.locale = norm(locale);
    }

    /// Translate `key` in the default locale.
    pub fn trans(&self, key: &str, args: &[(&str, &str)]) -> String {
        self.trans_in(&self.locale, key, args)
    }

    /// Translate `key` in `locale`: tries the exact tag, its language (`pt-BR` -> `pt`), then
    /// the fallback locale; a missing key returns the key. `:name` is replaced by the matching
    /// entry of `args` (unknown placeholders are left as written).
    pub fn trans_in(&self, locale: &str, key: &str, args: &[(&str, &str)]) -> String {
        match self.lookup(locale, key) {
            Some(m) => fill(m, args),
            None => key.to_string(),
        }
    }

    /// Pluralize with the default locale; see [`trans_choice_in`](Self::trans_choice_in).
    pub fn trans_choice(&self, key: &str, count: i64, args: &[(&str, &str)]) -> String {
        self.trans_choice_in(&self.locale, key, count, args)
    }

    /// The message is `one|other` (a single form is used for every count). `count == 1` picks
    /// the first form, anything else the second; `:count` is filled in.
    ///
    /// shortcut: no `{0}` / `[2,*]` ranges and no per-language plural rules (French treats 0 as
    /// singular, Russian has three forms); add them when a locale needs it.
    pub fn trans_choice_in(
        &self,
        locale: &str,
        key: &str,
        count: i64,
        args: &[(&str, &str)],
    ) -> String {
        let Some(m) = self.lookup(locale, key) else {
            return key.to_string();
        };
        let form = if count == 1 {
            m.split('|').next()
        } else {
            m.split('|').nth(1).or_else(|| m.split('|').next())
        }
        .unwrap_or(m);
        let c = count.to_string();
        let mut all: Vec<(&str, &str)> = args.to_vec();
        all.push(("count", &c));
        fill(form, &all)
    }

    fn lookup(&self, locale: &str, key: &str) -> Option<&str> {
        let l = norm(locale);
        let lang = l.split('-').next().unwrap_or(&l);
        [l.as_str(), lang, self.fallback.as_str()]
            .into_iter()
            .find_map(|loc| self.messages.get(loc)?.get(key))
            .map(String::as_str)
    }

    /// Locales that have messages loaded, sorted.
    pub fn locales(&self) -> Vec<String> {
        let mut v: Vec<String> = self.messages.keys().cloned().collect();
        v.sort();
        v
    }

    /// Best loaded locale for an `Accept-Language` header value (q-values honored, `q=0`
    /// refused, `fr-CA` matches `fr`); the fallback locale when nothing matches. Never fails.
    pub fn negotiate(&self, header: &str) -> String {
        let mut prefs: Vec<(f32, usize, String)> = header
            .split(',')
            .enumerate()
            .filter_map(|(i, part)| {
                let mut it = part.split(';');
                let tag = it.next()?.trim();
                let q = it
                    .find_map(|p| p.trim().strip_prefix("q="))
                    .map_or(Some(1.0), |v| v.trim().parse::<f32>().ok())?;
                (q > 0.0 && tag != "*" && !tag.is_empty()).then(|| (q, i, norm(tag)))
            })
            .collect();
        // highest q first; header order breaks ties
        prefs.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
        for (_, _, tag) in prefs {
            let lang = tag.split('-').next().unwrap_or(&tag);
            for cand in [tag.as_str(), lang] {
                if self.messages.contains_key(cand) {
                    return cand.to_string();
                }
            }
        }
        self.fallback.clone()
    }
}

/// Single pass, so a value that itself contains `:other` is never substituted twice.
fn fill(msg: &str, args: &[(&str, &str)]) -> String {
    let mut out = String::with_capacity(msg.len());
    let mut rest = msg;
    while let Some(i) = rest.find(':') {
        out.push_str(&rest[..i]);
        let after = &rest[i + 1..];
        let end = after
            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
            .unwrap_or(after.len());
        match args
            .iter()
            .find(|(k, _)| !k.is_empty() && *k == &after[..end])
        {
            Some((_, v)) => {
                out.push_str(v);
                rest = &after[end..];
            }
            None => {
                out.push(':');
                rest = after;
            }
        }
    }
    out.push_str(rest);
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample() -> Lang {
        let mut l = Lang::new("en");
        l.insert(
            "en",
            [
                ("hi", "Hello :name"),
                ("items", ":count item|:count items"),
                ("only", "same"),
            ],
        );
        l.insert("fr", [("hi", "Salut :name")]);
        l.insert("pt", [("hi", "Ola :name")]);
        l
    }

    #[test]
    fn trans_fallback_and_missing() {
        let mut l = sample();
        assert_eq!(l.trans("hi", &[("name", "A")]), "Hello A");
        l.set_locale("fr");
        assert_eq!(l.trans("hi", &[("name", "A")]), "Salut A");
        assert_eq!(l.trans("only", &[]), "same", "falls back to en");
        assert_eq!(l.trans("nope", &[]), "nope");
        l.set_locale("../../etc/passwd");
        assert_eq!(l.trans("hi", &[("name", "A")]), "Hello A", "unknown locale");
        assert_eq!(l.trans_in("pt-BR", "hi", &[("name", "A")]), "Ola A");
        assert_eq!(l.trans_in("pt_br", "hi", &[("name", "A")]), "Ola A");
        assert_eq!(l.trans_in("", "hi", &[("name", "A")]), "Hello A");
    }

    #[test]
    fn placeholders_single_pass() {
        let l = sample();
        // a value containing another placeholder is not re-expanded; unknown ones stay
        assert_eq!(l.trans("hi", &[("name", ":name")]), "Hello :name");
        assert_eq!(fill("a :x b :y: c:", &[("x", "1")]), "a 1 b :y: c:");
        assert_eq!(fill("time 10:30", &[("30", "x")]), "time 10x");
    }

    #[test]
    fn choice() {
        let l = sample();
        assert_eq!(l.trans_choice("items", 1, &[]), "1 item");
        assert_eq!(l.trans_choice("items", 0, &[]), "0 items");
        assert_eq!(l.trans_choice("items", 5, &[]), "5 items");
        assert_eq!(l.trans_choice("only", 5, &[]), "same");
        assert_eq!(l.trans_choice("zzz", 5, &[]), "zzz");
    }

    #[test]
    fn negotiate_q_values() {
        let l = sample();
        assert_eq!(l.negotiate("fr-CA,fr;q=0.9,en;q=0.8"), "fr");
        assert_eq!(l.negotiate("de, en;q=0.4, pt;q=0.7"), "pt");
        assert_eq!(l.negotiate("fr;q=0, en;q=0.1"), "en", "q=0 refused");
        assert_eq!(l.negotiate("de, ja;q=0.5"), "en", "no match -> fallback");
        assert_eq!(l.negotiate("*"), "en");
        assert_eq!(l.negotiate(""), "en");
        assert_eq!(
            l.negotiate(";;q=,,=x, fr;q=abc"),
            "en",
            "garbage never panics"
        );
    }

    #[test]
    fn load_dir_and_traversal() {
        let ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("ryuk-lang-{ns}"));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("en.json"), r#"{"hi":"Hello :name"}"#).unwrap();
        std::fs::write(dir.join("fr.json"), r#"{"hi":"Salut :name"}"#).unwrap();
        std::fs::write(dir.join("bad name.json"), r#"{"hi":"x"}"#).unwrap();
        let mut l = Lang::load_dir(&dir, "en").unwrap();
        assert_eq!(l.locales(), ["en", "fr"]);
        assert_eq!(l.trans_in("fr", "hi", &[("name", "Z")]), "Salut Z");

        for bad in [
            "../en",
            "a/b",
            "a\\b",
            "",
            "..",
            ".x",
            "en\0",
            &"a".repeat(36),
        ] {
            assert!(!valid_locale(bad), "{bad:?}");
            assert!(matches!(
                l.load_locale(&dir, bad),
                Err(LangError::BadLocale(_))
            ));
        }
        std::fs::write(dir.join("zz.json"), r#"{"a":1}"#).unwrap();
        assert!(matches!(
            l.load_locale(&dir, "zz"),
            Err(LangError::Json { .. })
        ));
        assert!(matches!(l.load_locale(&dir, "xx"), Err(LangError::Io(_))));
        l.load_locale(&dir, "pt-BR").unwrap_err();
        std::fs::remove_file(dir.join("bad name.json")).unwrap();
        std::fs::remove_file(dir.join("zz.json")).unwrap();
        std::fs::remove_file(dir.join("en.json")).unwrap();
        std::fs::remove_file(dir.join("fr.json")).unwrap();
        std::fs::remove_dir(&dir).unwrap();
    }
}