jmap_server/i18n.rs
1//! Server side of the `urn:ietf:params:jmap:i18n` capability
2//! (draft-atwood-jmap-updates-00 §3 and §4).
3//!
4//! A backend says which accounts support localizations through
5//! [`JmapAccounts::i18n_info`](crate::JmapAccounts::i18n_info). `/get`
6//! handlers build an [`I18nProjection`] per request; it reads the
7//! `language` argument, rejects it where the draft says to, and shapes
8//! `locale` and `localizations` on every returned object. `/set` handlers
9//! build an [`I18nSet`]; backends run [`localized_update`] inside each
10//! update of a type with localizable properties.
11//!
12//! Design: `docs/design/updates.md` (decisions 27 to 31).
13
14use crate::{JmapObject, SetError, SetErrorType};
15use jmap_types::i18n::{
16 JMAP_I18N_URI, LanguageRange, LocalizableProperty, check_localizations, localized_view,
17 parse_locale, prune_stale_localizations,
18};
19use jmap_types::{JmapError, PatchObject};
20use serde_json::{Map, Value};
21
22/// What a backend supports for `urn:ietf:params:jmap:i18n` in one
23/// account, as [`JmapAccounts::i18n_info`](crate::JmapAccounts::i18n_info)
24/// returns it.
25///
26/// Build one with [`I18nInfo::new`] and the `with_*` setters.
27#[non_exhaustive]
28#[derive(Debug, Clone, Default, PartialEq, Eq)]
29pub struct I18nInfo {
30 /// The most localizations stored per object, or `None` for no limit
31 /// (§4.1: "A server MAY limit the number of localizations it stores
32 /// per object").
33 pub max_localizations: Option<usize>,
34}
35
36impl I18nInfo {
37 /// An account that supports localizations, with no limit.
38 pub fn new() -> Self {
39 Self::default()
40 }
41
42 /// Set [`max_localizations`](Self::max_localizations).
43 #[must_use]
44 pub fn with_max_localizations(mut self, max: Option<usize>) -> Self {
45 self.max_localizations = max;
46 self
47 }
48}
49
50/// `true` if `using` includes `urn:ietf:params:jmap:i18n`
51/// (draft-atwood-jmap-updates-00 §3). Capability URIs compare as exact
52/// strings (§7.1).
53pub fn uses_i18n(using: &[String]) -> bool {
54 using.iter().any(|u| u == JMAP_I18N_URI)
55}
56
57#[derive(Debug, Clone, Default, PartialEq)]
58enum Mode {
59 /// The type has no localizable properties.
60 #[default]
61 Off,
62 /// The request or the account does not use the capability: the two
63 /// properties are not returned.
64 Strip,
65 /// The capability is in use and `language` is null: stored values,
66 /// with `null` for an absent property.
67 Stored,
68 /// `language` is set: the single-language view.
69 View(Vec<LanguageRange>),
70}
71
72/// How a `Foo/get` handler returns `locale` and `localizations`
73/// (draft-atwood-jmap-updates-00 §3, §4.2.1).
74///
75/// Build one per request with [`I18nProjection::from_args`], ask the
76/// backend for [`I18nProjection::backend_properties`], then call
77/// [`I18nProjection::apply`] on every returned object before filtering it
78/// to the requested `properties`. [`handle_get`](crate::handle_get) and
79/// [`handle_get_with_metadata`](crate::handle_get_with_metadata) do all
80/// three; a type-specific `/get` handler calls them itself.
81#[derive(Debug, Clone, Default)]
82pub struct I18nProjection {
83 mode: Mode,
84 properties: &'static [LocalizableProperty],
85}
86
87impl I18nProjection {
88 /// Read and remove the `language` argument of a `Foo/get`,
89 /// `Foo/query` or `Foo/queryChanges` for type `O`.
90 ///
91 /// `using` is the request's capability list and `info` the account's
92 /// [`JmapAccounts::i18n_info`](crate::JmapAccounts::i18n_info). A
93 /// missing or `null` `language` is the default and always accepted.
94 ///
95 /// # Errors
96 ///
97 /// `invalidArguments` when `language` is non-null and `O` has no
98 /// localizable properties, `urn:ietf:params:jmap:i18n` is not in
99 /// `using`, the account does not support it (§3: "as it would any
100 /// unknown argument"), or the value is not an array of RFC 4647
101 /// language ranges.
102 pub fn from_args<O: JmapObject>(
103 args: &mut Map<String, Value>,
104 using: &[String],
105 info: Option<&I18nInfo>,
106 ) -> Result<Self, JmapError> {
107 let language = args.remove("language");
108 let ranges = match language {
109 None | Some(Value::Null) => None,
110 Some(v) => {
111 if O::LOCALIZABLE.is_empty() {
112 return Err(JmapError::invalid_arguments(format!(
113 "language: {} has no localizable properties",
114 O::TYPE_NAME
115 )));
116 }
117 if !uses_i18n(using) {
118 return Err(JmapError::invalid_arguments(
119 "language requires urn:ietf:params:jmap:i18n in using",
120 ));
121 }
122 if info.is_none() {
123 return Err(JmapError::invalid_arguments(
124 "language: the account does not support urn:ietf:params:jmap:i18n",
125 ));
126 }
127 Some(parse_ranges(&v)?)
128 }
129 };
130 Ok(Self::with_ranges::<O>(ranges, using, info))
131 }
132
133 /// The projection for a request with no `language` argument (or a
134 /// `null` one): what [`Self::from_args`] returns for arguments
135 /// without `language`, which never fails.
136 ///
137 /// For a handler that does not take `language`, or that has already
138 /// removed it. `using` and `info` are as for [`Self::from_args`].
139 #[must_use]
140 pub fn without_language<O: JmapObject>(using: &[String], info: Option<&I18nInfo>) -> Self {
141 Self::with_ranges::<O>(None, using, info)
142 }
143
144 fn with_ranges<O: JmapObject>(
145 ranges: Option<Vec<LanguageRange>>,
146 using: &[String],
147 info: Option<&I18nInfo>,
148 ) -> Self {
149 let mode = if O::LOCALIZABLE.is_empty() {
150 Mode::Off
151 } else if !uses_i18n(using) || info.is_none() {
152 Mode::Strip
153 } else if let Some(r) = ranges {
154 Mode::View(r)
155 } else {
156 Mode::Stored
157 };
158 Self {
159 mode,
160 properties: O::LOCALIZABLE,
161 }
162 }
163
164 /// The `language` ranges, when the request set them.
165 pub fn language(&self) -> Option<&[LanguageRange]> {
166 match &self.mode {
167 Mode::View(r) => Some(r),
168 _ => None,
169 }
170 }
171
172 /// The `properties` to ask the backend for, given the client's
173 /// `requested` list: the view needs `locale` and `localizations` even
174 /// when the client did not ask for them. `None` (all properties)
175 /// stays `None`.
176 pub fn backend_properties(&self, requested: Option<&[String]>) -> Option<Vec<String>> {
177 let mut props = requested?.to_vec();
178 if matches!(self.mode, Mode::View(_)) {
179 for p in ["locale", "localizations"] {
180 if !props.iter().any(|q| q == p) {
181 props.push(p.to_owned());
182 }
183 }
184 }
185 Some(props)
186 }
187
188 /// Shape `locale` and `localizations` on one serialized object.
189 ///
190 /// Without the capability in use they are removed. With it, an absent
191 /// one is returned as `null` (its default, §4.1), and with `language`
192 /// set the object becomes its single-language view
193 /// ([`localized_view`]). `state` is not affected (§4.2.1).
194 pub fn apply(&self, item: &mut Map<String, Value>) {
195 match &self.mode {
196 Mode::Off => {}
197 Mode::Strip => {
198 item.remove("locale");
199 item.remove("localizations");
200 }
201 Mode::Stored => {
202 for p in ["locale", "localizations"] {
203 item.entry(p).or_insert(Value::Null);
204 }
205 }
206 Mode::View(ranges) => localized_view(item, self.properties, ranges),
207 }
208 }
209}
210
211fn parse_ranges(v: &Value) -> Result<Vec<LanguageRange>, JmapError> {
212 let bad = || JmapError::invalid_arguments("language must be an array of language ranges");
213 let Value::Array(items) = v else {
214 return Err(bad());
215 };
216 items
217 .iter()
218 .map(|i| {
219 i.as_str().ok_or_else(bad).and_then(|s| {
220 LanguageRange::parse(s)
221 .map_err(|e| JmapError::invalid_arguments(format!("language {s:?}: {e}")))
222 })
223 })
224 .collect()
225}
226
227// ---------------------------------------------------------------------------
228// /set
229// ---------------------------------------------------------------------------
230
231fn invalid(property: &str, description: impl Into<String>) -> Box<SetError> {
232 Box::new(
233 SetError::new(SetErrorType::InvalidProperties)
234 .with_properties([property])
235 .with_description(description),
236 )
237}
238
239/// The wire property a `/set` create key or update patch path writes, when
240/// it is `locale` or `localizations` (`"localizations/fr/name"` writes
241/// `localizations`).
242fn localized_root(key: &str) -> Option<&'static str> {
243 match key.split('/').next() {
244 Some("locale") => Some("locale"),
245 Some("localizations") => Some("localizations"),
246 _ => None,
247 }
248}
249
250/// How a `Foo/set` handler treats `locale` and `localizations`
251/// (draft-atwood-jmap-updates-00 §3, §4.1).
252///
253/// Build one per request with [`I18nSet::new`]. Call
254/// [`I18nSet::check_create`] on each create object and
255/// [`I18nSet::check_patch`] on each update patch before handing them to the
256/// backend, and [`I18nSet::echo`] on each object returned in `created` or
257/// `updated`. The checks that need the patched object (a key equal to the
258/// new `locale`, pruning) run in the backend through [`localized_update`],
259/// inside the same atomic update.
260#[derive(Debug, Clone, Default)]
261pub struct I18nSet {
262 /// `None`: the type has no localizable properties.
263 properties: Option<&'static [LocalizableProperty]>,
264 /// The request uses the capability and the account supports it.
265 allowed: bool,
266 max_localizations: Option<usize>,
267}
268
269impl I18nSet {
270 /// The handling for type `O`, given the request's `using` and the
271 /// account's [`JmapAccounts::i18n_info`](crate::JmapAccounts::i18n_info).
272 pub fn new<O: JmapObject>(using: &[String], info: Option<&I18nInfo>) -> Self {
273 Self {
274 properties: (!O::LOCALIZABLE.is_empty()).then_some(O::LOCALIZABLE),
275 allowed: uses_i18n(using) && info.is_some(),
276 max_localizations: info.and_then(|i| i.max_localizations),
277 }
278 }
279
280 fn gate(&self, key: &str) -> Result<(), Box<SetError>> {
281 match localized_root(key) {
282 Some(root) if self.properties.is_some() && !self.allowed => Err(invalid(
283 root,
284 format!(
285 "{root} requires urn:ietf:params:jmap:i18n in using and an account that \
286 supports it"
287 ),
288 )),
289 _ => Ok(()),
290 }
291 }
292
293 /// Check a create object and fold its tags to canonical case.
294 ///
295 /// Without the capability in use, naming `locale` or `localizations`
296 /// is `invalidProperties` (§3). With it, `locale` must be `null` or a
297 /// language tag, and `localizations` must follow §4.1
298 /// ([`check_localizations`]) and the account's
299 /// [`I18nInfo::max_localizations`]. Length and syntax limits of the
300 /// defining specification on localized values are the type's handler's
301 /// to apply.
302 ///
303 /// # Errors
304 ///
305 /// An `invalidProperties` [`SetError`] naming `locale` or
306 /// `localizations`.
307 pub fn check_create(&self, create: &mut Map<String, Value>) -> Result<(), Box<SetError>> {
308 let Some(properties) = self.properties else {
309 return Ok(());
310 };
311 for key in create.keys() {
312 self.gate(key)?;
313 }
314 if !self.allowed {
315 return Ok(());
316 }
317 check_and_fold(create, properties, self.max_localizations)
318 }
319
320 /// Check an update patch before the backend applies it.
321 ///
322 /// Without the capability in use, a patch path into `locale` or
323 /// `localizations` is `invalidProperties` (§3). Everything that depends
324 /// on the patched object is [`localized_update`]'s.
325 ///
326 /// # Errors
327 ///
328 /// An `invalidProperties` [`SetError`] naming `locale` or
329 /// `localizations`.
330 pub fn check_patch(&self, patch: &Map<String, Value>) -> Result<(), Box<SetError>> {
331 if self.properties.is_none() {
332 return Ok(());
333 }
334 patch.keys().try_for_each(|k| self.gate(k))
335 }
336
337 /// Shape a `created` or `updated` entry for the client: without the
338 /// capability in use, `locale` and `localizations` are removed (§3); with
339 /// it they are left as the backend returned them.
340 pub fn echo(&self, entry: &mut Value) {
341 if self.properties.is_some()
342 && !self.allowed
343 && let Value::Object(m) = entry
344 {
345 m.remove("locale");
346 m.remove("localizations");
347 }
348 }
349}
350
351/// Parse `locale` and check `localizations` in `obj`, writing both back in
352/// canonical case.
353fn check_and_fold(
354 obj: &mut Map<String, Value>,
355 properties: &[LocalizableProperty],
356 max: Option<usize>,
357) -> Result<(), Box<SetError>> {
358 let locale = match obj.get("locale") {
359 Some(v) => parse_locale(v)?,
360 None => None,
361 };
362 if let Some(tag) = &locale {
363 obj.insert("locale".to_owned(), Value::String(tag.as_str().to_owned()));
364 }
365 let Some(value) = obj.get("localizations") else {
366 return Ok(());
367 };
368 let locs = check_localizations(locale.as_ref(), value, properties)?;
369 if let (Some(locs), Some(max)) = (&locs, max)
370 && locs.len() > max
371 {
372 return Err(invalid(
373 "localizations",
374 format!("at most {max} localizations per object"),
375 ));
376 }
377 let folded = match locs {
378 Some(l) => serde_json::to_value(&l)
379 .map_err(|_| invalid("localizations", "localizations could not be serialized"))?,
380 None => Value::Null,
381 };
382 obj.insert("localizations".to_owned(), folded);
383 Ok(())
384}
385
386/// The draft-atwood-jmap-updates-00 §4.1 rules that need the patched
387/// object, for a backend's `update_object` of a type with
388/// [`JmapObject::LOCALIZABLE`] properties.
389///
390/// `old` is the stored object and `new` the result of applying `patch` to
391/// it (for example with [`apply_patch_object`](crate::apply_patch_object)),
392/// both serialized. It checks `locale` and `localizations` in `new`
393/// ([`check_localizations`], so no key may equal the new `locale`), applies
394/// `max_localizations` ([`I18nInfo::max_localizations`]), folds tags to
395/// canonical case, and then drops translations made stale by a changed
396/// base value ([`prune_stale_localizations`]). Run it inside the same
397/// atomic update, before validating and writing `new`.
398///
399/// Pruning applies to every client, including those that do not use the
400/// capability: that is the case §4.1 is for.
401///
402/// Returns `true` when pruning removed anything. The backend MUST then
403/// return the updated object (`Ok(Some(_))`) from `update_object`, so that
404/// the handler returns `localizations` in `updated` to clients that use the
405/// capability (§4.1, RFC 8620 §5.3).
406///
407/// # Errors
408///
409/// An `invalidProperties` [`SetError`] naming `locale` or
410/// `localizations`; the backend returns it as the update's [`SetError`].
411pub fn localized_update<O: JmapObject>(
412 old: &Map<String, Value>,
413 new: &mut Map<String, Value>,
414 patch: &PatchObject,
415 max_localizations: Option<usize>,
416) -> Result<bool, Box<SetError>> {
417 if O::LOCALIZABLE.is_empty() {
418 return Ok(false);
419 }
420 check_and_fold(new, O::LOCALIZABLE, max_localizations)?;
421 Ok(prune_stale_localizations(old, new, patch, O::LOCALIZABLE))
422}
423
424// ---------------------------------------------------------------------------
425// /query and /queryChanges: queryState
426// ---------------------------------------------------------------------------
427
428/// Separates the backend's queryState from the language in a wrapped state.
429/// Language ranges never contain `|`, so the last occurrence is the mark.
430const LANG_MARK: &str = "|lang=";
431
432fn join_ranges(language: &[LanguageRange]) -> String {
433 language
434 .iter()
435 .map(LanguageRange::as_str)
436 .collect::<Vec<_>>()
437 .join(",")
438}
439
440/// The `queryState` to return from a `Foo/query` whose `language` was
441/// `language` (draft-atwood-jmap-updates-00 §4.2.3: "The queryState of a
442/// /query result reflects the language it was computed with").
443///
444/// With `language` `None` the backend's `state` is returned unchanged.
445/// Otherwise it is wrapped as `<state>|lang=<r1>,<r2>`, the ranges in
446/// canonical case (decision 28). Backend query states MUST NOT contain
447/// `|lang=`. [`unwrap_query_state`] reverses it.
448///
449/// ```rust
450/// use jmap_server::{localized_query_state, unwrap_query_state};
451/// use jmap_types::State;
452/// use jmap_types::i18n::LanguageRange;
453///
454/// let de: Vec<LanguageRange> = vec!["DE-ch".parse().unwrap(), "de".parse().unwrap()];
455/// let wrapped = localized_query_state(&State::from("17"), Some(&de));
456/// assert_eq!(wrapped.as_ref(), "17|lang=de-CH,de");
457/// assert_eq!(unwrap_query_state(&wrapped, Some(&de)).unwrap().as_ref(), "17");
458/// assert!(unwrap_query_state(&wrapped, None).is_err());
459/// ```
460pub fn localized_query_state(
461 state: &jmap_types::State,
462 language: Option<&[LanguageRange]>,
463) -> jmap_types::State {
464 match language {
465 None => state.clone(),
466 Some(l) => {
467 jmap_types::State::from(format!("{}{LANG_MARK}{}", state.as_ref(), join_ranges(l)))
468 }
469 }
470}
471
472/// The backend's queryState inside a `Foo/queryChanges` `sinceQueryState`,
473/// checked against the request's `language`.
474///
475/// # Errors
476///
477/// `cannotCalculateChanges` when the language that `sinceQueryState` was
478/// computed with differs from `language` (draft-atwood-jmap-updates-00
479/// §4.2.3), including when one of them has a language and the other not.
480pub fn unwrap_query_state(
481 since: &jmap_types::State,
482 language: Option<&[LanguageRange]>,
483) -> Result<jmap_types::State, JmapError> {
484 let s = since.as_ref();
485 let (inner, was) = match s.rfind(LANG_MARK) {
486 Some(i) => (&s[..i], Some(&s[i + LANG_MARK.len()..])),
487 None => (s, None),
488 };
489 let now = language.map(join_ranges);
490 if was != now.as_deref() {
491 return Err(JmapError::cannot_calculate_changes());
492 }
493 Ok(jmap_types::State::from(inner))
494}