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    /// SUBJECT TO the server's `maxObjectsInGet` cap (RFC 8620 §5.1).
22    /// For production use, scope the result set via the corresponding
23    /// /query method first and pass explicit ids here to avoid
24    /// `requestTooLarge` errors when the account holds more objects
25    /// than the cap.
26    /// Pass `properties: None` to return all fields.
27    ///
28    /// # Errors
29    ///
30    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
31    ///   if the bound session has no primary account for
32    ///   `urn:ietf:params:jmap:tasks`.
33    /// - Any transport / protocol variant returned by
34    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call):
35    ///   [`Http`](jmap_base_client::ClientError::Http),
36    ///   [`Parse`](jmap_base_client::ClientError::Parse),
37    ///   [`AuthFailed`](jmap_base_client::ClientError::AuthFailed),
38    ///   [`MethodError`](jmap_base_client::ClientError::MethodError)
39    ///   (wraps RFC 8620 §3.6.2 method-level errors such as
40    ///   `accountNotFound`, `invalidArguments`, `serverFail`),
41    ///   [`MethodNotFound`](jmap_base_client::ClientError::MethodNotFound),
42    ///   [`ResponseTooLarge`](jmap_base_client::ClientError::ResponseTooLarge),
43    ///   or
44    ///   [`UnexpectedResponse`](jmap_base_client::ClientError::UnexpectedResponse).
45    pub async fn task_list_get(
46        &self,
47        ids: Option<&[Id]>,
48        properties: Option<&[&str]>,
49    ) -> Result<GetResponse<jmap_tasks_types::TaskList>, jmap_base_client::ClientError> {
50        let (api_url, account_id) = self.session_parts()?;
51        // Omit `ids` / `properties` entirely when None rather than sending
52        // an explicit JSON null. RFC 8620 §5.1 accepts both shapes, but the
53        // crate's other builders (set/changes/query) consistently use the
54        // conditional-add idiom; matching it here keeps the wire request
55        // canonical and avoids "present-but-null vs absent" interop quirks
56        // in proxies / audit loggers.
57        let mut args = serde_json::json!({ "accountId": account_id });
58        if let Some(id_slice) = ids {
59            args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
60        }
61        if let Some(props) = properties {
62            args["properties"] =
63                serde_json::to_value(props).expect("&[&str] Serialize is infallible");
64        }
65        let req = super::build_request("TaskList/get", args, super::USING_TASKS);
66        let resp = self.call_internal(api_url, &req).await?;
67        jmap_base_client::extract_response(&resp, super::CALL_ID)
68    }
69
70    /// Fetch changes to TaskList objects since `since_state` (draft-tasks-06 §3.6).
71    ///
72    /// If `has_more_changes` is true in the response, call again with `new_state`
73    /// as `since_state` until the flag is false.
74    ///
75    /// # Errors
76    ///
77    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
78    ///   if `since_state` is the empty string (defence-in-depth —
79    ///   `State` constructed via [`State::from`](jmap_types::State::from)
80    ///   accepts empty strings, but an empty `sinceState` is never
81    ///   useful and would otherwise generate a wasted round-trip).
82    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
83    ///   if the bound session has no primary account for
84    ///   `urn:ietf:params:jmap:tasks`.
85    /// - Any transport / protocol variant returned by
86    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
87    ///   the matching error list on [`Self::task_list_get`].
88    pub async fn task_list_changes(
89        &self,
90        since_state: &State,
91        max_changes: Option<u64>,
92    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
93        // Defence-in-depth: even with the typed-`State` parameter (a transparent
94        // newtype around `String`), an empty state token is still a logically
95        // invalid value that should be caught client-side rather than producing
96        // a confusing server-side `cannotCalculateChanges` error.
97        if since_state.as_ref().is_empty() {
98            return Err(jmap_base_client::ClientError::InvalidArgument(
99                "task_list_changes: since_state may not be empty".into(),
100            ));
101        }
102        let (api_url, account_id) = self.session_parts()?;
103        let mut args = serde_json::json!({
104            "accountId": account_id,
105            "sinceState": since_state,
106        });
107        if let Some(mc) = max_changes {
108            args["maxChanges"] = mc.into();
109        }
110        let req = super::build_request("TaskList/changes", args, super::USING_TASKS);
111        let resp = self.call_internal(api_url, &req).await?;
112        jmap_base_client::extract_response(&resp, super::CALL_ID)
113    }
114
115    /// Create, update, or destroy TaskList objects (draft-tasks-06 §3.7).
116    ///
117    /// Pass `create`, `update`, and/or `destroy` as needed. All three are
118    /// optional; pass `None` to omit any operation from the request.
119    ///
120    /// `update` is `Option<HashMap<Id, PatchObject>>` (RFC 8620 §5.3). Wire
121    /// format is unchanged from a plain JSON object because [`PatchObject`]
122    /// is `#[serde(transparent)]`; the typed parameter binds the JSON Pointer
123    /// key + null-leaf removal contract to the type system.
124    ///
125    /// `params` carries extra method-level arguments
126    /// ([`TaskListSetParams`](super::TaskListSetParams)). Pass `None`
127    /// (or `Some(Default::default())`) for spec-default behavior. Use
128    /// [`TaskListSetParams::on_destroy_remove_tasks`](super::TaskListSetParams::on_destroy_remove_tasks)
129    /// to allow destroying a non-empty TaskList (otherwise the server
130    /// returns `taskListHasTasks`), and
131    /// [`TaskListSetParams::extra`](super::TaskListSetParams::extra) for
132    /// vendor / site extension fields (workspace extras-preservation
133    /// policy).
134    ///
135    /// # Errors
136    ///
137    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
138    ///   if the bound session has no primary account for
139    ///   `urn:ietf:params:jmap:tasks`.
140    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
141    ///   if `update` is `Some` and `serde_json::to_value` fails on the
142    ///   patch map (pathological conditions only; see [`Self::task_set`]
143    ///   for the memory-cost discussion that applies identically here).
144    /// - Any transport / protocol variant returned by
145    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
146    ///   the matching error list on [`Self::task_list_get`].
147    pub async fn task_list_set(
148        &self,
149        create: Option<serde_json::Value>,
150        update: Option<HashMap<Id, PatchObject>>,
151        destroy: Option<Vec<Id>>,
152        params: Option<super::TaskListSetParams>,
153    ) -> Result<SetResponse<jmap_tasks_types::TaskList>, jmap_base_client::ClientError> {
154        if create.is_none() && update.is_none() && destroy.is_none() {
155            return Err(jmap_base_client::ClientError::InvalidArgument(
156                "task_list_set: at least one of create, update, destroy must be Some \
157                 (an all-None /set is a no-op round-trip)"
158                    .into(),
159            ));
160        }
161        let (api_url, account_id) = self.session_parts()?;
162        let mut args = serde_json::json!({
163            "accountId": account_id,
164        });
165        let mut params_extra: Option<serde_json::Map<String, serde_json::Value>> = None;
166        if let Some(p) = params {
167            if let Some(v) = p.on_destroy_remove_tasks {
168                args["onDestroyRemoveTasks"] = v.into();
169            }
170            if !p.extra.is_empty() {
171                params_extra = Some(p.extra);
172            }
173        }
174        if let Some(c) = create {
175            args["create"] = c;
176        }
177        if let Some(u) = update {
178            args["update"] = serde_json::to_value(&u).map_err(|e| {
179                jmap_base_client::ClientError::InvalidArgument(format!(
180                    "task_list_set: serializing update map failed: {e}"
181                ))
182            })?;
183        }
184        if let Some(d) = destroy {
185            args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
186        }
187        // Route caller-supplied vendor extras onto the wire (workspace
188        // extras-preservation policy). Use `entry().or_insert()` so a
189        // caller who put a typed wire key into `params.extra` cannot
190        // silently clobber the typed value — typed wins on collision.
191        if let Some(extra) = params_extra {
192            let args_obj = args
193                .as_object_mut()
194                .expect("task_list_set: args is constructed as Object");
195            for (k, v) in extra {
196                args_obj.entry(k).or_insert(v);
197            }
198        }
199        let req = super::build_request("TaskList/set", args, super::USING_TASKS);
200        let resp = self.call_internal(api_url, &req).await?;
201        jmap_base_client::extract_response(&resp, super::CALL_ID)
202    }
203}
204
205// ---------------------------------------------------------------------------
206// Tests — see tests/task_list_tests.rs (wiremock-backed end-to-end)
207// ---------------------------------------------------------------------------
208//
209// `task_list_set_on_destroy_remove_tasks_in_args` was vacuous: it hand-built
210// `args` Values and fed them to `build_request`, never exercising the
211// production `task_list_set` builder. Deleted in JMAP-tco1.20.
212//
213// Real production-path coverage:
214//   - task_list_get_sends_correct_wire_request
215//   - task_list_changes_sends_since_state
216//   - task_list_set_on_destroy_remove_tasks_round_trip
217//   - task_list_set_without_on_destroy_omits_field
218// in tests/task_list_tests.rs.
219//
220// Specific-flag passthrough coverage that may be lost is tracked
221// under JMAP-uuoi for follow-up wiremock smoke tests.
222//
223// `build_request`, `CALL_ID`, and `USING_TASKS` themselves have their
224// own focused tests in `methods/mod.rs`.
225//
226// The InvalidArgument guard for empty since_state lives in
227// task_list_changes production code; testing it requires a wiremock-backed
228// async harness. See JMAP-sc1b.64.
229//
230// The `task_list_get_empty_id_returns_invalid_argument` inline smoke test
231// was removed by the JMAP-6by7.5 typed-Id refactor. It was vacuous because
232// it only iterated a local `&[""]` slice and asserted `is_empty()` found
233// the empty value, without invoking any production method. Under typed
234// `&[Id]` parameters, an empty-Id input is impossible to express through
235// the API (`Id::new_validated("")` returns `Err` at the call site) so the
236// bug it pretended to test is unrepresentable.