Localised responses with Fluent
Negotiate Accept-Language in an extractor, translate with fluent, and localise the problem document in a global ErrorHandler.
An API that serves several languages needs the caller's preferred language in every handler and in every error the framework renders. An Accept-Language extractor gives handlers the preference. A singleton Translator holds the Fluent bundles, and a global error handler replaces the detail of the problem document with its translation.
This recipe compiled and ran against fluent-bundle 0.16.0, fluent-langneg 0.13.1 and unic-langid 0.9.6 with ulo 0.1.0-alpha.3.
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
ulo-http-hyper = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
ulo-transport = "=0.1.0-alpha.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
fluent-bundle = "0.16"
fluent-langneg = "0.13"
unic-langid = { version = "0.9", features = ["macros"] }fluent-langneg 0.14 is built on icu_locid, whose LanguageIdentifier is a different type from the unic-langid one that fluent-bundle 0.16 uses, and the two do not convert. Use 0.13 until fluent-bundle moves.
The code
use std::borrow::Cow;
use std::fmt;
use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::{FluentArgs, FluentResource};
use fluent_langneg::{NegotiationStrategy, negotiate_languages};
use ulo::{App, AppBuilder, BoxError, Dep, ErrorHandler, AnyErrorHandler, controller, handlers, injectable, module};
use ulo_http::{CallError, Classify, ErrorKind, ExtractError, FromCall, Http, HttpCx, HeaderValue};
use unic_langid::{LanguageIdentifier, langid};
const EN: &str = "
greeting = Hello, { $name }.
out-of-stock = SKU { $sku } is sold out.
error-not-found = Nothing is served at this address.
error-forbidden = You may not do that.
";
const FR: &str = "
greeting = Bonjour, { $name }.
out-of-stock = La référence { $sku } est épuisée.
error-not-found = Rien n'est servi à cette adresse.
error-forbidden = Vous n'avez pas le droit de faire cela.
";
/// The languages the caller asked for, best first, read from `Accept-Language`. A call without
/// the header asks for nothing, which negotiates to the default.
pub struct Locale(pub Vec<LanguageIdentifier>);
impl Locale {
pub fn of(cx: &HttpCx) -> Locale {
let asked = cx.headers().get("accept-language").and_then(|value| value.to_str().ok());
Locale(asked.map(by_weight).unwrap_or_default())
}
}
/// `fluent_langneg::accepted_languages::parse` keeps header order and drops the weights, so
/// `fr;q=0.2, en;q=0.9` would negotiate to French. This orders by weight and drops `q=0`.
fn by_weight(header: &str) -> Vec<LanguageIdentifier> {
let mut asked: Vec<(f32, LanguageIdentifier)> = header
.split(',')
.filter_map(|entry| {
let mut parts = entry.split(';');
let tag = parts.next()?.trim().parse::<LanguageIdentifier>().ok()?;
let weight = parts
.find_map(|param| param.trim().strip_prefix("q="))
.map_or(Some(1.0), |q| q.trim().parse::<f32>().ok())?;
(weight > 0.0).then_some((weight, tag))
})
.collect();
asked.sort_by(|a, b| b.0.total_cmp(&a.0));
asked.into_iter().map(|(_, tag)| tag).collect()
}
impl FromCall<Http> for Locale {
async fn from_call(cx: &HttpCx) -> Result<Self, ExtractError> {
Ok(Locale::of(cx))
}
}
pub struct Translator {
bundles: Vec<(LanguageIdentifier, FluentBundle<FluentResource>)>,
default: LanguageIdentifier,
}
impl Translator {
pub fn new() -> Translator {
let bundle = |id: LanguageIdentifier, source: &str| {
let mut bundle = FluentBundle::new_concurrent(vec![id.clone()]);
// The isolation marks Fluent wraps around an argument show up in a JSON body.
bundle.set_use_isolating(false);
bundle.add_resource(FluentResource::try_new(source.to_owned()).expect("the resource parses")).expect("no id repeats");
(id, bundle)
};
Translator { bundles: vec![bundle(langid!("en"), EN), bundle(langid!("fr"), FR)], default: langid!("en") }
}
/// The language a caller is answered in: the best of what it asked for that a bundle exists for.
pub fn negotiate(&self, locale: &Locale) -> &LanguageIdentifier {
let available: Vec<&LanguageIdentifier> = self.bundles.iter().map(|(id, _)| id).collect();
negotiate_languages(&locale.0, &available, Some(&&self.default), NegotiationStrategy::Filtering)
.first()
.map_or(&self.default, |best| **best)
}
/// The message `id` in the caller's language, or `None` when the bundle has no such message.
pub fn say(&self, locale: &Locale, id: &str, args: Option<&FluentArgs<'_>>) -> Option<String> {
let language = self.negotiate(locale);
let (_, bundle) = self.bundles.iter().find(|(id, _)| id == language)?;
let pattern = bundle.get_message(id)?.value()?;
let mut problems = Vec::new();
let text: Cow<'_, str> = bundle.format_pattern(pattern, args, &mut problems);
problems.is_empty().then(|| text.into_owned())
}
}
#[derive(Debug, Classify)]
#[classify(conflict)]
pub struct OutOfStock(pub u32);
impl fmt::Display for OutOfStock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "sku {} is out of stock", self.0)
}
}
impl std::error::Error for OutOfStock {}
/// Replaces the `detail` of every error with its translation and leaves the kind, details and
/// challenge as they were. Nothing is claimed: the transport still renders the problem document.
#[injectable]
pub struct Localise {
translator: Dep<Translator>,
}
impl ErrorHandler<Http> for Localise {
async fn handle(&self, err: BoxError, cx: &HttpCx) -> Result<ulo_http::Response, BoxError> {
let call = CallError::from_boxed(err);
let locale = Locale::of(cx);
let mut args = FluentArgs::new();
let id = match call.source_as::<OutOfStock>() {
Some(OutOfStock(sku)) => {
args.set("sku", *sku);
"out-of-stock".to_owned()
}
None => format!("error-{}", call.kind().as_str().replace('_', "-")),
};
let Some(text) = self.translator.say(&locale, &id, Some(&args)) else { return Err(Box::new(call)) };
let mut reshaped = match (call.kind(), call.challenge()) {
(ErrorKind::Unauthorized, Some(challenge)) => CallError::unauthorized(challenge),
(kind, _) => CallError::new(kind, text),
};
reshaped = reshaped.with_details(call.details().clone());
let language = self.translator.negotiate(&locale).to_string();
if let Ok(value) = HeaderValue::from_str(&language) {
cx.response_headers().insert("content-language", value);
}
Err(Box::new(reshaped))
}
}
#[controller]
pub struct ShopController {
translator: Dep<Translator>,
}
#[handlers]
impl ShopController {
#[ulo_http::get("/hello/{name}")]
fn hello(&self, ulo_http::Path(name): ulo_http::Path<String>, locale: Locale) -> String {
let mut args = FluentArgs::new();
args.set("name", name);
self.translator.say(&locale, "greeting", Some(&args)).unwrap_or_default()
}
#[ulo_http::get("/stock/{sku}")]
fn stock(&self, ulo_http::Path(sku): ulo_http::Path<u32>) -> Result<String, OutOfStock> {
Err(OutOfStock(sku))
}
}
#[module(
providers = [
with = || Translator::new(),
Localise,
into AnyErrorHandler<Http>: [Localise],
],
controllers = [ShopController],
)]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}What each seam does
LocaleimplementsFromCall<Http>, solocale: Localeis a handler parameter. It never fails: no header gives an empty list, which negotiates to the default.Locale::ofdoes the parsing so that the error handler, which has anHttpCxand no extractor machinery, reads the same value.by_weightorders the header byqand dropsq=0.fluent_langneg::accepted_languages::parsekeeps header order and ignores the weights, sofr;q=0.2, en;q=0.9negotiates to French with it. The test below covers that header.Translator::negotiateasksnegotiate_languageswith theFilteringstrategy for the best language that a bundle exists for, and falls back to the default when none matches.FluentBundlecomes fromfluent_bundle::concurrent, the variant used for a bundle that a singleton shares across calls.set_use_isolating(false)removes the Unicode isolation marks Fluent puts around each argument, which otherwise appear in JSON.Localiseis registered twice in the module: as a provider, soDep<Translator>is injected, and underinto AnyErrorHandler<Http>, which makes it the global error handler.- The handler never claims an error. It rebuilds the
CallErrorwith the translated message, the same kind and the same details. It returns the rebuilt error asErr, so the transport renders the problem document as it always does, with the status the kind gives. For anUnauthorizedit rebuilds throughCallError::unauthorizedwith the original challenge. - The message id comes from the error. A typed domain error (
OutOfStock, found throughsource_as) names its own id and supplies the arguments. Any other error useserror-plus its kind with_replaced by-. An id the bundle lacks leaves the error as it was. cx.response_headers()setscontent-languageon the response. It reached the problem document in the run below.
Tests
The tests use the example support crate in the repository (ex_support::start and call); any HTTP client does the same.
use ex_support::http::{Call, call};
use ex_support::start;
use r3::i18n::builder;
async fn answer(addr: std::net::SocketAddr, path: &str, language: Option<&str>) -> (u16, Option<String>, String) {
let mut request = Call::get(path);
if let Some(language) = language {
request = request.header("accept-language", language);
}
let reply = call(addr, request).await;
let content_language = reply.headers.iter().find(|(name, _)| name == "content-language").map(|(_, value)| value.clone());
(reply.status, content_language, reply.body)
}
#[tokio::test]
async fn a_call_is_answered_in_the_language_it_ranks_highest_among_those_offered() {
let server = start(builder()).await;
let addr = server.addr;
assert_eq!(answer(addr, "/hello/ada", Some("fr-CA,fr;q=0.9,en;q=0.5")).await.2, "Bonjour, ada.");
assert_eq!(answer(addr, "/hello/ada", Some("de, fr;q=0.5")).await.2, "Bonjour, ada.");
assert_eq!(answer(addr, "/hello/ada", Some("fr;q=0.2, en;q=0.9")).await.2, "Hello, ada.");
assert_eq!(answer(addr, "/hello/ada", Some("de")).await.2, "Hello, ada.");
assert_eq!(answer(addr, "/hello/ada", None).await.2, "Hello, ada.");
server.stop().await.unwrap();
}
#[tokio::test]
async fn the_problem_document_carries_the_translated_detail_and_the_original_status() {
let server = start(builder()).await;
let (status, language, body) = answer(server.addr, "/stock/7", Some("fr")).await;
assert_eq!((status, language.as_deref()), (409, Some("fr")));
let document: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(document["detail"], "La référence 7 est épuisée.");
assert_eq!(document["title"], "Conflict");
let (status, _, body) = answer(server.addr, "/nowhere", Some("fr")).await;
assert_eq!(status, 404);
assert!(body.contains("Rien n'est servi à cette adresse."), "{body}");
server.stop().await.unwrap();
}The French request for /stock/7 answered:
409 content-language: fr
{"type":"about:blank","title":"Conflict","status":409,"detail":"La référence 7 est épuisée."}Failure modes
- The
titlestays English. The transport writes it from the status phrase after the handler returns, and an error carries no field for it. A document with a translatedtitleneeds the handler to claim the error with a response of its own, which also means mapping the kind to a status in the handler. - A status set by
with_http_statuson the original error is not copied into the rebuiltCallError: the handler reads the getter only through a doc-hidden method. The rebuilt error renders with its kind's status, so applywith_http_statusagain in the handler for such an error. - Only the kinds in the bundle are translated. A kind with no
error-message keeps its original English text. Accept-Language: dewith no German bundle answers in the default language. The extractor reports no mismatch.- Messages on the success path call
translator.say(..)and getNonefor a missing id. The example answers an empty string; production code decides its own fallback.
Reference
- Custom extractors:
FromCallandOption<T>over it. - Error handling:
CallError, what a handler receives, and the problem document. - Providers: the
with = ||factory used for theTranslator.
Error reporting with Sentry
Report server faults to Sentry with the sentry-tracing error layer, fed by a global ErrorHandler that logs and passes every error on.
A client as a provider
The lifecycle a module writes for a client no store module covers, what the store modules add on top, and a hand-built SOAP client as the worked example.