Skip to main content

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    /// Pass `properties: None` to return all fields.
20    pub async fn thread_get(
21        &self,
22        ids: Option<&[Id]>,
23        properties: Option<&[&str]>,
24    ) -> Result<GetResponse<jmap_mail_types::Thread>, jmap_base_client::ClientError> {
25        let (api_url, account_id) = self.session_parts()?;
26        // Omit `ids` / `properties` when None — see the matching comment on
27        // `email_get` for the rationale (consistent with set/changes/query).
28        let mut args = serde_json::json!({ "accountId": account_id });
29        if let Some(id_slice) = ids {
30            args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
31        }
32        if let Some(props) = properties {
33            args["properties"] = serde_json::Value::Array(
34                props.iter().copied().map(serde_json::Value::from).collect(),
35            );
36        }
37        let req = super::build_request("Thread/get", args, super::USING_MAIL);
38        let resp = self.call_internal(api_url, &req).await?;
39        jmap_base_client::extract_response(&resp, super::CALL_ID)
40    }
41
42    /// Fetch changes to Thread objects since `since_state` (RFC 8621 §3.2 — Thread/changes).
43    ///
44    /// If `has_more_changes` is true in the response, call again with `new_state`
45    /// as `since_state` until the flag is false.
46    pub async fn thread_changes(
47        &self,
48        since_state: &State,
49        max_changes: Option<u64>,
50    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
51        // Defence-in-depth: `State::new_validated` rejects empty strings, but
52        // `State::from` does not. Guard against pathological constructions.
53        if since_state.as_ref().is_empty() {
54            return Err(jmap_base_client::ClientError::InvalidArgument(
55                "thread_changes: since_state may not be empty".into(),
56            ));
57        }
58        let (api_url, account_id) = self.session_parts()?;
59        let mut args = serde_json::json!({
60            "accountId": account_id,
61            "sinceState": since_state,
62        });
63        if let Some(mc) = max_changes {
64            args["maxChanges"] = mc.into();
65        }
66        let req = super::build_request("Thread/changes", args, super::USING_MAIL);
67        let resp = self.call_internal(api_url, &req).await?;
68        jmap_base_client::extract_response(&resp, super::CALL_ID)
69    }
70}
71
72// ---------------------------------------------------------------------------
73// Tests
74// ---------------------------------------------------------------------------
75
76#[cfg(test)]
77mod tests {
78    use serde_json::json;
79
80    // thread_get_empty_id_returns_invalid_argument was deleted in JMAP-6by7.2
81    // (typed-Id refactor): under `Option<&[Id]>` the empty-Id case becomes
82    // impossible to express through the typed API.
83
84    // The InvalidArgument guard for empty since_state lives in thread_changes
85    // production code; testing it requires a wiremock-backed async harness.
86    // See JMAP-sc1b.64.
87
88    // Deleted in JMAP-tco1.5 as Pattern E (vacuous inline tests):
89    //   - thread_get_request_shape
90    //   - thread_changes_request_includes_since_state
91    // Each hand-built `args = json!({...})` and fed it to `build_request`,
92    // never invoking the `thread_get` / `thread_changes` production builders.
93    // Real production-path coverage for these methods is tracked as a
94    // wiremock-smoke gap under JMAP-uuoi (no `tests/thread_*.rs` smoke
95    // file exists yet).
96    //
97    // `build_request`, `CALL_ID`, and `USING_MAIL` themselves have their
98    // own focused tests in `methods/mod.rs`.
99
100    /// Oracle: Thread deserialization from RFC 8621 §3 shape.
101    /// RFC 8621 §3.1: Thread has id and emailIds fields.
102    #[test]
103    fn thread_get_response_deserializes() {
104        let json = json!({
105            "accountId": "acc1",
106            "state": "s5",
107            "list": [
108                {
109                    "id": "t1",
110                    "emailIds": ["e1", "e2", "e3"]
111                }
112            ],
113            "notFound": []
114        });
115        use super::super::GetResponse;
116        let resp: GetResponse<jmap_mail_types::Thread> =
117            serde_json::from_value(json).expect("must deserialize Thread GetResponse");
118        assert_eq!(resp.list.len(), 1);
119        assert_eq!(resp.list[0].id.as_ref(), "t1");
120        assert_eq!(resp.list[0].email_ids.len(), 3);
121    }
122}