Skip to main content

jmap_server/
conditional.rs

1//! draft-ietf-jmap-conditional-02 support: the backend hooks
2//! ([`ConditionalBackend`], [`SetScope`]) and the opt-in registration
3//! ([`SetSupport`], [`Dispatcher::attach_set_support`]).
4//!
5//! Conditional support is opt-in per Foo/set method (docs/design/
6//! DECISIONS.md decisions 1 and 17): an extension crate's
7//! `register_<x>_conditional` attaches a [`SetSupport`] to each of its
8//! registered `/set` methods, after its unchanged `register_<x>_handlers`.
9//! A deployment that never calls it sees no API or trait-bound change.
10//! It advertises `urn:ietf:params:jmap:conditional` only when
11//! [`Dispatcher::conditional_ready`] is true, because the capability
12//! covers "every Foo/set" the server offers (§2.1).
13//!
14//! The dispatcher evaluates `ifUnchangedBy` and applies `atomic` itself,
15//! around the registered handler, inside a [`SetScope`] the backend opens
16//! (docs/design/conditional.md §5.2). The method's backend calls run
17//! while [`current_set_scope`] names that scope.
18
19use 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// ---- scope ids -------------------------------------------------------------
38
39/// Identifies one Foo/set method call's [`SetScope`].
40///
41/// Unique within the process. The dispatcher picks one per conditional
42/// method call, passes it in [`SetScopeRequest::scope`] and runs the method
43/// under it, so a backend can tell which of its calls belong to which open
44/// scope ([`current_set_scope`]).
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct SetScopeId(u64);
47
48impl SetScopeId {
49    /// A scope id not handed out before in this process.
50    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    /// The scope of the conditional Foo/set method running on this task.
64    pub(crate) static SET_SCOPE: SetScopeId;
65}
66
67/// The [`SetScope`] of the conditional Foo/set method running on this task,
68/// or `None` outside one.
69///
70/// Every backend call made while this is `Some(scope)` belongs to that
71/// scope: its reads see the scope's writes and its writes commit or roll
72/// back with it. Task-locals do not cross `tokio::spawn`, so a backend
73/// that spawns work must read the id first and carry it.
74pub fn current_set_scope() -> Option<SetScopeId> {
75    SET_SCOPE.try_with(|id| *id).ok()
76}
77
78/// Run `fut` with [`current_set_scope`] returning `scope`.
79pub(crate) async fn in_set_scope<F: Future>(scope: SetScopeId, fut: F) -> F::Output {
80    SET_SCOPE.scope(scope, fut).await
81}
82
83// ---- the backend hooks -----------------------------------------------------
84
85/// How a Foo/set method's changes must apply.
86#[non_exhaustive]
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum SetMode {
89    /// §6.1: no other writer commits to the account between the method's
90    /// precondition reads and its writes. Each change still succeeds or
91    /// fails on its own.
92    Isolated,
93    /// §4: all of the method's changes commit, or none do.
94    Atomic,
95}
96
97/// What [`ConditionalBackend::begin_set`] is asked to open.
98#[non_exhaustive]
99#[derive(Debug, Clone, Copy)]
100pub struct SetScopeRequest<'a> {
101    /// The scope's id; [`current_set_scope`] returns it while the method
102    /// runs.
103    pub scope: SetScopeId,
104    /// The method name, e.g. `"Mailbox/set"`.
105    pub method: &'a str,
106    /// The data type, e.g. `"Mailbox"`.
107    pub data_type: &'a str,
108    /// The call's `accountId`, if it had a well-formed one.
109    pub account_id: Option<&'a Id>,
110    /// Isolated or atomic.
111    pub mode: SetMode,
112    /// The call's arguments, without `ifUnchangedBy` and `atomic`.
113    pub args: &'a Value,
114}
115
116impl<'a> SetScopeRequest<'a> {
117    /// A request for `method` on `data_type`, in a fresh scope.
118    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/// Why [`ConditionalBackend::begin_set`] did not open a scope.
137#[non_exhaustive]
138#[derive(Debug)]
139pub enum BeginSetError<E> {
140    /// §4.3: the backend cannot apply this method atomically, "either at
141    /// all, or because this particular method is beyond what it can commit
142    /// as a unit". The method is rejected with `cannotApplyAtomically`.
143    CannotApplyAtomically,
144    /// A storage failure; the method fails with a redacted `serverFail`.
145    Other(E),
146}
147
148/// A change a [`SetScope`] could not commit.
149///
150/// Ids are the stored ids: a create carries the id the backend minted,
151/// which the dispatcher maps back to its creation id.
152#[non_exhaustive]
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum SetOp {
155    /// The object created with this id.
156    Create(Id),
157    /// The update of this object.
158    Update(Id),
159    /// The destroy of this object.
160    Destroy(Id),
161    /// The restore of this object (object history).
162    Restore(Id),
163}
164
165/// One change rejected at commit, with its SetError.
166#[non_exhaustive]
167#[derive(Debug, Clone, PartialEq)]
168pub struct DeferredFailure {
169    /// The change.
170    pub op: SetOp,
171    /// Why it failed, as it would appear in the Foo/set response.
172    pub error: SetError,
173}
174
175impl DeferredFailure {
176    /// `op` failed with `error`.
177    pub fn new(op: SetOp, error: SetError) -> Self {
178        Self { op, error }
179    }
180}
181
182/// Why [`SetScope::commit`] did not commit.
183#[non_exhaustive]
184#[derive(Debug)]
185pub enum CommitError {
186    /// An atomic scope's changes broke a constraint checked against the
187    /// final state (§4.2). The backend has already rolled back; the method
188    /// is rejected with `atomicFailure` naming these changes.
189    Rejected(Vec<DeferredFailure>),
190    /// A storage failure; the method fails with a redacted `serverFail`.
191    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
214/// The future [`SetScope::commit`] returns.
215pub type CommitFuture = Pin<Box<dyn Future<Output = Result<(), CommitError>> + Send>>;
216
217/// The future [`SetScope::rollback`] returns.
218pub type RollbackFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
219
220/// An open isolation (and, for [`SetMode::Atomic`], transaction) scope over
221/// one Foo/set method call, from [`ConditionalBackend::begin_set`].
222///
223/// The dispatcher ends it with exactly one of [`commit`](Self::commit) or
224/// [`rollback`](Self::rollback). **Dropping a scope without either MUST
225/// roll it back**: the dispatcher drops it when the method's task panics
226/// or is cancelled.
227pub trait SetScope: Send {
228    /// Make the scope's writes visible and release it.
229    ///
230    /// For an atomic scope, check the cross-object constraints
231    /// (uniqueness, cycles, single default, children on destroy, quotas)
232    /// against the final state; on a violation roll back and return
233    /// [`CommitError::Rejected`]. Run deferred external effects (mail send,
234    /// federation, push `StateChange`) only once committed.
235    fn commit(self: Box<Self>) -> CommitFuture;
236
237    /// Discard the scope's writes and release it. The state string and
238    /// change log are as before the scope opened (§4.2).
239    fn rollback(self: Box<Self>) -> RollbackFuture;
240}
241
242/// The conditional-02 backend hooks, required only by the opt-in
243/// `register_<x>_conditional` fns (decision 1).
244///
245/// Like [`PushSubscriptionBackend`](crate::PushSubscriptionBackend), a
246/// separate trait over [`JmapBackend`], so a backend that does not opt in
247/// is untouched.
248pub trait ConditionalBackend: JmapBackend {
249    /// Open the scope one Foo/set method call runs in (§4, §6.1).
250    ///
251    /// Lock, or start a transaction over, everything the method may read
252    /// or write in `request.account_id`, across all types: cascades (a
253    /// Mailbox destroy's `onDestroyRemoveEmails`, EmailSubmission's
254    /// implicit Email/set) run inside it. Every backend call made while
255    /// [`current_set_scope`] is `Some(request.scope)` belongs to the scope,
256    /// and `get_state` inside it sees the scope's writes.
257    ///
258    /// - [`SetMode::Isolated`]: no other writer commits to the account
259    ///   between the precondition reads and the method's writes (§6.1).
260    /// - [`SetMode::Atomic`] additionally: check cross-object constraints
261    ///   at [`SetScope::commit`] against the final state, leave the state
262    ///   string and change log unchanged on rollback (§4.2), and defer
263    ///   irreversible external effects to commit, or refuse with
264    ///   [`BeginSetError::CannotApplyAtomically`] (§4.3). Object-history
265    ///   restores in the scope are part of the unit.
266    ///
267    /// A backend MAY refuse large methods (§9.2).
268    ///
269    /// No default: a scope that does nothing lets a concurrent write land
270    /// between check and apply, so the server would report success for a
271    /// write §3.2 requires to be `stateMismatch`. A backend that already
272    /// serializes every write per account can return
273    /// [`serialized_writes_scope`].
274    ///
275    /// # Errors
276    ///
277    /// [`BeginSetError::CannotApplyAtomically`] or a storage error.
278    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    /// For each of `ids` (objects of `data_type` in `account_id`), the
285    /// top-level properties `caller` may not read, beyond what Foo/get
286    /// already leaves out or blanks for them (§9.1).
287    ///
288    /// A precondition on such a property is answered `forbidden` without
289    /// comparing its value, so the answer never depends on data the caller
290    /// cannot see.
291    ///
292    /// Default: nothing hidden (a permission hook, fail-open like the
293    /// other permission hooks, bd JMAP-bghk). Override it when the
294    /// backend's Foo/get redacts a property per caller.
295    ///
296    /// # Errors
297    ///
298    /// A storage error; the method fails with a redacted `serverFail`.
299    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
311/// A [`SetScope`] that does nothing, for a backend that already serializes
312/// every write per account.
313///
314/// **Correct only when the backend applies every write to an account one
315/// at a time, so no other writer can commit between this method's
316/// precondition reads and its writes** (§6.1, e.g. one lock held for each
317/// whole method call). It refuses [`SetMode::Atomic`] with
318/// [`BeginSetError::CannotApplyAtomically`], because it cannot undo
319/// writes. Test backends use it too.
320///
321/// # Errors
322///
323/// [`BeginSetError::CannotApplyAtomically`] for an atomic request.
324pub 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
333/// The scope [`serialized_writes_scope`] returns.
334struct 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
346// ---- registration ----------------------------------------------------------
347
348/// A boxed, sendable future borrowing for `'a`.
349type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
350
351/// [`ConditionalBackend`] made object-safe, with backend errors already
352/// mapped to redacted `serverFail`s.
353pub(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
404/// Conditional support for one Foo/set method, attached with
405/// [`Dispatcher::attach_set_support`].
406///
407/// Carries the data type (the dispatcher reads preconditions through the
408/// registered `"<type>/get"`), its property names (Foo/get alone does not
409/// reject unknown names, so the dispatcher checks pointers against them)
410/// and the backend that opens the method's [`SetScope`].
411pub struct SetSupport<C> {
412    data_type: &'static str,
413    properties: [&'static [&'static str]; 2],
414    backend: Arc<dyn DynConditional<C>>,
415    /// The evaluator, instantiated where `C` is known to be `Sync` (the
416    /// dispatcher's own `CallerCtx` bound does not say so).
417    run: RunFn<C>,
418}
419
420/// [`run`] for one caller type.
421type RunFn<C> = fn(Prepared<C>, Arc<dyn JmapHandler<C>>, CallContext<C>) -> HandlerFuture;
422
423impl<C> SetSupport<C> {
424    /// Support for `O`'s `/set`, with scopes from `backend`.
425    pub fn new<O, B>(backend: Arc<B>) -> Self
426    where
427        O: SetObject,
428        B: ConditionalBackend<CallerCtx = C>,
429        // Always true for a backend's `CallerCtx`; stated so the evaluator
430        // can be instantiated here.
431        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    /// The data type, e.g. `"Mailbox"`.
442    pub fn data_type(&self) -> &'static str {
443        self.data_type
444    }
445
446    /// Whether `name` is one of the type's properties.
447    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/// Why [`Dispatcher::attach_set_support`] refused.
476#[non_exhaustive]
477#[derive(Debug, Clone, PartialEq, Eq)]
478pub enum RegistrationError {
479    /// No handler is registered under the method name.
480    NotRegistered(String),
481    /// The method name does not end in `/set`.
482    NotASetMethod(String),
483    /// The support is for another data type than the method's.
484    DataTypeMismatch {
485        /// The method name.
486        method: String,
487        /// The support's data type.
488        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    /// Attach conditional support to the registered Foo/set `method`.
508    ///
509    /// Replaces support attached before. A later [`Dispatcher::register`]
510    /// of `method` drops it, so an overriding handler must opt in again;
511    /// until then the method shows in [`conditional_gaps`](Self::conditional_gaps).
512    ///
513    /// # Errors
514    ///
515    /// [`RegistrationError`] when `method` is not registered, does not end
516    /// in `/set`, or is not `"<support's data type>/set"`.
517    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    /// The registered Foo/set methods conditional-02 cannot serve yet: those
539    /// without attached [`SetSupport`], or whose `"<type>/get"` is not
540    /// registered (the dispatcher reads preconditions through it). Sorted.
541    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    /// Whether conditional-02 can be advertised: some support is attached
557    /// and [`conditional_gaps`](Self::conditional_gaps) is empty.
558    ///
559    /// A server MUST NOT put `urn:ietf:params:jmap:conditional` in its
560    /// Session unless this is true: the capability covers "every Foo/set"
561    /// (§2.1).
562    pub fn conditional_ready(&self) -> bool {
563        !self.set_support.is_empty() && self.conditional_gaps().is_empty()
564    }
565
566    /// The support attached to `method`, if any.
567    #[cfg(test)]
568    pub(crate) fn set_support(&self, method: &str) -> Option<&SetSupport<C>> {
569        self.set_support.get(method)
570    }
571}
572
573// ---- evaluation (docs/design/conditional.md §5.2) -------------------------
574
575/// The §3 arguments of one Foo/set call, checked.
576pub(crate) struct ConditionalArgs {
577    /// Key as sent (an id or `#creationId`) → precondition; `None` is the
578    /// JSON `null` "does not exist" precondition.
579    if_unchanged_by: BTreeMap<String, Precondition>,
580    atomic: bool,
581}
582
583/// One `ifUnchangedBy` value: a PatchObject, or `None` for JSON `null`.
584type Precondition = Option<Map<String, Value>>;
585
586/// An `ifUnchangedBy` entry: its key as sent, the id it resolves to (none
587/// for a `#creationId` with no creation), and its precondition.
588type Resolved<'a> = (&'a String, Option<Id>, &'a Precondition);
589
590/// What the evaluator needs from the dispatcher, gathered before the
591/// method's task is spawned (the dispatcher is not `'static`).
592pub(crate) struct Prepared<C> {
593    args: ConditionalArgs,
594    support: SetSupport<C>,
595    /// The registered `"<type>/get"`.
596    get: Option<Arc<dyn JmapHandler<C>>>,
597    /// The dispatcher guard's verdict on `"<type>/get"` for this caller.
598    get_guard: Result<(), JmapError>,
599}
600
601impl<C> Prepared<C> {
602    /// Run `handler` for `cx` under the conditional evaluator.
603    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
612/// Decision 2: without the URI in `using`, `atomic` must be absent, `null`
613/// or `false` and `ifUnchangedBy` absent, `null` or `{}`; those defaults are
614/// removed so the handler sees what it saw before conditional-02.
615fn 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
634/// Remove and check `ifUnchangedBy` and `atomic` (§3; `null` is the
635/// default). `None` when both are at their defaults.
636fn 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    /// Steps 1-3 of §5.2 for a Foo/set call: the decision-2 check, the
682    /// argument checks, and the lookups the evaluator needs. `Ok(None)`:
683    /// run the handler as usual (the defaults have been removed from
684    /// `args`).
685    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
724/// Steps 4-11 of §5.2: open the scope, check the preconditions, run the
725/// handler, and commit or roll back.
726async 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    // The scope is owned by this task: a panic drops it, which rolls back.
760    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        // §4.2: one failing change rejects the method; the others were not
784        // committed, so `extra_invocations` (implicit calls) go too.
785        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
797/// Steps 5-8: read the objects through `"<type>/get"` and evaluate every
798/// precondition (§3.1, §9.1).
799async 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    // §9.1: "the same permissions to read ... as ... Foo/get".
810    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    // Rule 2: a `#creationId` key stands for the id that creation
823    // produced; with no such creation the object does not exist.
824    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    // Rule 5: ifInState first. A /get without `state` (PushSubscription,
862    // Blob) leaves the argument to the handler.
863    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    // §9.1 needs the properties hidden from this caller; read them first,
885    // because rule 4 counts them as known.
886    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    // Rule 4: every pointer names a property of the type. Foo/get's own
902    // objects admit open-ended names (`header:*`, `digest:*`), and so do
903    // the names hidden from this caller: an extension property Foo/get
904    // leaves out for them (a Task `chatId` the caller may not view) is
905    // still a property, which §9.1 answers with `forbidden`.
906    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    // §9.1: readability before any value, so `forbidden` never depends on
925    // one. Invisible objects are left to step 8 (stateMismatch).
926    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    // Step 8: values.
946    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    // `failed` names resolved ids only; an unresolved creation id has
961    // none to name, so the list is left out.
962    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
968/// The decoded first token of a checked pointer.
969fn 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
974/// Whether `object`'s value at `pointer` equals `expected` (§3): every
975/// parent must exist and be an object; `null` matches an absent member.
976fn 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
1001/// The keys of a Foo/set response whose entries are failures.
1002const FAILURE_MAPS: [&str; 4] = ["notCreated", "notUpdated", "notDestroyed", "notRestored"];
1003
1004/// §4.2: an `atomicFailure` carrying the handler's non-empty failure maps,
1005/// or `None` when every change succeeded.
1006fn 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
1018/// §4.2: the changes a commit rejected, as an `atomicFailure`. A create is
1019/// named by its creation id, found in the handler's `created` map.
1020fn 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    /// Records what happens to its scopes; `fail` makes `begin_set` fail.
1107    #[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    /// A scope that logs how it ended, rolling back on drop as the
1190    /// [`SetScope`] contract requires.
1191    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    /// Answers `{"seen": <args>}`, plus an `unreadable` set.
1219    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        // Preconditions are read through Probe/get, which is missing.
1273        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        // Another /set without support is a gap again.
1279        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        // A refused try_register keeps the handler and its support.
1290        assert!(d.try_register("Probe/set", Arc::new(Echo)).is_err());
1291        assert!(d.conditional_ready());
1292        // Replacing the handler drops the support: the new handler must
1293        // opt in again.
1294        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        // A storage error becomes a redacted serverFail.
1328        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    /// The [`SetScope`] contract: a scope dropped without commit or
1341    /// rollback rolls back.
1342    #[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            // A spawned task does not inherit it.
1394            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    /// `HandlerOutput::unreadable` never reaches the wire.
1410    #[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}