1use std::collections::{BTreeMap, BTreeSet};
20use std::fmt;
21use std::future::Future;
22use std::pin::Pin;
23use std::sync::Arc;
24use std::sync::atomic::{AtomicU64, Ordering};
25
26use jmap_types::conditional::{AtomicFailure, JMAP_CONDITIONAL_URI};
27use jmap_types::{Id, JmapError, SetError, SetObject};
28use serde_json::{Map, Value, json};
29
30use crate::backend::JmapBackend;
31use crate::helpers::decode_pointer_token;
32use crate::{
33 CallContext, Dispatcher, HandlerFuture, HandlerOutput, JmapHandler, check_patch_paths,
34 server_fail_from_backend,
35};
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct SetScopeId(u64);
47
48impl SetScopeId {
49 pub fn next() -> Self {
51 static NEXT: AtomicU64 = AtomicU64::new(1);
52 Self(NEXT.fetch_add(1, Ordering::Relaxed))
53 }
54}
55
56impl fmt::Display for SetScopeId {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 write!(f, "set-scope-{}", self.0)
59 }
60}
61
62tokio::task_local! {
63 pub(crate) static SET_SCOPE: SetScopeId;
65}
66
67pub fn current_set_scope() -> Option<SetScopeId> {
75 SET_SCOPE.try_with(|id| *id).ok()
76}
77
78pub(crate) async fn in_set_scope<F: Future>(scope: SetScopeId, fut: F) -> F::Output {
80 SET_SCOPE.scope(scope, fut).await
81}
82
83#[non_exhaustive]
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum SetMode {
89 Isolated,
93 Atomic,
95}
96
97#[non_exhaustive]
99#[derive(Debug, Clone, Copy)]
100pub struct SetScopeRequest<'a> {
101 pub scope: SetScopeId,
104 pub method: &'a str,
106 pub data_type: &'a str,
108 pub account_id: Option<&'a Id>,
110 pub mode: SetMode,
112 pub args: &'a Value,
114}
115
116impl<'a> SetScopeRequest<'a> {
117 pub fn new(
119 method: &'a str,
120 data_type: &'a str,
121 account_id: Option<&'a Id>,
122 mode: SetMode,
123 args: &'a Value,
124 ) -> Self {
125 Self {
126 scope: SetScopeId::next(),
127 method,
128 data_type,
129 account_id,
130 mode,
131 args,
132 }
133 }
134}
135
136#[non_exhaustive]
138#[derive(Debug)]
139pub enum BeginSetError<E> {
140 CannotApplyAtomically,
144 Other(E),
146}
147
148#[non_exhaustive]
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum SetOp {
155 Create(Id),
157 Update(Id),
159 Destroy(Id),
161 Restore(Id),
163}
164
165#[non_exhaustive]
167#[derive(Debug, Clone, PartialEq)]
168pub struct DeferredFailure {
169 pub op: SetOp,
171 pub error: SetError,
173}
174
175impl DeferredFailure {
176 pub fn new(op: SetOp, error: SetError) -> Self {
178 Self { op, error }
179 }
180}
181
182#[non_exhaustive]
184#[derive(Debug)]
185pub enum CommitError {
186 Rejected(Vec<DeferredFailure>),
190 Other(Box<dyn std::error::Error + Send + Sync>),
192}
193
194impl fmt::Display for CommitError {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 match self {
197 Self::Rejected(failures) => {
198 write!(f, "commit rejected {} change(s)", failures.len())
199 }
200 Self::Other(e) => write!(f, "commit failed: {e}"),
201 }
202 }
203}
204
205impl std::error::Error for CommitError {
206 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
207 match self {
208 Self::Rejected(_) => None,
209 Self::Other(e) => Some(&**e),
210 }
211 }
212}
213
214pub type CommitFuture = Pin<Box<dyn Future<Output = Result<(), CommitError>> + Send>>;
216
217pub type RollbackFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
219
220pub trait SetScope: Send {
228 fn commit(self: Box<Self>) -> CommitFuture;
236
237 fn rollback(self: Box<Self>) -> RollbackFuture;
240}
241
242pub trait ConditionalBackend: JmapBackend {
249 fn begin_set(
279 &self,
280 caller: &Self::CallerCtx,
281 request: SetScopeRequest<'_>,
282 ) -> impl Future<Output = Result<Box<dyn SetScope>, BeginSetError<Self::Error>>> + Send;
283
284 fn hidden_properties(
300 &self,
301 caller: &Self::CallerCtx,
302 account_id: Option<&Id>,
303 data_type: &str,
304 ids: &[Id],
305 ) -> impl Future<Output = Result<BTreeMap<Id, Vec<String>>, Self::Error>> + Send {
306 let _ = (caller, account_id, data_type, ids);
307 async { Ok(BTreeMap::new()) }
308 }
309}
310
311pub fn serialized_writes_scope<E>(
325 request: SetScopeRequest<'_>,
326) -> Result<Box<dyn SetScope>, BeginSetError<E>> {
327 match request.mode {
328 SetMode::Isolated => Ok(Box::new(NoopScope)),
329 _ => Err(BeginSetError::CannotApplyAtomically),
330 }
331}
332
333struct NoopScope;
335
336impl SetScope for NoopScope {
337 fn commit(self: Box<Self>) -> CommitFuture {
338 Box::pin(async { Ok(()) })
339 }
340
341 fn rollback(self: Box<Self>) -> RollbackFuture {
342 Box::pin(async {})
343 }
344}
345
346type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
350
351pub(crate) trait DynConditional<C>: Send + Sync {
354 fn begin_set<'a>(
355 &'a self,
356 caller: &'a C,
357 request: SetScopeRequest<'a>,
358 ) -> BoxFuture<'a, Result<Box<dyn SetScope>, BeginSetError<JmapError>>>;
359
360 fn hidden_properties<'a>(
361 &'a self,
362 caller: &'a C,
363 account_id: Option<&'a Id>,
364 data_type: &'a str,
365 ids: &'a [Id],
366 ) -> BoxFuture<'a, Result<BTreeMap<Id, Vec<String>>, JmapError>>;
367}
368
369struct Adapter<B>(Arc<B>);
370
371impl<B: ConditionalBackend> DynConditional<B::CallerCtx> for Adapter<B> {
372 fn begin_set<'a>(
373 &'a self,
374 caller: &'a B::CallerCtx,
375 request: SetScopeRequest<'a>,
376 ) -> BoxFuture<'a, Result<Box<dyn SetScope>, BeginSetError<JmapError>>> {
377 Box::pin(async move {
378 self.0
379 .begin_set(caller, request)
380 .await
381 .map_err(|e| match e {
382 BeginSetError::Other(e) => BeginSetError::Other(server_fail_from_backend(&e)),
383 _ => BeginSetError::CannotApplyAtomically,
384 })
385 })
386 }
387
388 fn hidden_properties<'a>(
389 &'a self,
390 caller: &'a B::CallerCtx,
391 account_id: Option<&'a Id>,
392 data_type: &'a str,
393 ids: &'a [Id],
394 ) -> BoxFuture<'a, Result<BTreeMap<Id, Vec<String>>, JmapError>> {
395 Box::pin(async move {
396 self.0
397 .hidden_properties(caller, account_id, data_type, ids)
398 .await
399 .map_err(|e| server_fail_from_backend(&e))
400 })
401 }
402}
403
404pub struct SetSupport<C> {
412 data_type: &'static str,
413 properties: [&'static [&'static str]; 2],
414 backend: Arc<dyn DynConditional<C>>,
415 run: RunFn<C>,
418}
419
420type RunFn<C> = fn(Prepared<C>, Arc<dyn JmapHandler<C>>, CallContext<C>) -> HandlerFuture;
422
423impl<C> SetSupport<C> {
424 pub fn new<O, B>(backend: Arc<B>) -> Self
426 where
427 O: SetObject,
428 B: ConditionalBackend<CallerCtx = C>,
429 C: Clone + Send + Sync + 'static,
432 {
433 Self {
434 data_type: O::TYPE_NAME,
435 properties: [O::SERVER_SET, O::CLIENT_SETTABLE],
436 backend: Arc::new(Adapter(backend)),
437 run: |prepared, handler, cx| Box::pin(run(prepared, handler, cx)),
438 }
439 }
440
441 pub fn data_type(&self) -> &'static str {
443 self.data_type
444 }
445
446 pub(crate) fn is_property(&self, name: &str) -> bool {
448 self.properties.iter().any(|list| list.contains(&name))
449 }
450
451 pub(crate) fn backend(&self) -> &Arc<dyn DynConditional<C>> {
452 &self.backend
453 }
454}
455
456impl<C> Clone for SetSupport<C> {
457 fn clone(&self) -> Self {
458 Self {
459 data_type: self.data_type,
460 properties: self.properties,
461 backend: Arc::clone(&self.backend),
462 run: self.run,
463 }
464 }
465}
466
467impl<C> fmt::Debug for SetSupport<C> {
468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469 f.debug_struct("SetSupport")
470 .field("data_type", &self.data_type)
471 .finish_non_exhaustive()
472 }
473}
474
475#[non_exhaustive]
477#[derive(Debug, Clone, PartialEq, Eq)]
478pub enum RegistrationError {
479 NotRegistered(String),
481 NotASetMethod(String),
483 DataTypeMismatch {
485 method: String,
487 data_type: &'static str,
489 },
490}
491
492impl fmt::Display for RegistrationError {
493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494 match self {
495 Self::NotRegistered(m) => write!(f, "no handler is registered for {m:?}"),
496 Self::NotASetMethod(m) => write!(f, "{m:?} is not a Foo/set method"),
497 Self::DataTypeMismatch { method, data_type } => {
498 write!(f, "support for {data_type} attached to {method:?}")
499 }
500 }
501 }
502}
503
504impl std::error::Error for RegistrationError {}
505
506impl<C: Clone + Send + 'static> Dispatcher<C> {
507 pub fn attach_set_support(
518 &mut self,
519 method: &str,
520 support: SetSupport<C>,
521 ) -> Result<(), RegistrationError> {
522 let Some(data_type) = method.strip_suffix("/set") else {
523 return Err(RegistrationError::NotASetMethod(method.to_owned()));
524 };
525 if !self.handlers.contains_key(method) {
526 return Err(RegistrationError::NotRegistered(method.to_owned()));
527 }
528 if data_type != support.data_type {
529 return Err(RegistrationError::DataTypeMismatch {
530 method: method.to_owned(),
531 data_type: support.data_type,
532 });
533 }
534 self.set_support.insert(method.to_owned(), support);
535 Ok(())
536 }
537
538 pub fn conditional_gaps(&self) -> Vec<String> {
542 let mut gaps: Vec<String> = self
543 .handlers
544 .keys()
545 .filter_map(|method| {
546 let data_type = method.strip_suffix("/set")?;
547 let served = self.set_support.contains_key(method)
548 && self.handlers.contains_key(&format!("{data_type}/get"));
549 (!served).then(|| method.clone())
550 })
551 .collect();
552 gaps.sort();
553 gaps
554 }
555
556 pub fn conditional_ready(&self) -> bool {
563 !self.set_support.is_empty() && self.conditional_gaps().is_empty()
564 }
565
566 #[cfg(test)]
568 pub(crate) fn set_support(&self, method: &str) -> Option<&SetSupport<C>> {
569 self.set_support.get(method)
570 }
571}
572
573pub(crate) struct ConditionalArgs {
577 if_unchanged_by: BTreeMap<String, Precondition>,
580 atomic: bool,
581}
582
583type Precondition = Option<Map<String, Value>>;
585
586type Resolved<'a> = (&'a String, Option<Id>, &'a Precondition);
589
590pub(crate) struct Prepared<C> {
593 args: ConditionalArgs,
594 support: SetSupport<C>,
595 get: Option<Arc<dyn JmapHandler<C>>>,
597 get_guard: Result<(), JmapError>,
599}
600
601impl<C> Prepared<C> {
602 pub(crate) fn run(self, handler: Arc<dyn JmapHandler<C>>, cx: CallContext<C>) -> HandlerFuture {
604 (self.support.run)(self, handler, cx)
605 }
606}
607
608fn invalid(description: impl Into<String>) -> JmapError {
609 JmapError::invalid_arguments(description)
610}
611
612fn strip_without_uri(args: &mut Map<String, Value>) -> Result<(), JmapError> {
616 let atomic_ok = matches!(
617 args.remove("atomic"),
618 None | Some(Value::Null | Value::Bool(false))
619 );
620 let preconditions_ok = match args.remove("ifUnchangedBy") {
621 None | Some(Value::Null) => true,
622 Some(Value::Object(m)) => m.is_empty(),
623 Some(_) => false,
624 };
625 if atomic_ok && preconditions_ok {
626 Ok(())
627 } else {
628 Err(invalid(format!(
629 "ifUnchangedBy/atomic require {JMAP_CONDITIONAL_URI} in using"
630 )))
631 }
632}
633
634fn take_args(args: &mut Map<String, Value>) -> Result<Option<ConditionalArgs>, JmapError> {
637 let atomic = match args.remove("atomic") {
638 None | Some(Value::Null) => false,
639 Some(Value::Bool(b)) => b,
640 Some(_) => return Err(invalid("atomic must be a boolean")),
641 };
642 let mut if_unchanged_by = BTreeMap::new();
643 match args.remove("ifUnchangedBy") {
644 None | Some(Value::Null) => {}
645 Some(Value::Object(entries)) => {
646 for (key, value) in entries {
647 let id = key.strip_prefix('#').unwrap_or(&key);
648 if let Err(e) = Id::new_validated(id) {
649 return Err(invalid(format!(
650 "ifUnchangedBy key {key:?} is not an id: {e}"
651 )));
652 }
653 let precondition = match value {
654 Value::Null => None,
655 Value::Object(patch) => {
656 check_patch_paths(&patch)
657 .map_err(|e| invalid(format!("ifUnchangedBy/{key}: {e}")))?;
658 Some(patch)
659 }
660 _ => {
661 return Err(invalid(format!(
662 "ifUnchangedBy/{key} must be a PatchObject or null"
663 )));
664 }
665 };
666 if_unchanged_by.insert(key, precondition);
667 }
668 }
669 Some(_) => return Err(invalid("ifUnchangedBy must be an object or null")),
670 }
671 if if_unchanged_by.is_empty() && !atomic {
672 return Ok(None);
673 }
674 Ok(Some(ConditionalArgs {
675 if_unchanged_by,
676 atomic,
677 }))
678}
679
680impl<C: Clone + Send + 'static> Dispatcher<C> {
681 pub(crate) fn prepare_conditional(
686 &self,
687 method: &str,
688 args: &mut Value,
689 using: &[String],
690 caller: &C,
691 ) -> Result<Option<Prepared<C>>, JmapError> {
692 let Value::Object(map) = args else {
693 return Ok(None);
694 };
695 if !using.iter().any(|u| u == JMAP_CONDITIONAL_URI) {
696 strip_without_uri(map)?;
697 return Ok(None);
698 }
699 let Some(conditional) = take_args(map)? else {
700 return Ok(None);
701 };
702 let unsupported = || invalid(format!("conditional {method} is not supported"));
703 let Some(support) = self.set_support.get(method).cloned() else {
704 return Err(unsupported());
705 };
706 let get_method = format!("{}/get", support.data_type());
707 let get = self.handlers.get(&get_method).map(Arc::clone);
708 if get.is_none() && !conditional.if_unchanged_by.is_empty() {
709 return Err(unsupported());
710 }
711 let get_guard = self
712 .guard
713 .as_ref()
714 .map_or(Ok(()), |guard| guard(&get_method, caller));
715 Ok(Some(Prepared {
716 args: conditional,
717 support,
718 get,
719 get_guard,
720 }))
721 }
722}
723
724async fn run<C: Clone + Send + Sync + 'static>(
727 prepared: Prepared<C>,
728 handler: Arc<dyn JmapHandler<C>>,
729 cx: CallContext<C>,
730) -> Result<HandlerOutput, JmapError> {
731 let mode = if prepared.args.atomic {
732 SetMode::Atomic
733 } else {
734 SetMode::Isolated
735 };
736 let account_id = cx
737 .args
738 .get("accountId")
739 .and_then(Value::as_str)
740 .and_then(|s| Id::new_validated(s).ok());
741 let scope_id = SetScopeId::next();
742 let request = SetScopeRequest {
743 scope: scope_id,
744 method: &cx.method,
745 data_type: prepared.support.data_type(),
746 account_id: account_id.as_ref(),
747 mode,
748 args: &cx.args,
749 };
750 let scope = prepared
751 .support
752 .backend()
753 .begin_set(&cx.caller, request)
754 .await
755 .map_err(|e| match e {
756 BeginSetError::Other(e) => e,
757 _ => JmapError::cannot_apply_atomically(),
758 })?;
759 in_set_scope(scope_id, scoped(scope, prepared, account_id, handler, cx)).await
761}
762
763async fn scoped<C: Clone + Send + Sync + 'static>(
764 scope: Box<dyn SetScope>,
765 prepared: Prepared<C>,
766 account_id: Option<Id>,
767 handler: Arc<dyn JmapHandler<C>>,
768 cx: CallContext<C>,
769) -> Result<HandlerOutput, JmapError> {
770 if let Err(e) = check_preconditions(&prepared, account_id.as_ref(), &cx).await {
771 scope.rollback().await;
772 return Err(e);
773 }
774 let atomic = prepared.args.atomic;
775 let out = match handler.call(cx.with_atomic(atomic)).await {
776 Ok(out) => out,
777 Err(e) => {
778 scope.rollback().await;
779 return Err(e);
780 }
781 };
782 if atomic && let Some(err) = set_errors_in(&out.primary) {
783 scope.rollback().await;
786 return Err(err);
787 }
788 match scope.commit().await {
789 Ok(()) => Ok(out),
790 Err(CommitError::Rejected(failures)) if atomic => {
791 Err(rejected_at_commit(failures, &out.primary))
792 }
793 Err(e) => Err(server_fail_from_backend(&e)),
794 }
795}
796
797async fn check_preconditions<C: Clone + Send + Sync + 'static>(
800 prepared: &Prepared<C>,
801 account_id: Option<&Id>,
802 cx: &CallContext<C>,
803) -> Result<(), JmapError> {
804 let entries = &prepared.args.if_unchanged_by;
805 if entries.is_empty() {
806 return Ok(());
807 }
808 let data_type = prepared.support.data_type();
809 if prepared.get_guard.is_err() {
811 let mut e = JmapError::forbidden();
812 e.description = Some(format!("reading {data_type} objects is not permitted"));
813 return Err(e);
814 }
815 let Some(get) = &prepared.get else {
816 return Err(invalid(format!(
817 "conditional {} is not supported",
818 cx.method
819 )));
820 };
821
822 let resolved: Vec<Resolved<'_>> = entries
825 .iter()
826 .map(|(key, pre)| {
827 let id = match key.strip_prefix('#') {
828 Some(cid) => cx.created_ids.get(&Id::from(cid)).cloned(),
829 None => Some(Id::from(key.as_str())),
830 };
831 (key, id, pre)
832 })
833 .collect();
834 let ids: BTreeSet<&Id> = resolved
835 .iter()
836 .filter_map(|(_, id, _)| id.as_ref())
837 .collect();
838 let mut names = BTreeSet::from(["id".to_owned()]);
839 for (_, _, pre) in &resolved {
840 for pointer in pre.iter().flat_map(Map::keys) {
841 names.insert(top_level(pointer));
842 }
843 }
844 let mut get_args = json!({ "ids": ids, "properties": names });
845 if let Some(account) = cx.args.get("accountId") {
846 get_args["accountId"] = account.clone();
847 }
848 let got = get
849 .call(
850 CallContext::new(
851 format!("{data_type}/get"),
852 cx.call_id.clone(),
853 get_args,
854 cx.caller.clone(),
855 )
856 .with_created_ids(cx.created_ids.clone())
857 .with_using(cx.using.clone()),
858 )
859 .await?;
860
861 if let (Some(want), Some(have)) = (
864 cx.args.get("ifInState").and_then(Value::as_str),
865 got.primary.get("state").and_then(Value::as_str),
866 ) && want != have
867 {
868 return Err(JmapError::state_mismatch());
869 }
870
871 let list: BTreeMap<&str, &Map<String, Value>> = got
872 .primary
873 .get("list")
874 .and_then(Value::as_array)
875 .into_iter()
876 .flatten()
877 .filter_map(|o| {
878 let o = o.as_object()?;
879 Some((o.get("id")?.as_str()?, o))
880 })
881 .collect();
882 let object = |id: &Option<Id>| id.as_ref().and_then(|id| list.get(id.as_ref()).copied());
883
884 let visible: Vec<Id> = resolved
887 .iter()
888 .filter(|(_, id, pre)| pre.is_some() && object(id).is_some())
889 .filter_map(|(_, id, _)| id.clone())
890 .collect();
891 let hidden = if visible.is_empty() {
892 BTreeMap::new()
893 } else {
894 prepared
895 .support
896 .backend()
897 .hidden_properties(&cx.caller, account_id, data_type, &visible)
898 .await?
899 };
900
901 let marked = |name: &str| {
907 got.unreadable.values().any(|s| s.contains(name))
908 || hidden.values().any(|v| v.iter().any(|h| h == name))
909 };
910 for (key, _, pre) in &resolved {
911 for pointer in pre.iter().flat_map(Map::keys) {
912 let name = top_level(pointer);
913 let known = prepared.support.is_property(&name)
914 || list.values().any(|o| o.contains_key(&name))
915 || marked(&name);
916 if !known {
917 return Err(invalid(format!(
918 "ifUnchangedBy/{key}: {name} is not a {data_type} property"
919 )));
920 }
921 }
922 }
923
924 for (key, id, pre) in &resolved {
927 let (Some(id), Some(patch)) = (id, pre) else {
928 continue;
929 };
930 if object(&Some(id.clone())).is_none() {
931 continue;
932 }
933 for pointer in patch.keys() {
934 let name = top_level(pointer);
935 let unreadable = got.unreadable.get(id).is_some_and(|s| s.contains(&name))
936 || hidden.get(id).is_some_and(|v| v.contains(&name));
937 if unreadable {
938 let mut e = JmapError::forbidden();
939 e.description = Some(format!("ifUnchangedBy/{key}: {name} is not readable"));
940 return Err(e);
941 }
942 }
943 }
944
945 let mut failed: Vec<Option<Id>> = Vec::new();
947 for (_, id, pre) in &resolved {
948 let holds = match (pre, object(id)) {
949 (None, found) => found.is_none(),
950 (Some(_), None) => false,
951 (Some(patch), Some(o)) => patch.iter().all(|(p, v)| pointer_holds(o, p, v)),
952 };
953 if !holds {
954 failed.push(id.clone());
955 }
956 }
957 if failed.is_empty() {
958 return Ok(());
959 }
960 match failed.into_iter().collect::<Option<Vec<Id>>>() {
963 Some(ids) => Err(JmapError::state_mismatch_failed(ids)),
964 None => Err(JmapError::state_mismatch()),
965 }
966}
967
968fn top_level(pointer: &str) -> String {
970 let first = pointer.split('/').next().unwrap_or_default();
971 decode_pointer_token(first).map_or_else(|_| first.to_owned(), |t| t.into_owned())
972}
973
974fn pointer_holds(object: &Map<String, Value>, pointer: &str, expected: &Value) -> bool {
977 let Ok(tokens) = pointer
978 .split('/')
979 .map(decode_pointer_token)
980 .collect::<Result<Vec<_>, _>>()
981 else {
982 return false;
983 };
984 let Some((leaf, parents)) = tokens.split_last() else {
985 return false;
986 };
987 let mut current = object;
988 for token in parents {
989 match current.get(token.as_ref()) {
990 Some(Value::Object(m)) => current = m,
991 _ => return false,
992 }
993 }
994 match (expected, current.get(leaf.as_ref())) {
995 (Value::Null, None | Some(Value::Null)) => true,
996 (expected, Some(actual)) => expected == actual,
997 (_, None) => false,
998 }
999}
1000
1001const FAILURE_MAPS: [&str; 4] = ["notCreated", "notUpdated", "notDestroyed", "notRestored"];
1003
1004fn set_errors_in(primary: &Value) -> Option<JmapError> {
1007 let mut err = JmapError::atomic_failure(AtomicFailure::default());
1008 for key in FAILURE_MAPS {
1009 if let Some(map) = primary.get(key).and_then(Value::as_object)
1010 && !map.is_empty()
1011 {
1012 err.extra.insert(key.to_owned(), Value::Object(map.clone()));
1013 }
1014 }
1015 (!err.extra.is_empty()).then_some(err)
1016}
1017
1018fn rejected_at_commit(failures: Vec<DeferredFailure>, primary: &Value) -> JmapError {
1021 let created = primary.get("created").and_then(Value::as_object);
1022 let creation_id = |id: &Id| {
1023 created
1024 .and_then(|m| {
1025 m.iter()
1026 .find(|(_, o)| o.get("id").and_then(Value::as_str) == Some(id.as_ref()))
1027 })
1028 .map_or_else(|| id.to_string(), |(cid, _)| cid.clone())
1029 };
1030 let mut details = AtomicFailure::default();
1031 let mut not_restored = BTreeMap::new();
1032 for DeferredFailure { op, error } in failures {
1033 match op {
1034 SetOp::Create(id) => {
1035 details
1036 .not_created
1037 .get_or_insert_with(BTreeMap::new)
1038 .insert(creation_id(&id), error);
1039 }
1040 SetOp::Update(id) => {
1041 details
1042 .not_updated
1043 .get_or_insert_with(BTreeMap::new)
1044 .insert(id, error);
1045 }
1046 SetOp::Destroy(id) => {
1047 details
1048 .not_destroyed
1049 .get_or_insert_with(BTreeMap::new)
1050 .insert(id, error);
1051 }
1052 SetOp::Restore(id) => {
1053 not_restored.insert(id, error);
1054 }
1055 }
1056 }
1057 if !not_restored.is_empty() {
1058 details = details.with_not_restored(not_restored);
1059 }
1060 JmapError::atomic_failure(details)
1061}
1062
1063#[cfg(test)]
1064mod tests {
1065 use std::collections::BTreeSet;
1066 use std::sync::Mutex;
1067
1068 use jmap_types::{JmapObject, MethodErrorType, State};
1069 use serde::{Deserialize, Serialize};
1070 use serde_json::json;
1071
1072 use super::*;
1073 use crate::backend::{
1074 BackendChangesError, BackendQueryError, ChangesParams, ChangesResult, GetObject,
1075 QueryChangesParams, QueryChangesResult, QueryObject, QueryParams, QueryResult,
1076 };
1077 use crate::{CallContext, HandlerFuture, HandlerOutput, JmapHandler};
1078 use crate::{JmapAccounts, JmapReads};
1079
1080 #[derive(Debug, Serialize, Deserialize)]
1081 struct Probe;
1082
1083 impl JmapObject for Probe {
1084 const TYPE_NAME: &'static str = "Probe";
1085 type Property = ();
1086 }
1087
1088 impl SetObject for Probe {
1089 type Patch = Value;
1090 const SERVER_SET: &'static [&'static str] = &["id"];
1091 const CLIENT_SETTABLE: &'static [&'static str] = &["name"];
1092 const IMMUTABLE: &'static [&'static str] = &[];
1093 }
1094
1095 #[derive(Debug)]
1096 struct StubError;
1097
1098 impl fmt::Display for StubError {
1099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100 f.write_str("secret storage detail")
1101 }
1102 }
1103
1104 impl std::error::Error for StubError {}
1105
1106 #[derive(Default)]
1108 struct Backend {
1109 log: Arc<Mutex<Vec<String>>>,
1110 fail: bool,
1111 }
1112
1113 impl JmapAccounts for Backend {
1114 type Error = StubError;
1115 type CallerCtx = ();
1116
1117 async fn account_exists(&self, _: &(), _: &Id) -> Result<bool, StubError> {
1118 unreachable!("not used")
1119 }
1120 }
1121
1122 impl JmapReads for Backend {
1123 async fn get_objects<O: GetObject + Send + Sync>(
1124 &self,
1125 _: &(),
1126 _: &Id,
1127 _: Option<&[Id]>,
1128 _: Option<&[String]>,
1129 ) -> Result<(Vec<O>, Vec<Id>), StubError> {
1130 unreachable!("not used")
1131 }
1132
1133 async fn get_state<O: JmapObject + Send + Sync>(
1134 &self,
1135 _: &(),
1136 _: &Id,
1137 ) -> Result<State, StubError> {
1138 unreachable!("not used")
1139 }
1140
1141 async fn get_changes<O: JmapObject + Send + Sync>(
1142 &self,
1143 _: &(),
1144 _: &Id,
1145 _: ChangesParams<'_>,
1146 ) -> Result<ChangesResult, BackendChangesError<StubError>> {
1147 unreachable!("not used")
1148 }
1149
1150 async fn query_objects<O: QueryObject + Send + Sync>(
1151 &self,
1152 _: &(),
1153 _: &Id,
1154 _: QueryParams<'_, O>,
1155 ) -> Result<QueryResult, BackendQueryError<StubError>> {
1156 unreachable!("not used")
1157 }
1158
1159 async fn query_changes<O: QueryObject + Send + Sync>(
1160 &self,
1161 _: &(),
1162 _: &Id,
1163 _: QueryChangesParams<'_, O>,
1164 ) -> Result<QueryChangesResult, BackendChangesError<StubError>> {
1165 unreachable!("not used")
1166 }
1167 }
1168
1169 impl ConditionalBackend for Backend {
1170 async fn begin_set(
1171 &self,
1172 _: &(),
1173 request: SetScopeRequest<'_>,
1174 ) -> Result<Box<dyn SetScope>, BeginSetError<StubError>> {
1175 if self.fail {
1176 return Err(BeginSetError::Other(StubError));
1177 }
1178 self.log
1179 .lock()
1180 .unwrap()
1181 .push(format!("begin {:?} {}", request.mode, request.method));
1182 Ok(Box::new(RecordingScope {
1183 log: Arc::clone(&self.log),
1184 ended: false,
1185 }))
1186 }
1187 }
1188
1189 struct RecordingScope {
1192 log: Arc<Mutex<Vec<String>>>,
1193 ended: bool,
1194 }
1195
1196 impl SetScope for RecordingScope {
1197 fn commit(mut self: Box<Self>) -> CommitFuture {
1198 self.ended = true;
1199 self.log.lock().unwrap().push("commit".to_owned());
1200 Box::pin(async { Ok(()) })
1201 }
1202
1203 fn rollback(mut self: Box<Self>) -> RollbackFuture {
1204 self.ended = true;
1205 self.log.lock().unwrap().push("rollback".to_owned());
1206 Box::pin(async {})
1207 }
1208 }
1209
1210 impl Drop for RecordingScope {
1211 fn drop(&mut self) {
1212 if !self.ended {
1213 self.log.lock().unwrap().push("rollback on drop".to_owned());
1214 }
1215 }
1216 }
1217
1218 struct Echo;
1220
1221 impl JmapHandler<()> for Echo {
1222 fn call(&self, cx: CallContext<()>) -> HandlerFuture {
1223 Box::pin(async move {
1224 let hidden =
1225 BTreeMap::from([(Id::from("p1"), BTreeSet::from(["name".to_owned()]))]);
1226 Ok(HandlerOutput::new(json!({"seen": cx.args})).with_unreadable(hidden))
1227 })
1228 }
1229 }
1230
1231 fn support(backend: Backend) -> SetSupport<()> {
1232 SetSupport::new::<Probe, _>(Arc::new(backend))
1233 }
1234
1235 fn dispatcher(methods: &[&str]) -> Dispatcher<()> {
1236 let mut d = Dispatcher::new();
1237 for m in methods {
1238 d.register(*m, Arc::new(Echo));
1239 }
1240 d
1241 }
1242
1243 #[test]
1244 fn attach_needs_a_registered_set_of_the_same_type() {
1245 let mut d = dispatcher(&["Probe/get", "Other/set"]);
1246 assert_eq!(
1247 d.attach_set_support("Probe/get", support(Backend::default())),
1248 Err(RegistrationError::NotASetMethod("Probe/get".to_owned()))
1249 );
1250 assert_eq!(
1251 d.attach_set_support("Probe/set", support(Backend::default())),
1252 Err(RegistrationError::NotRegistered("Probe/set".to_owned()))
1253 );
1254 assert_eq!(
1255 d.attach_set_support("Other/set", support(Backend::default())),
1256 Err(RegistrationError::DataTypeMismatch {
1257 method: "Other/set".to_owned(),
1258 data_type: "Probe"
1259 })
1260 );
1261 assert!(d.set_support("Other/set").is_none());
1262 }
1263
1264 #[test]
1265 fn gaps_and_readiness() {
1266 let mut d = dispatcher(&[]);
1267 assert!(!d.conditional_ready(), "nothing attached");
1268 d.register("Probe/set", Arc::new(Echo));
1269 assert_eq!(d.conditional_gaps(), ["Probe/set"]);
1270 d.attach_set_support("Probe/set", support(Backend::default()))
1271 .unwrap();
1272 assert_eq!(d.conditional_gaps(), ["Probe/set"]);
1274 assert!(!d.conditional_ready());
1275 d.register("Probe/get", Arc::new(Echo));
1276 assert!(d.conditional_gaps().is_empty());
1277 assert!(d.conditional_ready());
1278 d.register("Other/set", Arc::new(Echo));
1280 assert_eq!(d.conditional_gaps(), ["Other/set"]);
1281 assert!(!d.conditional_ready());
1282 }
1283
1284 #[test]
1285 fn register_drops_support() {
1286 let mut d = dispatcher(&["Probe/get", "Probe/set"]);
1287 d.attach_set_support("Probe/set", support(Backend::default()))
1288 .unwrap();
1289 assert!(d.try_register("Probe/set", Arc::new(Echo)).is_err());
1291 assert!(d.conditional_ready());
1292 d.register("Probe/set", Arc::new(Echo));
1295 assert!(d.set_support("Probe/set").is_none());
1296 assert_eq!(d.conditional_gaps(), ["Probe/set"]);
1297 assert!(!d.conditional_ready());
1298 }
1299
1300 #[test]
1301 fn support_knows_its_type_and_properties() {
1302 let s = support(Backend::default());
1303 assert_eq!(s.data_type(), "Probe");
1304 assert!(s.is_property("id"));
1305 assert!(s.is_property("name"));
1306 assert!(!s.is_property("bogus"));
1307 assert!(format!("{s:?}").contains("Probe"));
1308 }
1309
1310 #[tokio::test]
1311 async fn adapter_opens_scopes_and_maps_errors() {
1312 let backend = Backend::default();
1313 let log = Arc::clone(&backend.log);
1314 let s = support(backend);
1315 let args = json!({});
1316 let request = SetScopeRequest::new("Probe/set", "Probe", None, SetMode::Atomic, &args);
1317 let scope = s.backend().begin_set(&(), request).await.unwrap();
1318 scope.commit().await.unwrap();
1319 assert_eq!(*log.lock().unwrap(), ["begin Atomic Probe/set", "commit"]);
1320 let hidden = s
1321 .backend()
1322 .hidden_properties(&(), None, "Probe", &[Id::from("p1")])
1323 .await
1324 .unwrap();
1325 assert!(hidden.is_empty(), "default: nothing hidden");
1326
1327 let failing = support(Backend {
1329 fail: true,
1330 ..Backend::default()
1331 });
1332 let request = SetScopeRequest::new("Probe/set", "Probe", None, SetMode::Isolated, &args);
1333 let Err(BeginSetError::Other(e)) = failing.backend().begin_set(&(), request).await else {
1334 panic!("expected a storage error");
1335 };
1336 assert_eq!(e.error_type, MethodErrorType::ServerFail);
1337 assert!(!format!("{e:?}").contains("secret"));
1338 }
1339
1340 #[tokio::test]
1343 async fn dropped_scope_rolls_back() {
1344 let backend = Backend::default();
1345 let log = Arc::clone(&backend.log);
1346 let args = json!({});
1347 let request = SetScopeRequest::new("Probe/set", "Probe", None, SetMode::Atomic, &args);
1348 let scope = backend.begin_set(&(), request).await.unwrap();
1349 drop(scope);
1350 let request = SetScopeRequest::new("Probe/set", "Probe", None, SetMode::Atomic, &args);
1351 backend
1352 .begin_set(&(), request)
1353 .await
1354 .unwrap()
1355 .rollback()
1356 .await;
1357 assert_eq!(
1358 *log.lock().unwrap(),
1359 [
1360 "begin Atomic Probe/set",
1361 "rollback on drop",
1362 "begin Atomic Probe/set",
1363 "rollback"
1364 ]
1365 );
1366 }
1367
1368 #[tokio::test]
1369 async fn serialized_writes_scope_refuses_atomic() {
1370 let args = json!({});
1371 let isolated = SetScopeRequest::new("Probe/set", "Probe", None, SetMode::Isolated, &args);
1372 let scope = serialized_writes_scope::<StubError>(isolated).unwrap();
1373 scope.commit().await.unwrap();
1374 let isolated = SetScopeRequest::new("Probe/set", "Probe", None, SetMode::Isolated, &args);
1375 serialized_writes_scope::<StubError>(isolated)
1376 .unwrap()
1377 .rollback()
1378 .await;
1379 let atomic = SetScopeRequest::new("Probe/set", "Probe", None, SetMode::Atomic, &args);
1380 assert!(matches!(
1381 serialized_writes_scope::<StubError>(atomic),
1382 Err(BeginSetError::CannotApplyAtomically)
1383 ));
1384 }
1385
1386 #[tokio::test]
1387 async fn current_scope_is_task_local() {
1388 assert_eq!(current_set_scope(), None);
1389 let (a, b) = (SetScopeId::next(), SetScopeId::next());
1390 assert_ne!(a, b);
1391 let seen = in_set_scope(a, async {
1392 let inner = current_set_scope();
1393 let spawned = tokio::spawn(async { current_set_scope() }).await.unwrap();
1395 (inner, spawned)
1396 })
1397 .await;
1398 assert_eq!(seen, (Some(a), None));
1399 assert_eq!(current_set_scope(), None);
1400 }
1401
1402 #[test]
1403 fn call_context_atomic_defaults_false() {
1404 let cx = CallContext::new("Probe/set", "c", json!({}), ());
1405 assert!(!cx.atomic);
1406 assert!(cx.with_atomic(true).atomic);
1407 }
1408
1409 #[tokio::test]
1411 async fn unreadable_is_not_serialized() {
1412 let d = dispatcher(&["Probe/get"]);
1413 let req: jmap_types::JmapRequest = serde_json::from_value(json!({
1414 "using": ["urn:ietf:params:jmap:core"],
1415 "methodCalls": [["Probe/get", {"ids": ["p1"]}, "c"]]
1416 }))
1417 .unwrap();
1418 let resp = serde_json::to_value(d.dispatch(req, (), State::from("s")).await).unwrap();
1419 assert_eq!(
1420 resp["methodResponses"][0][1],
1421 json!({"seen": {"ids": ["p1"]}})
1422 );
1423 let out = HandlerOutput::new(json!({}));
1424 assert!(out.unreadable.is_empty());
1425 }
1426}