Skip to main content

ash_jsonapi/
i18n.rs

1//! Translation keys on errors, and the negotiated locale on the response.
2//!
3//! An error's `title` and `detail` are English prose. That is fine for a log
4//! and useless for a user interface that has to render the same failure in
5//! whatever language its user reads, so a client is left matching on English
6//! substrings — which breaks the moment the wording is improved.
7//!
8//! This crate does not translate. It emits a **stable key** and the **params**
9//! the message interpolates, and the client renders them against its own
10//! catalog:
11//!
12//! ```json
13//! {
14//!   "status": "422",
15//!   "code": "invalid_attribute",
16//!   "title": "Invalid attribute",
17//!   "detail": "must be 80 characters or fewer",
18//!   "source": { "pointer": "/data/attributes/name" },
19//!   "meta": {
20//!     "i18n": {
21//!       "key": "todo.name.too_long",
22//!       "params": { "max": 80 }
23//!     }
24//!   }
25//! }
26//! ```
27//!
28//! `title` and `detail` stay exactly as they were — they are the fallback for
29//! a client with no catalog, and dropping them would break every existing
30//! consumer. The key is *additional*, which is also why it lives under `meta`:
31//! JSON:API fixes the members an error object may carry, and `meta` is the
32//! member it provides for everything else. A client that does not know about
33//! it sees an ordinary error object.
34//!
35//! # Why the server does not translate
36//!
37//! Reading `Accept-Language` and returning German prose is the other way to
38//! do this, and it is worse here: it puts a message catalog, a negotiation
39//! table and a release cycle for every wording change inside the API server,
40//! and it still cannot localize what the client composes around the message.
41//! The client already has a catalog — it renders its own UI — so the useful
42//! thing to send it is the key, not a second translation of it.
43//!
44//! What the server *does* do is record which locale the client asked for, on
45//! the document's top-level `meta`, so a response is self-describing about
46//! what it negotiated. See [`Locale`].
47
48use std::collections::BTreeMap;
49
50use serde::{Deserialize, Serialize};
51
52/// A translation key and the params its message interpolates.
53///
54/// Attached to a [`JsonApiError`](crate::JsonApiError) with
55/// [`translate`](crate::JsonApiError::translate), and serialized under the
56/// error object's `meta.i18n`.
57///
58/// The key is yours: this crate never invents one, and never rewrites one.
59/// Keep it stable across wording changes — that is the whole point of it —
60/// and namespace it however your catalog is organized.
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub struct Translation {
63    /// The catalog key, e.g. `todo.name.too_long`.
64    pub key: String,
65    /// The values the message interpolates, e.g. `{ "max": 80 }`.
66    ///
67    /// Omitted from the response when empty, so a message with no
68    /// placeholders does not carry an empty object.
69    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
70    pub params: BTreeMap<String, serde_json::Value>,
71}
72
73impl Translation {
74    /// A key with no params — a message with nothing to interpolate.
75    ///
76    /// ```
77    /// use ash_jsonapi::i18n::Translation;
78    ///
79    /// let t = Translation::new("todo.not_found");
80    /// assert_eq!(t.key, "todo.not_found");
81    /// assert!(t.params.is_empty());
82    /// ```
83    pub fn new(key: impl Into<String>) -> Self {
84        Self {
85            key: key.into(),
86            params: BTreeMap::new(),
87        }
88    }
89
90    /// Add one interpolation param.
91    ///
92    /// ```
93    /// use ash_jsonapi::i18n::Translation;
94    ///
95    /// let t = Translation::new("todo.name.too_long").param("max", 80);
96    /// assert_eq!(t.params["max"], 80);
97    /// ```
98    #[must_use]
99    pub fn param(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
100        self.params.insert(key.into(), value.into());
101        self
102    }
103}
104
105/// The locale the client asked for, as negotiated from `Accept-Language`.
106///
107/// Recorded on the response's top-level `meta.lang` so a response says which
108/// locale it was produced for, and carried on the [`Context`](crate::Context)
109/// so a handler that *does* have a catalog can consult it.
110///
111/// This is the client's request, not a promise: nothing in this crate
112/// translates, so `lang` describes what was asked for and the
113/// [`Translation`] keys are what make honouring it possible.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Locale(String);
116
117impl Locale {
118    /// The best match from an `Accept-Language` header value.
119    ///
120    /// Ranked by the `q` values the header carries, highest first, with a
121    /// missing `q` meaning `q=1` as [RFC 9110 §12.4.2] specifies. `*` is
122    /// skipped — it names no locale to record — and so is `q=0`, which is a
123    /// client saying it will *not* accept that language.
124    ///
125    /// Returns `None` when the header is absent, empty, or names nothing
126    /// usable; the response then carries no `lang` rather than a guess.
127    ///
128    /// ```
129    /// use ash_jsonapi::i18n::Locale;
130    ///
131    /// let best = Locale::negotiate("de-DE,de;q=0.9,en;q=0.8").unwrap();
132    /// assert_eq!(best.as_str(), "de-DE");
133    ///
134    /// // `q` ordering wins over position:
135    /// let best = Locale::negotiate("en;q=0.5, fr;q=0.9").unwrap();
136    /// assert_eq!(best.as_str(), "fr");
137    ///
138    /// assert!(Locale::negotiate("*").is_none());
139    /// ```
140    ///
141    /// [RFC 9110 §12.4.2]: https://www.rfc-editor.org/rfc/rfc9110#section-12.4.2
142    pub fn negotiate(header: &str) -> Option<Self> {
143        let mut best: Option<(f32, usize, &str)> = None;
144
145        for (position, entry) in header.split(',').enumerate() {
146            let mut parts = entry.split(';');
147
148            let tag = parts.next()?.trim();
149            if tag.is_empty() || tag == "*" || !is_language_tag(tag) {
150                continue;
151            }
152
153            // `;q=` is the only parameter that concerns us; anything else on
154            // the entry is ignored rather than treated as a parse failure.
155            let quality = parts
156                .find_map(|part| part.trim().strip_prefix("q=")?.trim().parse::<f32>().ok())
157                .unwrap_or(1.0);
158
159            // `q=0` means "not acceptable", so it never wins.
160            if quality <= 0.0 {
161                continue;
162            }
163
164            // Strictly greater, so an equal `q` keeps the earlier entry —
165            // header order is the tie-break the RFC leaves to the server.
166            let better = match best {
167                Some((best_q, _, _)) => quality > best_q,
168                None => true,
169            };
170            if better {
171                best = Some((quality, position, tag));
172            }
173        }
174
175        best.map(|(_, _, tag)| Self(tag.to_string()))
176    }
177
178    /// The language tag, e.g. `de-DE`.
179    pub fn as_str(&self) -> &str {
180        &self.0
181    }
182}
183
184impl std::fmt::Display for Locale {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.write_str(&self.0)
187    }
188}
189
190/// Whether a token is shaped like a language tag.
191///
192/// Deliberately strict: this value is echoed into a response body, so it is
193/// restricted to what a tag may contain rather than reflected verbatim.
194/// Length-capped for the same reason — a header is client-supplied input.
195fn is_language_tag(tag: &str) -> bool {
196    !tag.is_empty() && tag.len() <= 35 && tag.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
197}