Skip to main content

jmap_contacts_client/methods/
addressbook.rs

1//! JMAP Contacts — AddressBook/* 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_CONTACTS)`.
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::{AddressBookSetParams, ChangesResponse, GetResponse, SetResponse};
16
17impl super::SessionClient {
18    /// Fetch AddressBook objects by IDs (RFC 9610 §2.1).
19    ///
20    /// If `ids` is `None`, the server returns all AddressBooks 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:contacts`.
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 address_book_get(
46        &self,
47        ids: Option<&[Id]>,
48        properties: Option<&[&str]>,
49    ) -> Result<GetResponse<jmap_contacts_types::AddressBook>, 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("AddressBook/get", args, super::USING_CONTACTS);
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 AddressBook objects since `since_state`
71    /// (RFC 9610 §2.2).
72    ///
73    /// If `has_more_changes` is true in the response, call again with
74    /// `new_state` as `since_state` until the flag is false.
75    ///
76    /// # Errors
77    ///
78    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
79    ///   if `since_state` is the empty string (defence-in-depth —
80    ///   `State` constructed via [`State::from`](jmap_types::State::from)
81    ///   accepts empty strings, but an empty `sinceState` is never
82    ///   useful and would otherwise generate a wasted round-trip).
83    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
84    ///   if the bound session has no primary account for
85    ///   `urn:ietf:params:jmap:contacts`.
86    /// - Any transport / protocol variant returned by
87    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
88    ///   the matching error list on [`Self::address_book_get`].
89    pub async fn address_book_changes(
90        &self,
91        since_state: &State,
92        max_changes: Option<u64>,
93    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
94        // Defence-in-depth: even with the typed-`State` parameter (a transparent
95        // newtype around `String`), an empty state token is still a logically
96        // invalid value that should be caught client-side rather than producing
97        // a confusing server-side `cannotCalculateChanges` error.
98        if since_state.as_ref().is_empty() {
99            return Err(jmap_base_client::ClientError::InvalidArgument(
100                "address_book_changes: since_state may not be empty".into(),
101            ));
102        }
103        let (api_url, account_id) = self.session_parts()?;
104        let mut args = serde_json::json!({
105            "accountId": account_id,
106            "sinceState": since_state,
107        });
108        if let Some(mc) = max_changes {
109            args["maxChanges"] = mc.into();
110        }
111        let req = super::build_request("AddressBook/changes", args, super::USING_CONTACTS);
112        let resp = self.call_internal(api_url, &req).await?;
113        jmap_base_client::extract_response(&resp, super::CALL_ID)
114    }
115
116    /// Create, update, or destroy AddressBook objects
117    /// (RFC 9610 §2.3).
118    ///
119    /// Pass `create`, `update`, and/or `destroy` as needed. All three are
120    /// optional; pass `None` to omit any operation from the request.
121    ///
122    /// `update` is `Option<HashMap<Id, PatchObject>>` (RFC 8620 §5.3). Wire
123    /// format is unchanged from a plain JSON object because [`PatchObject`]
124    /// is `#[serde(transparent)]`; the typed parameter binds the JSON Pointer
125    /// key + null-leaf removal contract to the type system.
126    ///
127    /// `params` carries the Contacts-specific extra arguments
128    /// `onDestroyRemoveContents` and `onSuccessSetIsDefault`. Pass
129    /// `None` (or `Some(Default::default())`) when neither is needed.
130    ///
131    /// # Errors
132    ///
133    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
134    ///   if the bound session has no primary account for
135    ///   `urn:ietf:params:jmap:contacts`.
136    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
137    ///   if `update` is `Some` and `serde_json::to_value` fails on the
138    ///   patch map (pathological conditions only — allocation failure,
139    ///   or a `PatchObject` whose JSON tree exceeds `serde_json`'s
140    ///   recursion limit). The transient memory peak for very large
141    ///   `update` maps is roughly 3-4× the `HashMap`'s in-memory size
142    ///   (source map + `serde_json::Value` tree + serialized `Vec<u8>`
143    ///   body); callers dealing with thousands of patches per call may
144    ///   prefer to batch.
145    /// - Any transport / protocol variant returned by
146    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
147    ///   the matching error list on [`Self::address_book_get`].
148    pub async fn address_book_set(
149        &self,
150        create: Option<serde_json::Value>,
151        update: Option<HashMap<Id, PatchObject>>,
152        destroy: Option<Vec<Id>>,
153        params: Option<AddressBookSetParams>,
154    ) -> Result<SetResponse<jmap_contacts_types::AddressBook>, jmap_base_client::ClientError> {
155        if create.is_none() && update.is_none() && destroy.is_none() {
156            return Err(jmap_base_client::ClientError::InvalidArgument(
157                "address_book_set: at least one of create, update, destroy must be Some \
158                 (an all-None /set is a no-op round-trip)"
159                    .into(),
160            ));
161        }
162        let (api_url, account_id) = self.session_parts()?;
163        let mut args = serde_json::json!({
164            "accountId": account_id,
165        });
166        if let Some(c) = create {
167            args["create"] = c;
168        }
169        if let Some(u) = update {
170            args["update"] = serde_json::to_value(&u).map_err(|e| {
171                jmap_base_client::ClientError::InvalidArgument(format!(
172                    "address_book_set: serializing update map failed: {e}"
173                ))
174            })?;
175        }
176        if let Some(d) = destroy {
177            args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
178        }
179        if let Some(p) = params {
180            if let Some(v) = p.on_destroy_remove_contents {
181                args["onDestroyRemoveContents"] = v.into();
182            }
183            if let Some(v) = p.on_success_set_is_default {
184                args["onSuccessSetIsDefault"] = v;
185            }
186        }
187        let req = super::build_request("AddressBook/set", args, super::USING_CONTACTS);
188        let resp = self.call_internal(api_url, &req).await?;
189        jmap_base_client::extract_response(&resp, super::CALL_ID)
190    }
191}
192
193// ---------------------------------------------------------------------------
194// Tests
195// ---------------------------------------------------------------------------
196
197#[cfg(test)]
198mod tests {
199    use serde_json::json;
200
201    // Inline guard smoke tests (e.g. `address_book_get_empty_id_returns_invalid_argument`,
202    // `address_book_changes_empty_since_state_returns_invalid_argument`,
203    // `address_book_set_empty_destroy_id_returns_invalid_argument`) were
204    // removed by the JMAP-6by7.4 typed-Id refactor. They were vacuous
205    // because they only iterated a local `&[""]` slice (or duplicated the
206    // guard's `is_empty()` check) and asserted `is_empty()` found the
207    // empty value, without invoking any production method. Under typed
208    // `&[Id]` / `Vec<Id>` parameters, an empty-Id input is impossible to
209    // express through the API (`Id::new_validated("")` returns `Err` at
210    // the call site) so the bug they pretended to test is unrepresentable.
211    //
212    // Additionally, `address_book_get_request_shape`,
213    // `address_book_changes_request_includes_since_state`,
214    // `address_book_set_destroy_request_shape`, and
215    // `address_book_set_params_on_destroy_serializes` were vacuous: they
216    // hand-built `args` Values and fed them to `build_request`, never
217    // exercising the production `address_book_*` builders. Deleted in
218    // JMAP-tco1.15.
219    //
220    // Real production-path coverage:
221    //   - addressbook_get_round_trip
222    //   - addressbook_changes_sends_since_state
223    //   - addressbook_set_create_round_trip
224    //   - addressbook_set_on_destroy_remove_contents
225    // in tests/addressbook_tests.rs (wiremock-backed end-to-end).
226    //
227    // Specific-flag passthrough coverage that may be lost is tracked
228    // under JMAP-uuoi for follow-up wiremock smoke tests.
229    //
230    // `build_request`, `CALL_ID`, and `USING_CONTACTS` themselves have
231    // their own focused tests in `methods/mod.rs`, including a
232    // dedicated `AddressBookSetParams` serialization test.
233
234    /// Oracle: AddressBook deserialization from RFC 9610 §4.1 example.
235    /// Expected JSON taken verbatim from spec §4.1.
236    #[test]
237    fn address_book_deserializes_from_spec_example() {
238        let json = json!({
239            "id": "062adcfa-105d-455c-bc60-6db68b69c3f3",
240            "name": "Personal",
241            "description": null,
242            "sortOrder": 0,
243            "isDefault": true,
244            "isSubscribed": true,
245            "shareWith": null,
246            "myRights": {
247                "mayRead": true,
248                "mayWrite": true,
249                "mayShare": true,
250                "mayDelete": false
251            }
252        });
253        let ab: jmap_contacts_types::AddressBook =
254            serde_json::from_value(json).expect("AddressBook must deserialize");
255        assert_eq!(ab.name, "Personal");
256        assert!(ab.is_default);
257        assert!(ab.is_subscribed);
258        assert_eq!(ab.sort_order, 0);
259        assert!(ab.description.is_none());
260        assert!(ab.share_with.is_none());
261        assert!(ab.my_rights.may_read);
262        assert!(ab.my_rights.may_write);
263        assert!(ab.my_rights.may_share);
264        assert!(!ab.my_rights.may_delete);
265    }
266
267    /// Oracle: GetResponse<AddressBook> deserializes from RFC 8620 §5.1 shape.
268    #[test]
269    fn get_response_address_book_deserializes() {
270        use super::super::GetResponse;
271
272        let json = json!({
273            "accountId": "acc1",
274            "state": "s42",
275            "list": [
276                {
277                    "id": "ab1",
278                    "name": "Personal",
279                    "sortOrder": 0,
280                    "isDefault": true,
281                    "isSubscribed": true,
282                    "myRights": {
283                        "mayRead": true,
284                        "mayWrite": true,
285                        "mayShare": false,
286                        "mayDelete": false
287                    }
288                }
289            ],
290            "notFound": null
291        });
292        let resp: GetResponse<jmap_contacts_types::AddressBook> =
293            serde_json::from_value(json).expect("GetResponse<AddressBook> must deserialize");
294        assert_eq!(resp.account_id, "acc1");
295        assert_eq!(resp.list.len(), 1);
296        assert_eq!(resp.list[0].name, "Personal");
297        assert!(resp.not_found.is_none());
298    }
299}