1use std::collections::BTreeMap;
31
32use serde::{Deserialize, Serialize};
33use serde_json::{Map, Value};
34
35use crate::{Id, JmapError, MethodErrorType, PatchObject, SetError};
36
37pub const JMAP_CONDITIONAL_URI: &str = "urn:ietf:params:jmap:conditional";
39
40pub const ATOMIC_FAILURE: &str = "atomicFailure";
43
44pub const CANNOT_APPLY_ATOMICALLY: &str = "cannotApplyAtomically";
47
48#[non_exhaustive]
52#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
53pub struct ConditionalCapability {
54 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
56 pub extra: Map<String, Value>,
57}
58
59pub type IfUnchangedBy = BTreeMap<String, Option<PatchObject>>;
65
66#[non_exhaustive]
70#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72pub struct ConditionalSetArgs {
73 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
75 pub if_unchanged_by: IfUnchangedBy,
76 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
78 pub atomic: bool,
79}
80
81impl ConditionalSetArgs {
82 pub fn is_default(&self) -> bool {
85 self.if_unchanged_by.is_empty() && !self.atomic
86 }
87}
88
89#[non_exhaustive]
97#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99pub struct AtomicFailure {
100 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub not_created: Option<BTreeMap<String, SetError>>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub not_updated: Option<BTreeMap<Id, SetError>>,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub not_destroyed: Option<BTreeMap<Id, SetError>>,
109 #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
111 pub extra: Map<String, Value>,
112}
113
114const NOT_RESTORED: &str = "notRestored";
116
117impl AtomicFailure {
118 pub fn not_restored(&self) -> Option<BTreeMap<Id, SetError>> {
121 serde_json::from_value(self.extra.get(NOT_RESTORED)?.clone()).ok()
122 }
123
124 #[must_use]
126 pub fn with_not_restored(mut self, not_restored: BTreeMap<Id, SetError>) -> Self {
127 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
135const FAILED: &str = "failed";
137
138impl JmapError {
139 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 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 pub fn cannot_apply_atomically() -> Self {
162 Self::custom(CANNOT_APPLY_ATOMICALLY)
163 }
164
165 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 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 #[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 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 assert_eq!(JmapError::atomic_failure(details.clone()), e);
262 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 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 #[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}