Skip to main content

jmap_types/
conditional.rs

1//! draft-ietf-jmap-conditional-02 wire types: the capability, the
2//! `ifUnchangedBy` and `atomic` Foo/set arguments, and the
3//! `stateMismatch`, `atomicFailure` and `cannotApplyAtomically` method
4//! errors.
5//!
6//! The two new error codes are `&str` constants used with
7//! [`JmapError::custom`], like other extension codes: they decode to
8//! [`MethodErrorType::Other`], and no
9//! [`MethodErrorType`] variant is added
10//! (docs/design/DECISIONS.md decision 7). Their extra properties live in
11//! [`JmapError::extra`], read and written by the constructors and readers
12//! here.
13//!
14//! # Example
15//!
16//! ```rust
17//! use jmap_types::JmapError;
18//! use jmap_types::conditional::{AtomicFailure, ATOMIC_FAILURE};
19//!
20//! let err = JmapError::state_mismatch_failed(vec![jmap_types::Id::from("f42")]);
21//! assert_eq!(
22//!     serde_json::to_value(&err).unwrap(),
23//!     serde_json::json!({"type": "stateMismatch", "failed": ["f42"]})
24//! );
25//!
26//! let err = JmapError::atomic_failure(AtomicFailure::default());
27//! assert_eq!(err.error_type.as_str(), ATOMIC_FAILURE);
28//! ```
29
30use std::collections::BTreeMap;
31
32use serde::{Deserialize, Serialize};
33use serde_json::{Map, Value};
34
35use crate::{Id, JmapError, MethodErrorType, PatchObject, SetError};
36
37/// The capability URI (§2.1, §8.1).
38pub const JMAP_CONDITIONAL_URI: &str = "urn:ietf:params:jmap:conditional";
39
40/// The `atomicFailure` method error (§4.2, §8.2): an atomic Foo/set could
41/// not commit all its changes, so it made none.
42pub const ATOMIC_FAILURE: &str = "atomicFailure";
43
44/// The `cannotApplyAtomically` method error (§4.3, §8.3): the server
45/// cannot commit this Foo/set as a unit, so it made no change.
46pub const CANNOT_APPLY_ATOMICALLY: &str = "cannotApplyAtomically";
47
48/// The Session capability object (§2.1): "The value of this property MUST
49/// be an empty object." Unknown members are kept in
50/// [`extra`](Self::extra).
51#[non_exhaustive]
52#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
53pub struct ConditionalCapability {
54    /// Unknown members, kept for round-trip.
55    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
56    pub extra: Map<String, Value>,
57}
58
59/// The `ifUnchangedBy` argument (§3): `"Id[PatchObject|null]"`.
60///
61/// Keys are `String`, not [`Id`]: §3.1 allows a `#`-prefixed creation id,
62/// which `Id` does not accept. `None` is the JSON `null` precondition,
63/// "the object does not exist".
64pub type IfUnchangedBy = BTreeMap<String, Option<PatchObject>>;
65
66/// The two §3 Foo/set arguments, for a client to merge into a Foo/set
67/// call. Defaults (empty `ifUnchangedBy`, `atomic` false) are not
68/// written.
69#[non_exhaustive]
70#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72pub struct ConditionalSetArgs {
73    /// `ifUnchangedBy`: preconditions by object id.
74    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
75    pub if_unchanged_by: IfUnchangedBy,
76    /// `atomic`: commit every change or none (§4).
77    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
78    pub atomic: bool,
79}
80
81impl ConditionalSetArgs {
82    /// True when both arguments are at their defaults: there is nothing to
83    /// send, and the request needs no conditional capability.
84    pub fn is_default(&self) -> bool {
85        self.if_unchanged_by.is_empty() && !self.atomic
86    }
87}
88
89/// The details of an `atomicFailure` error (§4.2): the Foo/set-shaped
90/// `notCreated`, `notUpdated` and `notDestroyed` maps, each optional ("A
91/// server MAY report only the first failure it encounters").
92///
93/// Other members, in particular object-history `notRestored`, are kept in
94/// [`extra`](Self::extra); [`not_restored`](Self::not_restored) reads it
95/// (decision 6(b): neither draft names it yet, so it is not a field).
96#[non_exhaustive]
97#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99pub struct AtomicFailure {
100    /// `notCreated`: creation id → error.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub not_created: Option<BTreeMap<String, SetError>>,
103    /// `notUpdated`: object id → error.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub not_updated: Option<BTreeMap<Id, SetError>>,
106    /// `notDestroyed`: object id → error.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub not_destroyed: Option<BTreeMap<Id, SetError>>,
109    /// Unknown members, kept for round-trip.
110    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
111    pub extra: Map<String, Value>,
112}
113
114/// The `extra` key of object-history's stopgap `notRestored` map.
115const NOT_RESTORED: &str = "notRestored";
116
117impl AtomicFailure {
118    /// `notRestored` (object history; decision 6(b) stopgap name), or
119    /// `None` when it is absent or malformed.
120    pub fn not_restored(&self) -> Option<BTreeMap<Id, SetError>> {
121        serde_json::from_value(self.extra.get(NOT_RESTORED)?.clone()).ok()
122    }
123
124    /// Set `notRestored` (decision 6(b) stopgap name).
125    #[must_use]
126    pub fn with_not_restored(mut self, not_restored: BTreeMap<Id, SetError>) -> Self {
127        // A map of `Id` to `SetError` always serializes.
128        if let Ok(v) = serde_json::to_value(not_restored) {
129            self.extra.insert(NOT_RESTORED.to_owned(), v);
130        }
131        self
132    }
133}
134
135/// The `extra` key of the §3.3 `stateMismatch` `failed` list.
136const FAILED: &str = "failed";
137
138impl JmapError {
139    /// A `stateMismatch` error for failed `ifUnchangedBy` preconditions,
140    /// naming the objects (§3.3 `failed`: "The ids of the objects whose
141    /// preconditions were not satisfied").
142    pub fn state_mismatch_failed(failed: Vec<Id>) -> Self {
143        let mut e = Self::state_mismatch();
144        if let Ok(v) = serde_json::to_value(failed) {
145            e.extra.insert(FAILED.to_owned(), v);
146        }
147        e
148    }
149
150    /// An `atomicFailure` error (§4.2) carrying `details`' maps as
151    /// properties of the error object.
152    pub fn atomic_failure(details: AtomicFailure) -> Self {
153        let mut e = Self::custom(ATOMIC_FAILURE);
154        if let Ok(Value::Object(map)) = serde_json::to_value(details) {
155            e.extra = map;
156        }
157        e
158    }
159
160    /// A `cannotApplyAtomically` error (§4.3).
161    pub fn cannot_apply_atomically() -> Self {
162        Self::custom(CANNOT_APPLY_ATOMICALLY)
163    }
164
165    /// The §3.3 `failed` ids of a `stateMismatch` error, or `None` when
166    /// this is another error or `failed` is absent or malformed.
167    pub fn failed(&self) -> Option<Vec<Id>> {
168        if self.error_type != MethodErrorType::StateMismatch {
169            return None;
170        }
171        serde_json::from_value(self.extra.get(FAILED)?.clone()).ok()
172    }
173
174    /// The §4.2 details of an `atomicFailure` error, or `None` when this is
175    /// another error or the maps are malformed.
176    pub fn atomic_failure_details(&self) -> Option<AtomicFailure> {
177        if self.error_type.as_str() != ATOMIC_FAILURE {
178            return None;
179        }
180        serde_json::from_value(Value::Object(self.extra.clone())).ok()
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use serde_json::json;
187
188    use super::*;
189    use crate::SetErrorType;
190
191    #[test]
192    fn capability_is_an_empty_object() {
193        let cap: ConditionalCapability = serde_json::from_value(json!({})).unwrap();
194        assert_eq!(serde_json::to_value(&cap).unwrap(), json!({}));
195        let cap: ConditionalCapability = serde_json::from_value(json!({"x": 1})).unwrap();
196        assert_eq!(cap.extra["x"], 1);
197    }
198
199    #[test]
200    fn set_args() {
201        let args: ConditionalSetArgs =
202            serde_json::from_value(json!({"ifUnchangedBy": {"r": null, "f42": {}}})).unwrap();
203        assert_eq!(args.if_unchanged_by["r"], None);
204        assert!(args.if_unchanged_by["f42"].is_some());
205        assert!(!args.atomic);
206        assert!(!args.is_default());
207        assert_eq!(
208            serde_json::to_value(&args).unwrap(),
209            json!({"ifUnchangedBy": {"f42": {}, "r": null}})
210        );
211        assert!(ConditionalSetArgs::default().is_default());
212        assert_eq!(
213            serde_json::to_value(ConditionalSetArgs::default()).unwrap(),
214            json!({})
215        );
216        let atomic: ConditionalSetArgs = serde_json::from_value(json!({"atomic": true})).unwrap();
217        assert!(!atomic.is_default());
218    }
219
220    /// §5.1: the stateMismatch error JSON, verbatim.
221    #[test]
222    fn example_5_1_state_mismatch() {
223        let wire = json!({"type": "stateMismatch", "failed": ["f42"]});
224        let e: JmapError = serde_json::from_value(wire.clone()).unwrap();
225        assert_eq!(e.error_type, MethodErrorType::StateMismatch);
226        assert_eq!(e.failed(), Some(vec![Id::from("f42")]));
227        assert_eq!(serde_json::to_value(&e).unwrap(), wire);
228        assert_eq!(JmapError::state_mismatch_failed(vec![Id::from("f42")]), e);
229        // `failed` belongs to stateMismatch only.
230        let mut other = JmapError::invalid_arguments("x");
231        other.extra = e.extra.clone();
232        assert_eq!(other.failed(), None);
233        assert_eq!(JmapError::state_mismatch().failed(), None);
234    }
235
236    #[test]
237    fn atomic_failure_round_trip() {
238        let wire = json!({
239            "type": "atomicFailure",
240            "notCreated": {"c1": {"type": "invalidProperties", "properties": ["name"]}},
241            "notUpdated": {"f1": {"type": "notFound"}},
242            "notDestroyed": {"f2": {"type": "forbidden"}},
243            "notRestored": {"f3": {"type": "notFound"}}
244        });
245        let e: JmapError = serde_json::from_value(wire.clone()).unwrap();
246        assert_eq!(
247            e.error_type,
248            MethodErrorType::Other(ATOMIC_FAILURE.to_owned())
249        );
250        assert_eq!(serde_json::to_value(&e).unwrap(), wire);
251        let details = e.atomic_failure_details().unwrap();
252        assert_eq!(
253            details.not_created.as_ref().unwrap()["c1"].error_type,
254            SetErrorType::InvalidProperties
255        );
256        assert_eq!(details.not_updated.as_ref().unwrap().len(), 1);
257        assert_eq!(details.not_destroyed.as_ref().unwrap().len(), 1);
258        let restored = details.not_restored().unwrap();
259        assert_eq!(restored[&Id::from("f3")].error_type, SetErrorType::NotFound);
260        // The constructor writes the same error.
261        assert_eq!(JmapError::atomic_failure(details.clone()), e);
262        // Rebuilt from the typed parts, `with_not_restored` writes the
263        // same details.
264        let rebuilt = AtomicFailure {
265            not_created: details.not_created.clone(),
266            not_updated: details.not_updated.clone(),
267            not_destroyed: details.not_destroyed.clone(),
268            extra: Map::new(),
269        }
270        .with_not_restored(restored);
271        assert_eq!(rebuilt, details);
272    }
273
274    #[test]
275    fn atomic_failure_maps_are_optional() {
276        let e: JmapError = serde_json::from_value(json!({"type": "atomicFailure"})).unwrap();
277        assert_eq!(e.atomic_failure_details(), Some(AtomicFailure::default()));
278        assert_eq!(
279            serde_json::to_value(JmapError::atomic_failure(AtomicFailure::default())).unwrap(),
280            json!({"type": "atomicFailure"})
281        );
282        assert_eq!(
283            JmapError::cannot_apply_atomically().atomic_failure_details(),
284            None
285        );
286        // A malformed map gives None, not a panic.
287        let bad: JmapError =
288            serde_json::from_value(json!({"type": "atomicFailure", "notUpdated": 3})).unwrap();
289        assert_eq!(bad.atomic_failure_details(), None);
290    }
291
292    /// Decision 7: both codes are extension codes, `Other`, and the
293    /// constructors match `custom`.
294    #[test]
295    fn codes_decode_to_other() {
296        for code in [ATOMIC_FAILURE, CANNOT_APPLY_ATOMICALLY] {
297            let e: JmapError = serde_json::from_value(json!({"type": code})).unwrap();
298            assert_eq!(e.error_type, MethodErrorType::Other(code.to_owned()));
299        }
300        assert_eq!(
301            JmapError::custom(ATOMIC_FAILURE),
302            JmapError::atomic_failure(AtomicFailure::default())
303        );
304        assert_eq!(
305            JmapError::custom(CANNOT_APPLY_ATOMICALLY),
306            JmapError::cannot_apply_atomically()
307        );
308    }
309}