Internationalization (id_effect_i18n)

A service that answers people in their own language needs three things: translated messages with the grammar of each language (plurals above all), a rule for what happens when a translation is missing, and a way to know, deep inside a handler, which language this request wants. id_effect_i18n provides them over Project Fluent:

  1. Catalog: Fluent resources per locale, parsed once at startup, with a fallback chain and a completeness check.
  2. CLDR plurals through Fluent selectors, with the rules of the locale a message comes from.
  3. CurrentLocale: a capability in the environment whose value is per fiber, switched for one request with with_locale; translate formats a message in it.
[dependencies]
id_effect_i18n = "0.13"

Messages and plurals

A Fluent resource is a list of messages. Placeables ({ $name }) insert arguments; a selector ({ $count -> … }) picks a variant, and for a number the variant keys are the CLDR plural categories of the language: English has one and other, Polish one, few, many and other, Arabic all six, Japanese only other. The translator writes the variants the language needs; the code passes a number.

#![allow(unused)]
fn main() {
use id_effect_i18n::{Args, Catalog, Locale};

let en = Locale::parse("en").unwrap();
let pl = Locale::parse("pl").unwrap();
let ar = Locale::parse("ar").unwrap();
let catalog = Catalog::builder(en.clone())
    .embedded(en.clone(), "en/app.ftl", "
files = { $count ->
    [one] { $count } file
   *[other] { $count } files
}
")
    .embedded(pl.clone(), "pl/app.ftl", "
files = { $count ->
    [one] { $count } plik
    [few] { $count } pliki
   *[many] { $count } plików
}
")
    .embedded(ar.clone(), "ar/app.ftl", "
files = { $count ->
    [zero] لا ملفات
    [one] ملف واحد
    [two] ملفان
    [few] { $count } ملفات
   *[many] { $count } ملفًا
    [other] { $count } ملف
}
")
    .use_isolating(false) // plain strings for the asserts below; keep it on for UI text
    .build()
    .expect("every resource parses");

let files = |locale: &Locale, n: u32| catalog.format(locale, "files", &Args::new().with("count", n));
assert_eq!(files(&en, 1), "1 file");
assert_eq!(files(&en, 5), "5 files");
assert_eq!(files(&pl, 3), "3 pliki");
assert_eq!(files(&pl, 5), "5 plików");
assert_eq!(files(&pl, 22), "22 pliki");
assert_eq!(files(&ar, 2), "ملفان");
assert_eq!(files(&ar, 11), "11 ملفًا");
assert_eq!(files(&ar, 100), "100 ملف");
}

Args takes text and numbers (with("count", n) for any integer or float). Attributes are keys too: catalog.format(&locale, "form.title", &args) formats the .title attribute of form.

Arguments are wrapped in Unicode bidi isolation marks (U+2068 … U+2069) by default, so a right-to-left name cannot reorder the sentence around it. Turn it off (use_isolating(false)) only for output that is never displayed in a bidirectional context, such as logs or tests.

Loading a catalog

Resources come from the binary or from disk, and both are read once, at startup:

  • embedded(locale, origin, source) adds a &'static str, usually include_str!("../locales/de/app.ftl"). Nothing is read at run time, and the binary is the deployment unit.
  • allow_dir(dir)? allowlists a directory; dir(dir)? then loads every <locale>/*.ftl below it (each subdirectory is named after its locale: en, de, pt-BR), and file(locale, path)? one file. A path is resolved first (.. and symbolic links), and a file outside every allowlisted directory is refused with CatalogError::PathOutsideAllowlist. Only .ftl files of at most MAX_RESOURCE_BYTES (1 MiB) are read.

build() parses everything. A Fluent syntax error (CatalogError::Parse), a message defined twice in one locale (CatalogError::Conflict) or a default locale without resources (CatalogError::MissingDefault) fails the build, so a broken translation stops the deploy instead of showing up in a response.

#![allow(unused)]
fn main() {
use id_effect_i18n::{Catalog, CatalogError, Locale};

let en = Locale::parse("en").unwrap();
let broken = Catalog::builder(en.clone())
    .embedded(en.clone(), "en/app.ftl", "greeting = Hello, { $name")
    .build();
assert!(matches!(broken, Err(CatalogError::Parse { .. })));

// Nothing allowlisted: no path is read at all.
let refused = Catalog::builder(en).file(Locale::parse("de").unwrap(), "/etc/passwd.ftl");
assert!(refused.is_err());
}

The locale a request asks for never becomes a path: catalogs are keyed by parsed Locale values, Locale::parse accepts at most 16 bytes of ASCII subtags (language[-Script][-REGION]), and the files were read before the first request arrived (ADR 0013 R4).

Fallback and the startup check

A lookup tries, in order, the requested locale, its language and the default locale: de-AT → de → en. A regional resource only needs the messages that differ. A key that no locale of the chain defines is returned as the key itself by format (and as None by lookup, which also tells which locale answered).

Catalog::check() is the startup check: it reports every key of the default locale that a non-default locale lacks, where neither the locale nor its language defines it, which is exactly the text a user of that locale would see in the default language. Log it at startup, fail CI on it, or call require_complete() on the builder to make an incomplete catalog fail build.

#![allow(unused)]
fn main() {
use id_effect_i18n::{Args, Catalog, Locale};

let en = Locale::parse("en").unwrap();
let de = Locale::parse("de").unwrap();
let de_at = Locale::parse("de-AT").unwrap();
let catalog = Catalog::builder(en.clone())
    .embedded(en.clone(), "en/app.ftl", "greeting = Hello!\nfarewell = Goodbye!\nhelp = Help")
    .embedded(de.clone(), "de/app.ftl", "greeting = Hallo!\nhelp = Hilfe")
    .embedded(de_at.clone(), "de-AT/app.ftl", "greeting = Servus!")
    .build()
    .unwrap();

let none = Args::new();
assert_eq!(catalog.format(&de_at, "greeting", &none), "Servus!"); // de-AT
assert_eq!(catalog.format(&de_at, "help", &none), "Hilfe"); // de
let farewell = catalog.lookup(&de_at, "farewell", &none).unwrap(); // en
assert_eq!((farewell.text.as_str(), farewell.locale.as_str()), ("Goodbye!", "en"));
assert_eq!(catalog.format(&de_at, "no-such-key", &none), "no-such-key");

let report = catalog.check();
assert_eq!(report.missing_in(&de).collect::<Vec<_>>(), ["farewell"]);
assert_eq!(report.missing_in(&de_at).collect::<Vec<_>>(), ["farewell"]); // help comes from de
println!("{report}"); // 2 missing key(s): de: farewell; de-AT: farewell;
}

The locale of a request: CurrentLocale and with_locale

Passing a locale argument through every function that might format a message does not scale. CurrentLocale is a capability: provide it once in the application environment with the default locale, next to the Catalog. Its value is fiber-local (an id_effect FiberRef, never a thread-local): with_locale(locale, effect) runs one effect, typically a request handler, with the locale switched, restores the previous value however the effect ends, and every fiber the effect forks inherits the switch. Two requests running at the same time each see their own locale.

current_locale() reads it; translate(key, args) formats a message from the Catalog in it.

#![allow(unused)]
fn main() {
use id_effect::{Effect, Exit, HCons, HNil, Never, hlist, run_test, zip_par};
use id_effect_i18n::{Args, Catalog, CurrentLocale, Locale, current_locale, translate, with_locale};

type AppEnv = HCons<Catalog, HCons<CurrentLocale, HNil>>;

/// Deep in the handler: no locale parameter, it comes from the environment.
fn welcome(name: &str) -> Effect<String, Never, AppEnv> {
    translate("welcome", Args::new().with("name", name.to_owned()))
}

/// One request in the locale the edge chose for it.
fn handle(locale: Locale, name: &'static str) -> Effect<String, Never, AppEnv> {
    with_locale(locale, welcome(name))
}

let en = Locale::parse("en").unwrap();
let de = Locale::parse("de").unwrap();
let catalog = Catalog::builder(en.clone())
    .embedded(en.clone(), "en/app.ftl", "welcome = Welcome, { $name }!")
    .embedded(de.clone(), "de/app.ftl", "welcome = Willkommen, { $name }!")
    .use_isolating(false)
    .build()
    .unwrap();
let env = hlist![catalog, CurrentLocale::new(en.clone())];

// Two concurrent requests, two locales; the parent fiber keeps the default.
let requests = zip_par(handle(de, "Ada"), handle(en.clone(), "Grace"))
    .flat_map(|pair| current_locale().map(move |after| (pair, after)));
match run_test(requests.provide_all(env)) {
    Exit::Success(((de_text, en_text), after)) => {
        assert_eq!(de_text, "Willkommen, Ada!");
        assert_eq!(en_text, "Welcome, Grace!");
        assert_eq!(after, en);
    }
    other => panic!("{other:?}"),
}
}

Where the locale comes from is the edge's decision: a user setting, a cookie, or the Accept-Language header negotiated against Catalog::supports (the axum feature adds a layer that does this and calls with_locale for each request). Choose from the catalog's locales rather than echoing input: an unsupported locale is harmless for lookups (they fall back), but it is what current_locale() reports to the rest of the request.

On the web: which language does this request want?

A browser states its languages in Accept-Language (de-AT, de;q=0.9, en;q=0.5); a language switcher usually remembers the choice in a cookie; a signed-in user may have a stored preference. negotiate::Negotiator turns those three untrusted inputs into one locale of an allowlist, trying the preference first, then the cookie, then the header, then the default:

#![allow(unused)]
fn main() {
use id_effect_i18n::Locale;
use id_effect_i18n::negotiate::{LocaleSource, Negotiator, parse_accept_language};

let en = Locale::parse("en").unwrap();
let de = Locale::parse("de").unwrap();
let pt_br = Locale::parse("pt-BR").unwrap();
let negotiator = Negotiator::new(en.clone(), [de.clone(), pt_br.clone()]);

// The best supported range wins: `de-AT` reaches `de`, `pt` reaches `pt-BR`.
let header = "fr-CH, fr;q=0.9, de-AT;q=0.8, en;q=0.5";
assert_eq!(negotiator.select(None, None, Some(header)), (de.clone(), LocaleSource::AcceptLanguage));
assert_eq!(negotiator.match_accept_language("pt"), Some(pt_br));

// A cookie beats the header, a preference beats both; values outside the allowlist are skipped.
assert_eq!(negotiator.select(None, Some("en"), Some(header)), (en.clone(), LocaleSource::Cookie));
assert_eq!(negotiator.select(Some("fr"), Some("ja"), Some("de")).1, LocaleSource::AcceptLanguage);
assert_eq!(negotiator.select(Some("../x"), None, Some("fr")), (en, LocaleSource::Default));

// The parser itself (the fuzzing entry point): ranges best first, `q=0` dropped.
let ranges = parse_accept_language("en;q=0.5, de, fr;q=0").unwrap();
assert_eq!(ranges.iter().map(|r| r.quality()).collect::<Vec<_>>(), [1000, 500]);
}

Matching is fluent-langneg's lookup: an exact match, then the supported locale as a range (de-CH → de), then likely subtags (pt → pt-BR), then a sibling region.

The header is attacker-controlled, so its parse is bounded (ADR 0013 R4): at most MAX_ACCEPT_LANGUAGE_BYTES (256) bytes and MAX_ACCEPT_LANGUAGE_RANGES (32) ranges. Beyond either limit the whole header is ignored and the request gets the default locale; it is never truncated and half-parsed. Each tag goes through Locale::parse (16 bytes of ASCII subtags), and the result is always a member of the allowlist, so nothing from the header reaches a lookup or a path.

The axum layer (feature axum)

id_effect_i18n::axum::LocaleLayer runs the negotiation for every request, with the catalog's locales as the allowlist (or a narrower Negotiator through LocaleLayer::with_negotiator). It leaves the decision in three places:

  • a Localizer (the catalog plus the negotiated locale) in the request extensions; it is also an extractor, and the input of t in views;
  • a CurrentLocale override in the request's RequestCaps, so an effect handler run through execute_with_request_caps finds the negotiated locale in its DynEnv; with a typed environment, localizer.scope(effect) calls with_locale for you;
  • the LocaleSource that decided (also an extractor), for logging or a "detected language" hint.

The response gets Content-Language and Vary: accept-language, cookie, so a cache keeps one copy per language.

#![allow(unused)]
fn main() {
use std::convert::Infallible;

use axum::{Router, extract::State, routing::get};
use id_effect::{DynEnv, Effect, succeed};
use id_effect_axum::{RequestCaps, execute_with_request_caps};
use id_effect_i18n::axum::LocaleLayer;
use id_effect_i18n::{Args, Catalog, CurrentLocale, Locale, Localizer};

let en = Locale::parse("en").unwrap();
let de = Locale::parse("de").unwrap();
let catalog = Catalog::builder(en.clone())
    .embedded(en.clone(), "en.ftl", "hello = Hello!")
    .embedded(de, "de.ftl", "hello = Hallo!")
    .build()
    .unwrap();

// A plain handler takes the `Localizer`.
async fn hello(localizer: Localizer) -> String {
    localizer.format("hello", &Args::new())
}

// An effect handler reads the negotiated `CurrentLocale` from its environment.
fn locale(env: &mut DynEnv) -> Effect<String, Infallible, DynEnv> {
    match env.try_get::<CurrentLocale>() {
        Ok(current) => current.get().map(|l: Locale| l.to_string()),
        Err(_) => succeed(String::new()),
    }
}

let base = DynEnv::new().with(CurrentLocale::new(en));
let app: Router = Router::new()
    .route("/", get(hello))
    .route("/locale", get(|st: State<DynEnv>, caps: RequestCaps| execute_with_request_caps(st, caps, locale)))
    .with_state(base)
    .layer(
        LocaleLayer::new(catalog)
            .cookie("lang") // default: `locale`; `.without_cookie()` to ignore cookies
            .preference(|parts| parts.headers.get("x-user-lang")?.to_str().ok().map(str::to_owned)),
    );
let _ = app;
}

In a real application the preference comes from the authenticated user (an extension the authentication layer inserted before this one), not from a request header.

Translated messages in views (feature maud)

t(&localizer, "id", args) returns a Message, which implements maud::Render: a view interpolates it like any other value.

#![allow(unused)]
fn main() {
use id_effect_i18n::{Args, Catalog, Locale, Localizer, t};
use maud::html;

let en = Locale::parse("en").unwrap();
let catalog = Catalog::builder(en.clone())
    .embedded(en.clone(), "en.ftl", "greeting = Hello, { $name }!")
    .build()
    .unwrap();
let l = Localizer::new(catalog, en);

let name = "<script>alert(1)</script>"; // user input
let page = html! { h1 { (t(&l, "greeting", Args::new().with("name", name))) } };
assert_eq!(
    page.into_string(),
    "<h1>Hello, \u{2068}&lt;script&gt;alert(1)&lt;/script&gt;\u{2069}!</h1>"
);
}

A message renders as text (ADR 0013 R9): the formatted message, arguments and translation alike, goes through maud's escaping, so neither a user-supplied argument nor a compromised translation can inject markup; markup belongs in the template. The arguments keep the catalog's bidi isolation (U+2068 … U+2069), which stays on unless the catalog opts out.

Translated validation errors (feature schema)

Schema decoding reports each issue as a ParseError (a path and an English message). SchemaErrorCode::classify recovers what went wrong from every message the built-in decoders, validators and #[derive(Schema)] produce, maps it to a Fluent message id (schema-min-length, schema-missing-field, schema-email, …) with its arguments ($field, $path, $min, …), and schema_messages() adds the English and German catalogs shipped with the crate. translate_parse_errors (or localizer.parse_errors(&errors), or the effect localize_parse_errors in the current locale) returns the same ParseErrors, translated, ready for a form or an RFC 9457 problem body.

#![allow(unused)]
fn main() {
use id_effect::schema::{ParseErrors, Unknown, email, min_length, refine, i64, string};
use id_effect_i18n::{Catalog, Locale, SchemaMessages, translate_parse_errors};

let en = Locale::parse("en").unwrap();
let de = Locale::parse("de").unwrap();
let catalog = Catalog::builder(en.clone())
    .schema_messages()
    // A custom refinement message can be a message id of the application's own catalog.
    .embedded(en, "app/en.ftl", "age-positive = Age must be positive.")
    .embedded(de.clone(), "app/de.ftl", "age-positive = Das Alter muss positiv sein.")
    .use_isolating(false)
    .require_complete()
    .build()
    .unwrap();

let mut issues = Vec::new();
let name = min_length(string::<()>(), 3).decode_unknown_all(&Unknown::String("Al".into()));
issues.extend(name.unwrap_err().prefix("name").issues);
let mail = email(string::<()>()).decode_unknown_all(&Unknown::String("nope".into()));
issues.extend(mail.unwrap_err().prefix("email").issues);
let age = refine(i64::<()>(), |n| *n > 0, "age-positive").decode_unknown_all(&Unknown::I64(-1));
issues.extend(age.unwrap_err().prefix("age").issues);

let german = translate_parse_errors(&catalog, &de, &ParseErrors::new(issues));
let messages: Vec<_> = german.issues.iter().map(|i| (i.path.as_str(), i.message.as_str())).collect();
assert_eq!(messages, [
    ("name", "Muss mindestens 3 Zeichen lang sein."),
    ("email", "Muss eine gültige E-Mail-Adresse sein."),
    ("age", "Das Alter muss positiv sein."),
]);
}

A message without a translation in the chain is kept as it was, so adding a locale never turns an error into an empty string. The shipped messages are complete in both languages (require_complete passes); to reword one, embed your own copy of locales/schema/*/schema.ftl instead of calling schema_messages().

The example cargo run -p id_effect_i18n --all-features --example i18n_web puts it together: a negotiated, cookie-switchable sign-up page in English and German with translated validation errors.

Summary

PieceAPINotes
CatalogCatalog::builder(default) · embedded / allow_dir + dir / file · build()parsed once; parse errors fail startup
PluralsFluent selectors { $n -> [one] … *[other] … }CLDR rules of the message's locale
Fallbacklookup / format / fallback_chainrequested → language → default
Startup checkcheck() → CatalogReport · require_complete()keys a locale shows in the default language
Locale of a requestCurrentLocale::new(default) · with_locale · current_locale · translatefiber-local, inherited by forks
InputLocale::parse≤ 16 bytes, ASCII subtags; never a path
Negotiationnegotiate::Negotiator · select(preference, cookie, header) · parse_accept_languageallowlist only; header ≤ 256 bytes, ≤ 32 ranges or ignored
axum (axum)axum::LocaleLayer · Localizer / LocaleSource extractors · CurrentLocale in RequestCapsContent-Language, Vary
Views (maud)t(&localizer, "id", args) → Message: maud::Renderescaped text, bidi isolation on
Validation (schema)SchemaErrorCode · schema_messages() · translate_parse_errors / localize_parse_errorsen + de shipped