use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::{Id, JmapError, MethodErrorType, PatchObject, SetError};
pub const JMAP_CONDITIONAL_URI: &str = "urn:ietf:params:jmap:conditional";
pub const ATOMIC_FAILURE: &str = "atomicFailure";
pub const CANNOT_APPLY_ATOMICALLY: &str = "cannotApplyAtomically";
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConditionalCapability {
#[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
pub extra: Map<String, Value>,
}
pub type IfUnchangedBy = BTreeMap<String, Option<PatchObject>>;
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConditionalSetArgs {
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub if_unchanged_by: IfUnchangedBy,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub atomic: bool,
}
impl ConditionalSetArgs {
pub fn is_default(&self) -> bool {
self.if_unchanged_by.is_empty() && !self.atomic
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AtomicFailure {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_created: Option<BTreeMap<String, SetError>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_updated: Option<BTreeMap<Id, SetError>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_destroyed: Option<BTreeMap<Id, SetError>>,
#[serde(flatten, default, skip_serializing_if = "Map::is_empty")]
pub extra: Map<String, Value>,
}
const NOT_RESTORED: &str = "notRestored";
impl AtomicFailure {
pub fn not_restored(&self) -> Option<BTreeMap<Id, SetError>> {
serde_json::from_value(self.extra.get(NOT_RESTORED)?.clone()).ok()
}
#[must_use]
pub fn with_not_restored(mut self, not_restored: BTreeMap<Id, SetError>) -> Self {
if let Ok(v) = serde_json::to_value(not_restored) {
self.extra.insert(NOT_RESTORED.to_owned(), v);
}
self
}
}
const FAILED: &str = "failed";
impl JmapError {
pub fn state_mismatch_failed(failed: Vec<Id>) -> Self {
let mut e = Self::state_mismatch();
if let Ok(v) = serde_json::to_value(failed) {
e.extra.insert(FAILED.to_owned(), v);
}
e
}
pub fn atomic_failure(details: AtomicFailure) -> Self {
let mut e = Self::custom(ATOMIC_FAILURE);
if let Ok(Value::Object(map)) = serde_json::to_value(details) {
e.extra = map;
}
e
}
pub fn cannot_apply_atomically() -> Self {
Self::custom(CANNOT_APPLY_ATOMICALLY)
}
pub fn failed(&self) -> Option<Vec<Id>> {
if self.error_type != MethodErrorType::StateMismatch {
return None;
}
serde_json::from_value(self.extra.get(FAILED)?.clone()).ok()
}
pub fn atomic_failure_details(&self) -> Option<AtomicFailure> {
if self.error_type.as_str() != ATOMIC_FAILURE {
return None;
}
serde_json::from_value(Value::Object(self.extra.clone())).ok()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::SetErrorType;
#[test]
fn capability_is_an_empty_object() {
let cap: ConditionalCapability = serde_json::from_value(json!({})).unwrap();
assert_eq!(serde_json::to_value(&cap).unwrap(), json!({}));
let cap: ConditionalCapability = serde_json::from_value(json!({"x": 1})).unwrap();
assert_eq!(cap.extra["x"], 1);
}
#[test]
fn set_args() {
let args: ConditionalSetArgs =
serde_json::from_value(json!({"ifUnchangedBy": {"r": null, "f42": {}}})).unwrap();
assert_eq!(args.if_unchanged_by["r"], None);
assert!(args.if_unchanged_by["f42"].is_some());
assert!(!args.atomic);
assert!(!args.is_default());
assert_eq!(
serde_json::to_value(&args).unwrap(),
json!({"ifUnchangedBy": {"f42": {}, "r": null}})
);
assert!(ConditionalSetArgs::default().is_default());
assert_eq!(
serde_json::to_value(ConditionalSetArgs::default()).unwrap(),
json!({})
);
let atomic: ConditionalSetArgs = serde_json::from_value(json!({"atomic": true})).unwrap();
assert!(!atomic.is_default());
}
#[test]
fn example_5_1_state_mismatch() {
let wire = json!({"type": "stateMismatch", "failed": ["f42"]});
let e: JmapError = serde_json::from_value(wire.clone()).unwrap();
assert_eq!(e.error_type, MethodErrorType::StateMismatch);
assert_eq!(e.failed(), Some(vec![Id::from("f42")]));
assert_eq!(serde_json::to_value(&e).unwrap(), wire);
assert_eq!(JmapError::state_mismatch_failed(vec![Id::from("f42")]), e);
let mut other = JmapError::invalid_arguments("x");
other.extra = e.extra.clone();
assert_eq!(other.failed(), None);
assert_eq!(JmapError::state_mismatch().failed(), None);
}
#[test]
fn atomic_failure_round_trip() {
let wire = json!({
"type": "atomicFailure",
"notCreated": {"c1": {"type": "invalidProperties", "properties": ["name"]}},
"notUpdated": {"f1": {"type": "notFound"}},
"notDestroyed": {"f2": {"type": "forbidden"}},
"notRestored": {"f3": {"type": "notFound"}}
});
let e: JmapError = serde_json::from_value(wire.clone()).unwrap();
assert_eq!(
e.error_type,
MethodErrorType::Other(ATOMIC_FAILURE.to_owned())
);
assert_eq!(serde_json::to_value(&e).unwrap(), wire);
let details = e.atomic_failure_details().unwrap();
assert_eq!(
details.not_created.as_ref().unwrap()["c1"].error_type,
SetErrorType::InvalidProperties
);
assert_eq!(details.not_updated.as_ref().unwrap().len(), 1);
assert_eq!(details.not_destroyed.as_ref().unwrap().len(), 1);
let restored = details.not_restored().unwrap();
assert_eq!(restored[&Id::from("f3")].error_type, SetErrorType::NotFound);
assert_eq!(JmapError::atomic_failure(details.clone()), e);
let rebuilt = AtomicFailure {
not_created: details.not_created.clone(),
not_updated: details.not_updated.clone(),
not_destroyed: details.not_destroyed.clone(),
extra: Map::new(),
}
.with_not_restored(restored);
assert_eq!(rebuilt, details);
}
#[test]
fn atomic_failure_maps_are_optional() {
let e: JmapError = serde_json::from_value(json!({"type": "atomicFailure"})).unwrap();
assert_eq!(e.atomic_failure_details(), Some(AtomicFailure::default()));
assert_eq!(
serde_json::to_value(JmapError::atomic_failure(AtomicFailure::default())).unwrap(),
json!({"type": "atomicFailure"})
);
assert_eq!(
JmapError::cannot_apply_atomically().atomic_failure_details(),
None
);
let bad: JmapError =
serde_json::from_value(json!({"type": "atomicFailure", "notUpdated": 3})).unwrap();
assert_eq!(bad.atomic_failure_details(), None);
}
#[test]
fn codes_decode_to_other() {
for code in [ATOMIC_FAILURE, CANNOT_APPLY_ATOMICALLY] {
let e: JmapError = serde_json::from_value(json!({"type": code})).unwrap();
assert_eq!(e.error_type, MethodErrorType::Other(code.to_owned()));
}
assert_eq!(
JmapError::custom(ATOMIC_FAILURE),
JmapError::atomic_failure(AtomicFailure::default())
);
assert_eq!(
JmapError::custom(CANNOT_APPLY_ATOMICALLY),
JmapError::cannot_apply_atomically()
);
}
}