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