Skip to main content

jmap_mail_client/methods/
mailbox.rs

1//! JMAP Mail — Mailbox/* method implementations on SessionClient.
2//!
3//! Each method follows the standard five-step pattern:
4//!   1. Validate arguments (defence-in-depth empty-state guards).
5//!   2. Call `self.session_parts()?` → `(api_url, account_id)`.
6//!   3. Build args JSON with `serde_json::json!({…})`.
7//!   4. Call `build_request(method_name, args, USING_MAIL)`.
8//!   5. Call `self.call_internal(api_url, &req).await?`.
9//!   6. Call `jmap_base_client::extract_response(&resp, CALL_ID)?`.
10
11use std::collections::HashMap;
12
13use jmap_types::{Id, PatchObject, State};
14
15use super::{
16    ChangesResponse, GetResponse, MailboxSetParams, QueryChangesResponse, QueryResponse,
17    SetResponse,
18};
19
20impl super::SessionClient {
21    /// Fetch Mailbox objects by IDs (RFC 8621 §2.1 — Mailbox/get).
22    ///
23    /// If `ids` is `None`, the server returns all Mailboxes for the account,
24    /// SUBJECT TO the server's `maxObjectsInGet` cap (RFC 8620 §5.1).
25    /// For production use, scope the result set via the corresponding
26    /// /query method first and pass explicit ids here to avoid
27    /// `requestTooLarge` errors when the account holds more objects
28    /// than the cap.
29    /// Pass `properties: None` to return all fields.
30    ///
31    /// # Errors
32    ///
33    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
34    ///   if the bound session has no primary account for
35    ///   `urn:ietf:params:jmap:mail`.
36    /// - Any transport / protocol variant returned by
37    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call):
38    ///   [`Http`](jmap_base_client::ClientError::Http),
39    ///   [`Parse`](jmap_base_client::ClientError::Parse),
40    ///   [`AuthFailed`](jmap_base_client::ClientError::AuthFailed),
41    ///   [`MethodError`](jmap_base_client::ClientError::MethodError)
42    ///   (wraps RFC 8620 §3.6.2 method-level errors such as
43    ///   `accountNotFound`, `invalidArguments`, `serverFail`),
44    ///   [`MethodNotFound`](jmap_base_client::ClientError::MethodNotFound),
45    ///   [`ResponseTooLarge`](jmap_base_client::ClientError::ResponseTooLarge),
46    ///   or
47    ///   [`UnexpectedResponse`](jmap_base_client::ClientError::UnexpectedResponse).
48    pub async fn mailbox_get(
49        &self,
50        ids: Option<&[Id]>,
51        properties: Option<&[&str]>,
52    ) -> Result<GetResponse<jmap_mail_types::Mailbox>, jmap_base_client::ClientError> {
53        let (api_url, account_id) = self.session_parts()?;
54        // Omit `ids` / `properties` when None — see the matching comment on
55        // `email_get` for the rationale (consistent with set/changes/query).
56        let mut args = serde_json::json!({ "accountId": account_id });
57        if let Some(id_slice) = ids {
58            args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
59        }
60        if let Some(props) = properties {
61            args["properties"] =
62                serde_json::to_value(props).expect("&[&str] Serialize is infallible");
63        }
64        let req = super::build_request("Mailbox/get", args, super::USING_MAIL);
65        let resp = self.call_internal(api_url, &req).await?;
66        jmap_base_client::extract_response(&resp, super::CALL_ID)
67    }
68
69    /// Fetch changes to Mailbox objects since `since_state` (RFC 8621 §2.2 — Mailbox/changes).
70    ///
71    /// `max_changes` follows the same RFC 8620 §5.2 magic-value semantics
72    /// as [`Self::email_changes`]: `None` lets the server apply its
73    /// default cap, `Some(0)` means "no client limit", `Some(n>0)`
74    /// requests at most `n` entries.
75    ///
76    /// # Errors
77    ///
78    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
79    ///   if `since_state` is the empty string (defence-in-depth —
80    ///   `State` constructed via [`State::from`](jmap_types::State::from)
81    ///   accepts empty strings, but an empty `sinceState` is never
82    ///   useful and would otherwise generate a wasted round-trip).
83    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
84    ///   if the bound session has no primary account for
85    ///   `urn:ietf:params:jmap:mail`.
86    /// - Any transport / protocol variant returned by
87    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
88    ///   the matching error list on [`Self::mailbox_get`].
89    pub async fn mailbox_changes(
90        &self,
91        since_state: &State,
92        max_changes: Option<u64>,
93    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
94        // Defence-in-depth: see `thread_changes`.
95        if since_state.as_ref().is_empty() {
96            return Err(jmap_base_client::ClientError::InvalidArgument(
97                "mailbox_changes: since_state may not be empty".into(),
98            ));
99        }
100        let (api_url, account_id) = self.session_parts()?;
101        let mut args = serde_json::json!({
102            "accountId": account_id,
103            "sinceState": since_state,
104        });
105        if let Some(mc) = max_changes {
106            args["maxChanges"] = mc.into();
107        }
108        let req = super::build_request("Mailbox/changes", args, super::USING_MAIL);
109        let resp = self.call_internal(api_url, &req).await?;
110        jmap_base_client::extract_response(&resp, super::CALL_ID)
111    }
112
113    /// Create, update, or destroy Mailbox objects (RFC 8621 §2.5 — Mailbox/set).
114    ///
115    /// Pass `create`, `update`, and/or `destroy` as needed. Pass `None` to omit.
116    /// Pass `params: Some(MailboxSetParams { on_destroy_remove_emails: Some(true) })`
117    /// to allow destroying a non-empty mailbox.
118    ///
119    /// `update` is `Option<HashMap<Id, PatchObject>>` (RFC 8620 §5.3). Wire
120    /// format is unchanged from a plain JSON object because [`PatchObject`]
121    /// is `#[serde(transparent)]`; the typed parameter binds the JSON Pointer
122    /// key + null-leaf removal contract to the type system.
123    ///
124    /// # Errors
125    ///
126    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
127    ///   if the bound session has no primary account for
128    ///   `urn:ietf:params:jmap:mail`.
129    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
130    ///   if `update` is `Some` and `serde_json::to_value` fails on the
131    ///   patch map (pathological conditions only; see [`Self::email_set`]
132    ///   for the memory-cost discussion that applies identically here).
133    /// - Any transport / protocol variant returned by
134    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
135    ///   the matching error list on [`Self::mailbox_get`].
136    pub async fn mailbox_set(
137        &self,
138        create: Option<serde_json::Value>,
139        update: Option<HashMap<Id, PatchObject>>,
140        destroy: Option<Vec<Id>>,
141        params: Option<MailboxSetParams>,
142    ) -> Result<SetResponse<jmap_mail_types::Mailbox>, jmap_base_client::ClientError> {
143        if create.is_none() && update.is_none() && destroy.is_none() {
144            return Err(jmap_base_client::ClientError::InvalidArgument(
145                "mailbox_set: at least one of create, update, destroy must be Some \
146                 (an all-None /set is a no-op round-trip)"
147                    .into(),
148            ));
149        }
150        let (api_url, account_id) = self.session_parts()?;
151        let mut args = serde_json::json!({
152            "accountId": account_id,
153        });
154        let mut params_extra: Option<serde_json::Map<String, serde_json::Value>> = None;
155        if let Some(p) = params {
156            if let Some(v) = p.on_destroy_remove_emails {
157                args["onDestroyRemoveEmails"] = v.into();
158            }
159            if !p.extra.is_empty() {
160                params_extra = Some(p.extra);
161            }
162        }
163        if let Some(c) = create {
164            args["create"] = c;
165        }
166        if let Some(u) = update {
167            args["update"] = serde_json::to_value(&u).map_err(|e| {
168                jmap_base_client::ClientError::InvalidArgument(format!(
169                    "mailbox_set: serializing update map failed: {e}"
170                ))
171            })?;
172        }
173        if let Some(d) = destroy {
174            args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
175        }
176        // Route caller-supplied vendor extras onto the wire (workspace
177        // extras-preservation policy). Use `entry().or_insert()` so a
178        // caller who put a typed wire key into `params.extra` cannot
179        // silently clobber the typed value — typed wins on collision.
180        if let Some(extra) = params_extra {
181            let args_obj = args
182                .as_object_mut()
183                .expect("mailbox_set: args is constructed as Object");
184            for (k, v) in extra {
185                args_obj.entry(k).or_insert(v);
186            }
187        }
188        let req = super::build_request("Mailbox/set", args, super::USING_MAIL);
189        let resp = self.call_internal(api_url, &req).await?;
190        jmap_base_client::extract_response(&resp, super::CALL_ID)
191    }
192
193    /// Query Mailbox IDs with optional filter and sort (RFC 8621 §2.3 — Mailbox/query).
194    ///
195    /// Pass `filter: None` and `sort: None` to return all Mailboxes with
196    /// server-default ordering. Use `position` and `limit` for pagination.
197    ///
198    /// `position` and `limit` follow the same RFC 8620 §5.5 magic-value
199    /// semantics as [`Self::email_query`]: `position: Some(0)` is the
200    /// first item (zero-indexed); `limit: Some(0)` means "server's
201    /// default cap", NOT "zero results".
202    ///
203    /// # Errors
204    ///
205    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
206    ///   if the bound session has no primary account for
207    ///   `urn:ietf:params:jmap:mail`.
208    /// - Any transport / protocol variant returned by
209    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
210    ///   the matching error list on [`Self::mailbox_get`]. RFC 8620 §5.5
211    ///   defines additional /query method-level errors (`anchorNotFound`,
212    ///   `unsupportedFilter`, `unsupportedSort`, `tooManyChanges`) that
213    ///   surface as
214    ///   [`MethodError`](jmap_base_client::ClientError::MethodError).
215    pub async fn mailbox_query(
216        &self,
217        filter: Option<serde_json::Value>,
218        sort: Option<serde_json::Value>,
219        position: Option<u64>,
220        limit: Option<u64>,
221    ) -> Result<QueryResponse, jmap_base_client::ClientError> {
222        let (api_url, account_id) = self.session_parts()?;
223        let mut args = serde_json::json!({
224            "accountId": account_id,
225        });
226        if let Some(f) = filter {
227            args["filter"] = f;
228        }
229        if let Some(s) = sort {
230            args["sort"] = s;
231        }
232        if let Some(p) = position {
233            args["position"] = p.into();
234        }
235        if let Some(l) = limit {
236            args["limit"] = l.into();
237        }
238        let req = super::build_request("Mailbox/query", args, super::USING_MAIL);
239        let resp = self.call_internal(api_url, &req).await?;
240        jmap_base_client::extract_response(&resp, super::CALL_ID)
241    }
242
243    /// Fetch query-result changes for Mailbox since `since_query_state`
244    /// (RFC 8621 §2.4 — Mailbox/queryChanges).
245    ///
246    /// `filter` and `sort` MUST match the `filter` / `sort` passed to the
247    /// original `Mailbox/query` call that returned `since_query_state` —
248    /// RFC 8620 §5.6 is explicit that the server uses them to compute
249    /// which entries entered or left the result set. Omitting them when
250    /// the original query had a non-trivial filter or sort gives the
251    /// wrong added/removed deltas (or `cannotCalculateChanges`).
252    ///
253    /// `up_to_id` is the highest-index id the client has cached
254    /// (RFC 8620 §5.6); the server may use it to omit changes past that
255    /// point when both `filter` and `sort` are on immutable properties.
256    ///
257    /// `calculate_total` requests the new total result count.
258    ///
259    /// `max_changes` follows the same magic-value semantics as
260    /// [`Self::email_changes`].
261    ///
262    /// # Errors
263    ///
264    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
265    ///   if `since_query_state` is the empty string (defence-in-depth
266    ///   empty-state guard; see [`Self::mailbox_changes`]).
267    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
268    ///   if the bound session has no primary account for
269    ///   `urn:ietf:params:jmap:mail`.
270    /// - Any transport / protocol variant returned by
271    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
272    ///   the matching error list on [`Self::mailbox_get`]. RFC 8620 §5.6
273    ///   also defines `cannotCalculateChanges` (returned when the
274    ///   server cannot honour the request given the supplied filter /
275    ///   sort); it surfaces as
276    ///   [`MethodError`](jmap_base_client::ClientError::MethodError).
277    pub async fn mailbox_query_changes(
278        &self,
279        since_query_state: &State,
280        max_changes: Option<u64>,
281        filter: Option<serde_json::Value>,
282        sort: Option<serde_json::Value>,
283        up_to_id: Option<&Id>,
284        calculate_total: Option<bool>,
285    ) -> Result<QueryChangesResponse, jmap_base_client::ClientError> {
286        // Defence-in-depth: see `thread_changes`.
287        if since_query_state.as_ref().is_empty() {
288            return Err(jmap_base_client::ClientError::InvalidArgument(
289                "mailbox_query_changes: since_query_state may not be empty".into(),
290            ));
291        }
292        let (api_url, account_id) = self.session_parts()?;
293        let mut args = serde_json::json!({
294            "accountId": account_id,
295            "sinceQueryState": since_query_state,
296        });
297        if let Some(f) = filter {
298            args["filter"] = f;
299        }
300        if let Some(s) = sort {
301            args["sort"] = s;
302        }
303        if let Some(mc) = max_changes {
304            args["maxChanges"] = mc.into();
305        }
306        if let Some(uti) = up_to_id {
307            args["upToId"] = serde_json::to_value(uti).expect("Id Serialize is infallible");
308        }
309        if let Some(ct) = calculate_total {
310            args["calculateTotal"] = ct.into();
311        }
312        let req = super::build_request("Mailbox/queryChanges", args, super::USING_MAIL);
313        let resp = self.call_internal(api_url, &req).await?;
314        jmap_base_client::extract_response(&resp, super::CALL_ID)
315    }
316}
317
318// ---------------------------------------------------------------------------
319// Tests
320// ---------------------------------------------------------------------------
321
322#[cfg(test)]
323mod tests {
324    use serde_json::json;
325
326    // mailbox_get_empty_id_returns_invalid_argument was deleted in JMAP-6by7.2
327    // (typed-Id refactor): under `Option<&[Id]>` the empty-Id case becomes
328    // impossible to express through the typed API.
329
330    // The InvalidArgument guards for empty since_state and since_query_state
331    // live in mailbox_changes / mailbox_query_changes production code; testing
332    // them requires a wiremock-backed async harness. See JMAP-sc1b.64.
333
334    // Deleted in JMAP-tco1.5 as Pattern E (vacuous inline tests):
335    //   - mailbox_get_request_shape
336    //   - mailbox_set_on_destroy_remove_emails_request_shape
337    //   - mailbox_query_request_includes_filter
338    // Each hand-built `args = json!({...})` and fed it to `build_request`,
339    // never invoking the `mailbox_get` / `mailbox_set` / `mailbox_query`
340    // production builders. Real production-path coverage for these methods
341    // is tracked as a wiremock-smoke gap under JMAP-uuoi (no
342    // `tests/mailbox_*.rs` smoke file exists yet). Specific-flag passthrough
343    // coverage that may be lost (e.g. `onDestroyRemoveEmails`) is also
344    // tracked under JMAP-uuoi for follow-up wiremock smoke tests.
345    //
346    // `build_request`, `CALL_ID`, and `USING_MAIL` themselves have their
347    // own focused tests in `methods/mod.rs`.
348
349    /// Oracle: Mailbox deserialization from RFC 8621 §2 example.
350    #[test]
351    fn mailbox_get_response_deserializes() {
352        let json = json!({
353            "accountId": "acc1",
354            "state": "s10",
355            "list": [
356                {
357                    "id": "mb1",
358                    "name": "Inbox",
359                    "role": "inbox",
360                    "sortOrder": 10,
361                    "totalEmails": 42,
362                    "unreadEmails": 3,
363                    "totalThreads": 20,
364                    "unreadThreads": 2,
365                    "myRights": {
366                        "mayReadItems": true,
367                        "mayAddItems": true,
368                        "mayRemoveItems": true,
369                        "maySetSeen": true,
370                        "maySetKeywords": true,
371                        "mayCreateChild": true,
372                        "mayRename": true,
373                        "mayDelete": false,
374                        "maySubmit": false
375                    },
376                    "isSubscribed": true
377                }
378            ],
379            "notFound": []
380        });
381        use super::super::GetResponse;
382        let resp: GetResponse<jmap_mail_types::Mailbox> =
383            serde_json::from_value(json).expect("must deserialize Mailbox GetResponse");
384        assert_eq!(resp.list.len(), 1);
385        assert_eq!(resp.list[0].name, "Inbox");
386    }
387}