jmap_mail_client/methods/thread.rs
1//! JMAP Mail — Thread/* 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 jmap_types::{Id, State};
12
13use super::{ChangesResponse, GetResponse};
14
15impl super::SessionClient {
16 /// Fetch Thread objects by IDs (RFC 8621 §3.1 — Thread/get).
17 ///
18 /// If `ids` is `None`, the server returns all Threads for the account,
19 /// SUBJECT TO the server's `maxObjectsInGet` cap (RFC 8620 §5.1).
20 /// For production use, scope the result set via the corresponding
21 /// /query method first and pass explicit ids here to avoid
22 /// `requestTooLarge` errors when the account holds more objects
23 /// than the cap.
24 /// Pass `properties: None` to return all fields.
25 ///
26 /// # Errors
27 ///
28 /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
29 /// if the bound session has no primary account for
30 /// `urn:ietf:params:jmap:mail`.
31 /// - Any transport / protocol variant returned by
32 /// [`JmapClient::call`](jmap_base_client::JmapClient::call):
33 /// [`Http`](jmap_base_client::ClientError::Http),
34 /// [`Parse`](jmap_base_client::ClientError::Parse),
35 /// [`AuthFailed`](jmap_base_client::ClientError::AuthFailed),
36 /// [`MethodError`](jmap_base_client::ClientError::MethodError)
37 /// (wraps RFC 8620 §3.6.2 method-level errors such as
38 /// `accountNotFound`, `invalidArguments`, `serverFail`),
39 /// [`MethodNotFound`](jmap_base_client::ClientError::MethodNotFound),
40 /// [`ResponseTooLarge`](jmap_base_client::ClientError::ResponseTooLarge),
41 /// or
42 /// [`UnexpectedResponse`](jmap_base_client::ClientError::UnexpectedResponse).
43 pub async fn thread_get(
44 &self,
45 ids: Option<&[Id]>,
46 properties: Option<&[&str]>,
47 ) -> Result<GetResponse<jmap_mail_types::Thread>, jmap_base_client::ClientError> {
48 let (api_url, account_id) = self.session_parts()?;
49 // Omit `ids` / `properties` when None — see the matching comment on
50 // `email_get` for the rationale (consistent with set/changes/query).
51 let mut args = serde_json::json!({ "accountId": account_id });
52 if let Some(id_slice) = ids {
53 args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
54 }
55 if let Some(props) = properties {
56 args["properties"] =
57 serde_json::to_value(props).expect("&[&str] Serialize is infallible");
58 }
59 let req = super::build_request("Thread/get", args, super::USING_MAIL);
60 let resp = self.call_internal(api_url, &req).await?;
61 jmap_base_client::extract_response(&resp, super::CALL_ID)
62 }
63
64 /// Fetch changes to Thread objects since `since_state` (RFC 8621 §3.2 — Thread/changes).
65 ///
66 /// If `has_more_changes` is true in the response, call again with `new_state`
67 /// as `since_state` until the flag is false.
68 ///
69 /// `max_changes` follows the same RFC 8620 §5.2 magic-value semantics
70 /// as [`SessionClient::email_changes`](crate::methods::SessionClient::email_changes):
71 /// `None` lets the server apply its default cap, `Some(0)` means
72 /// "no client limit", `Some(n>0)` requests at most `n` entries.
73 ///
74 /// # Errors
75 ///
76 /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
77 /// if `since_state` is the empty string (defence-in-depth —
78 /// `State` constructed via [`State::from`](jmap_types::State::from)
79 /// accepts empty strings, but an empty `sinceState` is never
80 /// useful and would otherwise generate a wasted round-trip).
81 /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
82 /// if the bound session has no primary account for
83 /// `urn:ietf:params:jmap:mail`.
84 /// - Any transport / protocol variant returned by
85 /// [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
86 /// the matching error list on [`Self::thread_get`].
87 pub async fn thread_changes(
88 &self,
89 since_state: &State,
90 max_changes: Option<u64>,
91 ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
92 // Defence-in-depth: `State::new_validated` rejects empty strings, but
93 // `State::from` does not. Guard against pathological constructions.
94 if since_state.as_ref().is_empty() {
95 return Err(jmap_base_client::ClientError::InvalidArgument(
96 "thread_changes: since_state may not be empty".into(),
97 ));
98 }
99 let (api_url, account_id) = self.session_parts()?;
100 let mut args = serde_json::json!({
101 "accountId": account_id,
102 "sinceState": since_state,
103 });
104 if let Some(mc) = max_changes {
105 args["maxChanges"] = mc.into();
106 }
107 let req = super::build_request("Thread/changes", args, super::USING_MAIL);
108 let resp = self.call_internal(api_url, &req).await?;
109 jmap_base_client::extract_response(&resp, super::CALL_ID)
110 }
111}
112
113// ---------------------------------------------------------------------------
114// Tests
115// ---------------------------------------------------------------------------
116
117#[cfg(test)]
118mod tests {
119 use serde_json::json;
120
121 // thread_get_empty_id_returns_invalid_argument was deleted in JMAP-6by7.2
122 // (typed-Id refactor): under `Option<&[Id]>` the empty-Id case becomes
123 // impossible to express through the typed API.
124
125 // The InvalidArgument guard for empty since_state lives in thread_changes
126 // production code; testing it requires a wiremock-backed async harness.
127 // See JMAP-sc1b.64.
128
129 // Deleted in JMAP-tco1.5 as Pattern E (vacuous inline tests):
130 // - thread_get_request_shape
131 // - thread_changes_request_includes_since_state
132 // Each hand-built `args = json!({...})` and fed it to `build_request`,
133 // never invoking the `thread_get` / `thread_changes` production builders.
134 // Real production-path coverage for these methods is tracked as a
135 // wiremock-smoke gap under JMAP-uuoi (no `tests/thread_*.rs` smoke
136 // file exists yet).
137 //
138 // `build_request`, `CALL_ID`, and `USING_MAIL` themselves have their
139 // own focused tests in `methods/mod.rs`.
140
141 /// Oracle: Thread deserialization from RFC 8621 §3 shape.
142 /// RFC 8621 §3.1: Thread has id and emailIds fields.
143 #[test]
144 fn thread_get_response_deserializes() {
145 let json = json!({
146 "accountId": "acc1",
147 "state": "s5",
148 "list": [
149 {
150 "id": "t1",
151 "emailIds": ["e1", "e2", "e3"]
152 }
153 ],
154 "notFound": []
155 });
156 use super::super::GetResponse;
157 let resp: GetResponse<jmap_mail_types::Thread> =
158 serde_json::from_value(json).expect("must deserialize Thread GetResponse");
159 assert_eq!(resp.list.len(), 1);
160 assert_eq!(resp.list[0].id.as_ref(), "t1");
161 assert_eq!(resp.list[0].email_ids.len(), 3);
162 }
163}