Skip to main content

jmap_mail_client/methods/
submission.rs

1//! JMAP Mail — EmailSubmission/* method implementations on SessionClient.
2//!
3//! Implements RFC 8621 §7.1-7.5.
4//!
5//! Each method follows the standard six-step pattern:
6//!   1. Validate arguments (defence-in-depth empty-state guards).
7//!   2. Call `self.session_parts()?` → `(api_url, account_id)`.
8//!   3. Build args JSON with `serde_json::json!({…})`.
9//!   4. Call `build_request(method_name, args, USING_SUBMISSION)`.
10//!   5. Call `self.call_internal(api_url, &req).await?`.
11//!   6. Call `jmap_base_client::extract_response(&resp, CALL_ID)?`.
12//!
13//! Wire key notes (RFC 8621 §7):
14//!   - Object field for submission creation time:     "sendAt"       (§7.1)
15//!   - Sort property for /query:                      "sentAt"       (§7.3, line 4513)
16//!   - Success hooks on /set:                         "onSuccessUpdateEmail",
17//!     "onSuccessDestroyEmail" (§7.5)
18
19use std::collections::HashMap;
20
21use jmap_types::{Id, PatchObject, State};
22
23use super::{
24    ChangesResponse, EmailSubmissionSetParams, GetResponse, QueryChangesResponse, QueryResponse,
25    SetResponse,
26};
27
28impl super::SessionClient {
29    /// Fetch EmailSubmission objects by IDs (RFC 8621 §7.1 — EmailSubmission/get).
30    ///
31    /// If `ids` is `None`, the server returns all submissions for the account,
32    /// SUBJECT TO the server's `maxObjectsInGet` cap (RFC 8620 §5.1).
33    /// For production use, scope the result set via the corresponding
34    /// /query method first and pass explicit ids here to avoid
35    /// `requestTooLarge` errors when the account holds more objects
36    /// than the cap.
37    /// Pass `properties: None` to return all fields.
38    ///
39    /// # Errors
40    ///
41    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
42    ///   if the bound session has no primary account for
43    ///   `urn:ietf:params:jmap:mail`. (EmailSubmission/* uses
44    ///   `urn:ietf:params:jmap:submission` in its `using` array but is
45    ///   keyed on the mail primary account.)
46    /// - Any transport / protocol variant returned by
47    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call):
48    ///   [`Http`](jmap_base_client::ClientError::Http),
49    ///   [`Parse`](jmap_base_client::ClientError::Parse),
50    ///   [`AuthFailed`](jmap_base_client::ClientError::AuthFailed),
51    ///   [`MethodError`](jmap_base_client::ClientError::MethodError)
52    ///   (wraps RFC 8620 §3.6.2 method-level errors such as
53    ///   `accountNotFound`, `invalidArguments`, `serverFail`),
54    ///   [`MethodNotFound`](jmap_base_client::ClientError::MethodNotFound),
55    ///   [`ResponseTooLarge`](jmap_base_client::ClientError::ResponseTooLarge),
56    ///   or
57    ///   [`UnexpectedResponse`](jmap_base_client::ClientError::UnexpectedResponse).
58    pub async fn email_submission_get(
59        &self,
60        ids: Option<&[Id]>,
61        properties: Option<&[&str]>,
62    ) -> Result<GetResponse<jmap_mail_types::EmailSubmission>, jmap_base_client::ClientError> {
63        let (api_url, account_id) = self.session_parts()?;
64        // Omit `ids` / `properties` when None — see the matching comment on
65        // `email_get` for the rationale (consistent with set/changes/query).
66        let mut args = serde_json::json!({ "accountId": account_id });
67        if let Some(id_slice) = ids {
68            args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
69        }
70        if let Some(props) = properties {
71            args["properties"] =
72                serde_json::to_value(props).expect("&[&str] Serialize is infallible");
73        }
74        let req = super::build_request("EmailSubmission/get", args, super::USING_SUBMISSION);
75        let resp = self.call_internal(api_url, &req).await?;
76        jmap_base_client::extract_response(&resp, super::CALL_ID)
77    }
78
79    /// Fetch changes to EmailSubmission objects since `since_state`
80    /// (RFC 8621 §7.2 — EmailSubmission/changes).
81    ///
82    /// `max_changes` follows the same RFC 8620 §5.2 magic-value semantics
83    /// as [`SessionClient::email_changes`](crate::methods::SessionClient::email_changes):
84    /// `None` lets the server apply its default cap, `Some(0)` means
85    /// "no client limit", `Some(n>0)` requests at most `n` entries.
86    ///
87    /// # Errors
88    ///
89    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
90    ///   if `since_state` is the empty string (defence-in-depth —
91    ///   `State` constructed via [`State::from`](jmap_types::State::from)
92    ///   accepts empty strings, but an empty `sinceState` is never
93    ///   useful and would otherwise generate a wasted round-trip).
94    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
95    ///   if the bound session has no primary account for
96    ///   `urn:ietf:params:jmap:mail`.
97    /// - Any transport / protocol variant returned by
98    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
99    ///   the matching error list on [`Self::email_submission_get`].
100    pub async fn email_submission_changes(
101        &self,
102        since_state: &State,
103        max_changes: Option<u64>,
104    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
105        // Defence-in-depth: see `thread_changes`.
106        if since_state.as_ref().is_empty() {
107            return Err(jmap_base_client::ClientError::InvalidArgument(
108                "email_submission_changes: since_state may not be empty".into(),
109            ));
110        }
111        let (api_url, account_id) = self.session_parts()?;
112        let mut args = serde_json::json!({
113            "accountId": account_id,
114            "sinceState": since_state,
115        });
116        if let Some(mc) = max_changes {
117            args["maxChanges"] = mc.into();
118        }
119        let req = super::build_request("EmailSubmission/changes", args, super::USING_SUBMISSION);
120        let resp = self.call_internal(api_url, &req).await?;
121        jmap_base_client::extract_response(&resp, super::CALL_ID)
122    }
123
124    /// Query EmailSubmission IDs with optional filter and sort
125    /// (RFC 8621 §7.3 — EmailSubmission/query).
126    ///
127    /// The sort property for this object type is `"sentAt"` (RFC 8621 §7.3, line 4513),
128    /// not `"sendAt"` (which is an object field).  Callers constructing the sort
129    /// argument should use `"sentAt"` as the property name.
130    ///
131    /// `position` and `limit` follow the same RFC 8620 §5.5 magic-value
132    /// semantics as
133    /// [`SessionClient::email_query`](crate::methods::SessionClient::email_query):
134    /// `position: Some(0)` is the first item (zero-indexed); `limit:
135    /// Some(0)` means "server's default cap", NOT "zero results".
136    ///
137    /// # Errors
138    ///
139    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
140    ///   if the bound session has no primary account for
141    ///   `urn:ietf:params:jmap:mail`.
142    /// - Any transport / protocol variant returned by
143    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
144    ///   the matching error list on [`Self::email_submission_get`].
145    ///   RFC 8620 §5.5 defines additional /query method-level errors
146    ///   (`anchorNotFound`, `unsupportedFilter`, `unsupportedSort`,
147    ///   `tooManyChanges`) that surface as
148    ///   [`MethodError`](jmap_base_client::ClientError::MethodError).
149    pub async fn email_submission_query(
150        &self,
151        filter: Option<serde_json::Value>,
152        sort: Option<serde_json::Value>,
153        position: Option<u64>,
154        limit: Option<u64>,
155    ) -> Result<QueryResponse, jmap_base_client::ClientError> {
156        let (api_url, account_id) = self.session_parts()?;
157        let mut args = serde_json::json!({
158            "accountId": account_id,
159        });
160        if let Some(f) = filter {
161            args["filter"] = f;
162        }
163        if let Some(s) = sort {
164            args["sort"] = s;
165        }
166        if let Some(p) = position {
167            args["position"] = p.into();
168        }
169        if let Some(l) = limit {
170            args["limit"] = l.into();
171        }
172        let req = super::build_request("EmailSubmission/query", args, super::USING_SUBMISSION);
173        let resp = self.call_internal(api_url, &req).await?;
174        jmap_base_client::extract_response(&resp, super::CALL_ID)
175    }
176
177    /// Fetch query-result changes for EmailSubmission since `since_query_state`
178    /// (RFC 8621 §7.4 — EmailSubmission/queryChanges).
179    ///
180    /// `filter` and `sort` MUST match the `filter` / `sort` passed to the
181    /// original `EmailSubmission/query` call that returned
182    /// `since_query_state` — RFC 8620 §5.6 is explicit that the server
183    /// uses them to compute which entries entered or left the result set.
184    /// Omitting them when the original query had a non-trivial filter or
185    /// sort gives the wrong added/removed deltas (or
186    /// `cannotCalculateChanges`).
187    ///
188    /// `up_to_id` is the highest-index id the client has cached
189    /// (RFC 8620 §5.6); the server may use it to omit changes past that
190    /// point when both `filter` and `sort` are on immutable properties.
191    ///
192    /// `calculate_total` requests the new total result count.
193    ///
194    /// `max_changes` follows the same magic-value semantics as
195    /// [`SessionClient::email_changes`](crate::methods::SessionClient::email_changes).
196    ///
197    /// # Errors
198    ///
199    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
200    ///   if `since_query_state` is the empty string (defence-in-depth
201    ///   empty-state guard; see [`Self::email_submission_changes`]).
202    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
203    ///   if the bound session has no primary account for
204    ///   `urn:ietf:params:jmap:mail`.
205    /// - Any transport / protocol variant returned by
206    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
207    ///   the matching error list on [`Self::email_submission_get`].
208    ///   RFC 8620 §5.6 also defines `cannotCalculateChanges` (returned
209    ///   when the server cannot honour the request given the supplied
210    ///   filter / sort); it surfaces as
211    ///   [`MethodError`](jmap_base_client::ClientError::MethodError).
212    pub async fn email_submission_query_changes(
213        &self,
214        since_query_state: &State,
215        max_changes: Option<u64>,
216        filter: Option<serde_json::Value>,
217        sort: Option<serde_json::Value>,
218        up_to_id: Option<&Id>,
219        calculate_total: Option<bool>,
220    ) -> Result<QueryChangesResponse, jmap_base_client::ClientError> {
221        // Defence-in-depth: see `thread_changes`.
222        if since_query_state.as_ref().is_empty() {
223            return Err(jmap_base_client::ClientError::InvalidArgument(
224                "email_submission_query_changes: since_query_state may not be empty".into(),
225            ));
226        }
227        let (api_url, account_id) = self.session_parts()?;
228        let mut args = serde_json::json!({
229            "accountId": account_id,
230            "sinceQueryState": since_query_state,
231        });
232        if let Some(f) = filter {
233            args["filter"] = f;
234        }
235        if let Some(s) = sort {
236            args["sort"] = s;
237        }
238        if let Some(mc) = max_changes {
239            args["maxChanges"] = mc.into();
240        }
241        if let Some(uti) = up_to_id {
242            args["upToId"] = serde_json::to_value(uti).expect("Id Serialize is infallible");
243        }
244        if let Some(ct) = calculate_total {
245            args["calculateTotal"] = ct.into();
246        }
247        let req = super::build_request(
248            "EmailSubmission/queryChanges",
249            args,
250            super::USING_SUBMISSION,
251        );
252        let resp = self.call_internal(api_url, &req).await?;
253        jmap_base_client::extract_response(&resp, super::CALL_ID)
254    }
255
256    /// Create, update, or destroy EmailSubmission objects
257    /// (RFC 8621 §7.5 — EmailSubmission/set).
258    ///
259    /// The optional `params` argument carries the two success-hook fields:
260    ///
261    /// - `on_success_update_email` — a `PatchObject` map (keyed by submission
262    ///   creation key) of patches to apply to the associated Email when the
263    ///   submission is created successfully (RFC 8621 §7.5).
264    /// - `on_success_destroy_email` — IDs (or `#`-reference creation keys) of
265    ///   Email objects to destroy when the submission is created successfully
266    ///   (RFC 8621 §7.5).
267    ///
268    /// # Errors
269    ///
270    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
271    ///   if the bound session has no primary account for
272    ///   `urn:ietf:params:jmap:mail`.
273    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
274    ///   if `serde_json::to_value` fails on `update` or on
275    ///   `params.on_success_update_email` (pathological conditions only;
276    ///   see [`Self::email_set`] for the memory-cost discussion that
277    ///   applies identically here).
278    /// - Any transport / protocol variant returned by
279    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
280    ///   the matching error list on [`Self::email_submission_get`].
281    pub async fn email_submission_set(
282        &self,
283        create: Option<serde_json::Value>,
284        update: Option<HashMap<Id, PatchObject>>,
285        destroy: Option<Vec<Id>>,
286        if_in_state: Option<&State>,
287        params: Option<EmailSubmissionSetParams>,
288    ) -> Result<SetResponse<jmap_mail_types::EmailSubmission>, jmap_base_client::ClientError> {
289        if create.is_none() && update.is_none() && destroy.is_none() {
290            return Err(jmap_base_client::ClientError::InvalidArgument(
291                "email_submission_set: at least one of create, update, destroy must be Some \
292                 (an all-None /set is a no-op round-trip; if_in_state and params alone are \
293                 not sufficient)"
294                    .into(),
295            ));
296        }
297        let (api_url, account_id) = self.session_parts()?;
298        let mut args = serde_json::json!({
299            "accountId": account_id,
300        });
301        let mut params_extra: Option<serde_json::Map<String, serde_json::Value>> = None;
302        // Merge success-hook params into the top-level args object (RFC 8621 §7.5).
303        // These are method-level arguments, not nested under a key.
304        if let Some(p) = params {
305            if let Some(v) = p.on_success_update_email {
306                args["onSuccessUpdateEmail"] = serde_json::to_value(&v).map_err(|e| {
307                    jmap_base_client::ClientError::InvalidArgument(format!(
308                        "email_submission_set: serializing onSuccessUpdateEmail failed: {e}"
309                    ))
310                })?;
311            }
312            if let Some(v) = p.on_success_destroy_email {
313                args["onSuccessDestroyEmail"] = serde_json::Value::Array(
314                    v.into_iter().map(serde_json::Value::String).collect(),
315                );
316            }
317            if !p.extra.is_empty() {
318                params_extra = Some(p.extra);
319            }
320        }
321        if let Some(s) = if_in_state {
322            args["ifInState"] = serde_json::Value::String(s.as_ref().to_owned());
323        }
324        if let Some(c) = create {
325            args["create"] = c;
326        }
327        if let Some(u) = update {
328            args["update"] = serde_json::to_value(&u).map_err(|e| {
329                jmap_base_client::ClientError::InvalidArgument(format!(
330                    "email_submission_set: serializing update map failed: {e}"
331                ))
332            })?;
333        }
334        if let Some(d) = destroy {
335            args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
336        }
337        // Route caller-supplied vendor extras onto the wire (workspace
338        // extras-preservation policy). Use `entry().or_insert()` so a
339        // caller who put a typed wire key into `params.extra` cannot
340        // silently clobber the typed value — typed wins on collision.
341        if let Some(extra) = params_extra {
342            let args_obj = args
343                .as_object_mut()
344                .expect("email_submission_set: args is constructed as Object");
345            for (k, v) in extra {
346                args_obj.entry(k).or_insert(v);
347            }
348        }
349        let req = super::build_request("EmailSubmission/set", args, super::USING_SUBMISSION);
350        let resp = self.call_internal(api_url, &req).await?;
351        jmap_base_client::extract_response(&resp, super::CALL_ID)
352    }
353}
354
355// ---------------------------------------------------------------------------
356// Tests
357// ---------------------------------------------------------------------------
358
359#[cfg(test)]
360mod tests {
361    use serde_json::json;
362
363    // submission_get_empty_id_guard and submission_set_empty_destroy_id_guard
364    // were deleted in JMAP-6by7.2 (typed-Id refactor): under `Option<&[Id]>`
365    // and `Option<Vec<Id>>` the empty-Id case becomes impossible to express
366    // through the typed API.
367
368    // The InvalidArgument guards for empty since_state and since_query_state
369    // live in email_submission_changes / email_submission_query_changes
370    // production code; testing them requires a wiremock-backed async harness.
371    // See JMAP-sc1b.64.
372
373    // Deleted in JMAP-tco1.5 as Pattern E (vacuous inline tests):
374    //   - submission_get_request_shape
375    //   - submission_changes_request_shape
376    //   - submission_query_request_includes_filter
377    //   - submission_query_changes_request_shape
378    //   - submission_set_on_success_update_email_request_shape
379    //   - submission_set_on_success_destroy_email_request_shape
380    // Each hand-built `args = json!({...})` and fed it to `build_request`,
381    // never invoking the `email_submission_get` / `email_submission_changes` /
382    // `email_submission_query` / `email_submission_query_changes` /
383    // `email_submission_set` production builders.
384    //
385    // Real production-path coverage:
386    //   - tests/submission_get_changes.rs:
387    //       email_submission_get_round_trip,
388    //       email_submission_get_specific_ids,
389    //       email_submission_changes_round_trip,
390    //       email_submission_changes_no_max_changes
391    //   - tests/submission_query.rs:
392    //       email_submission_query_with_filter,
393    //       email_submission_query_no_filter,
394    //       email_submission_query_changes_round_trip,
395    //       email_submission_query_changes_with_filter_and_sort
396    //   - tests/submission_set.rs:
397    //       email_submission_set_create_round_trip,
398    //       email_submission_set_on_success_update_email,
399    //       email_submission_set_no_on_success_when_none
400    //
401    // Specific-flag passthrough coverage that may be lost (`onSuccessDestroyEmail`)
402    // is tracked under JMAP-uuoi for a follow-up wiremock smoke test —
403    // there is no current wiremock test that asserts the
404    // `onSuccessDestroyEmail` array field reaches the wire.
405    //
406    // `build_request`, `CALL_ID`, and `USING_SUBMISSION` themselves have their
407    // own focused tests in `methods/mod.rs`.
408
409    // ── Response deserialization tests ───────────────────────────────────────
410
411    /// Oracle: GetResponse<EmailSubmission> deserializes from RFC 8621 §7.1 response shape.
412    /// JSON constructed from §7 field descriptions (not derived from code).
413    #[test]
414    fn submission_get_response_deserializes() {
415        let json_val = json!({
416            "accountId": "acc1",
417            "state": "s5",
418            "list": [
419                {
420                    "id": "sub1",
421                    "identityId": "ident1",
422                    "emailId": "eml1",
423                    "threadId": "thr1",
424                    "envelope": null,
425                    "sendAt": "2024-06-15T10:00:00Z",
426                    "undoStatus": "final",
427                    "deliveryStatus": null,
428                    "dsnBlobIds": [],
429                    "mdnBlobIds": []
430                }
431            ],
432            "notFound": []
433        });
434
435        use super::super::GetResponse;
436        let resp: GetResponse<jmap_mail_types::EmailSubmission> =
437            serde_json::from_value(json_val).expect("must deserialize EmailSubmission GetResponse");
438        assert_eq!(resp.state, "s5");
439        assert_eq!(resp.list.len(), 1);
440        assert_eq!(resp.list[0].id.as_ref(), "sub1");
441    }
442}