Skip to main content

jmap_tasks_client/methods/
task_list.rs

1//! JMAP Tasks — TaskList/* 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_TASKS)`.
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::{ChangesResponse, GetResponse, SetResponse};
16
17impl super::SessionClient {
18    /// Fetch TaskList objects by IDs (draft-tasks-06 §3.5).
19    ///
20    /// If `ids` is `None`, the server returns all TaskLists for the account.
21    /// Pass `properties: None` to return all fields.
22    pub async fn task_list_get(
23        &self,
24        ids: Option<&[Id]>,
25        properties: Option<&[&str]>,
26    ) -> Result<GetResponse<jmap_tasks_types::TaskList>, jmap_base_client::ClientError> {
27        let (api_url, account_id) = self.session_parts()?;
28        // Omit `ids` / `properties` entirely when None rather than sending
29        // an explicit JSON null. RFC 8620 §5.1 accepts both shapes, but the
30        // crate's other builders (set/changes/query) consistently use the
31        // conditional-add idiom; matching it here keeps the wire request
32        // canonical and avoids "present-but-null vs absent" interop quirks
33        // in proxies / audit loggers.
34        let mut args = serde_json::json!({ "accountId": account_id });
35        if let Some(id_slice) = ids {
36            args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
37        }
38        if let Some(props) = properties {
39            args["properties"] = serde_json::Value::Array(
40                props.iter().copied().map(serde_json::Value::from).collect(),
41            );
42        }
43        let req = super::build_request("TaskList/get", args, super::USING_TASKS);
44        let resp = self.call_internal(api_url, &req).await?;
45        jmap_base_client::extract_response(&resp, super::CALL_ID)
46    }
47
48    /// Fetch changes to TaskList objects since `since_state` (draft-tasks-06 §3.6).
49    ///
50    /// If `has_more_changes` is true in the response, call again with `new_state`
51    /// as `since_state` until the flag is false.
52    pub async fn task_list_changes(
53        &self,
54        since_state: &State,
55        max_changes: Option<u64>,
56    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
57        // Defence-in-depth: even with the typed-`State` parameter (a transparent
58        // newtype around `String`), an empty state token is still a logically
59        // invalid value that should be caught client-side rather than producing
60        // a confusing server-side `cannotCalculateChanges` error.
61        if since_state.as_ref().is_empty() {
62            return Err(jmap_base_client::ClientError::InvalidArgument(
63                "task_list_changes: since_state may not be empty".into(),
64            ));
65        }
66        let (api_url, account_id) = self.session_parts()?;
67        let mut args = serde_json::json!({
68            "accountId": account_id,
69            "sinceState": since_state,
70        });
71        if let Some(mc) = max_changes {
72            args["maxChanges"] = mc.into();
73        }
74        let req = super::build_request("TaskList/changes", args, super::USING_TASKS);
75        let resp = self.call_internal(api_url, &req).await?;
76        jmap_base_client::extract_response(&resp, super::CALL_ID)
77    }
78
79    /// Create, update, or destroy TaskList objects (draft-tasks-06 §3.7).
80    ///
81    /// `on_destroy_remove_tasks`: if `true`, any tasks in destroyed task lists
82    /// are also destroyed. If `false` (default), attempting to destroy a task list
83    /// that still contains tasks returns a `taskListHasTasks` error for that id.
84    ///
85    /// Pass `create`, `update`, and/or `destroy` as needed. All three are
86    /// optional; pass `None` to omit any operation from the request.
87    ///
88    /// `update` is `Option<HashMap<Id, PatchObject>>` (RFC 8620 §5.3). Wire
89    /// format is unchanged from a plain JSON object because [`PatchObject`]
90    /// is `#[serde(transparent)]`; the typed parameter binds the JSON Pointer
91    /// key + null-leaf removal contract to the type system.
92    pub async fn task_list_set(
93        &self,
94        create: Option<serde_json::Value>,
95        update: Option<HashMap<Id, PatchObject>>,
96        destroy: Option<Vec<Id>>,
97        on_destroy_remove_tasks: Option<bool>,
98    ) -> Result<SetResponse<jmap_tasks_types::TaskList>, jmap_base_client::ClientError> {
99        let (api_url, account_id) = self.session_parts()?;
100        let mut args = serde_json::json!({
101            "accountId": account_id,
102        });
103        if let Some(c) = create {
104            args["create"] = c;
105        }
106        if let Some(u) = update {
107            args["update"] = serde_json::to_value(&u).map_err(|e| {
108                jmap_base_client::ClientError::InvalidArgument(format!(
109                    "task_list_set: serializing update map failed: {e}"
110                ))
111            })?;
112        }
113        if let Some(d) = destroy {
114            args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
115        }
116        if let Some(v) = on_destroy_remove_tasks {
117            args["onDestroyRemoveTasks"] = v.into();
118        }
119        let req = super::build_request("TaskList/set", args, super::USING_TASKS);
120        let resp = self.call_internal(api_url, &req).await?;
121        jmap_base_client::extract_response(&resp, super::CALL_ID)
122    }
123}
124
125// ---------------------------------------------------------------------------
126// Tests — see tests/task_list_tests.rs (wiremock-backed end-to-end)
127// ---------------------------------------------------------------------------
128//
129// `task_list_set_on_destroy_remove_tasks_in_args` was vacuous: it hand-built
130// `args` Values and fed them to `build_request`, never exercising the
131// production `task_list_set` builder. Deleted in JMAP-tco1.20.
132//
133// Real production-path coverage:
134//   - task_list_get_sends_correct_wire_request
135//   - task_list_changes_sends_since_state
136//   - task_list_set_on_destroy_remove_tasks_round_trip
137//   - task_list_set_without_on_destroy_omits_field
138// in tests/task_list_tests.rs.
139//
140// Specific-flag passthrough coverage that may be lost is tracked
141// under JMAP-uuoi for follow-up wiremock smoke tests.
142//
143// `build_request`, `CALL_ID`, and `USING_TASKS` themselves have their
144// own focused tests in `methods/mod.rs`.
145//
146// The InvalidArgument guard for empty since_state lives in
147// task_list_changes production code; testing it requires a wiremock-backed
148// async harness. See JMAP-sc1b.64.
149//
150// The `task_list_get_empty_id_returns_invalid_argument` inline smoke test
151// was removed by the JMAP-6by7.5 typed-Id refactor. It was vacuous because
152// it only iterated a local `&[""]` slice and asserted `is_empty()` found
153// the empty value, without invoking any production method. Under typed
154// `&[Id]` parameters, an empty-Id input is impossible to express through
155// the API (`Id::new_validated("")` returns `Err` at the call site) so the
156// bug it pretended to test is unrepresentable.