io_jmap/rfc9610/contact_card/set.rs
1//! JMAP `ContactCard/set` coroutine (RFC 9610 §3.5): wraps the generic
2//! [`JmapSet`] with [`JmapContactCardSetArgs`] (create/update/destroy) and
3//! decodes per-object [`JmapContactCardSetItemError`] payloads.
4//!
5//! # Example
6//!
7//! ```rust,no_run
8//! use std::{
9//! io::{Read, Write},
10//! net::TcpStream,
11//! };
12//!
13//! use io_jmap::{
14//! coroutine::{JmapCoroutine, JmapCoroutineState, JmapYield},
15//! rfc8620::session::JmapSession,
16//! rfc9610::contact_card::set::{JmapContactCardSet, JmapContactCardSetArgs},
17//! };
18//! use secrecy::SecretString;
19//!
20//! // Ready stream needed (TCP-connected, TLS-negociated)
21//! let mut stream = TcpStream::connect("api.example.com:443").unwrap();
22//! let mut buf = [0u8; 4096];
23//!
24//! let session: JmapSession = serde_json::from_str(r#"{
25//! "username": "",
26//! "accounts": {},
27//! "primaryAccounts": {"urn:ietf:params:jmap:contacts": "a1"},
28//! "capabilities": {},
29//! "apiUrl": "https://api.example.com/jmap/",
30//! "downloadUrl": "",
31//! "uploadUrl": "",
32//! "eventSourceUrl": "",
33//! "state": ""
34//! }"#).unwrap();
35//! let auth = SecretString::from("Bearer xyz");
36//! let mut coroutine =
37//! JmapContactCardSet::new(&session, &auth, JmapContactCardSetArgs::default()).unwrap();
38//! let mut arg = None;
39//!
40//! let out = loop {
41//! match coroutine.resume(arg.take()) {
42//! JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
43//! stream.write_all(&bytes).unwrap();
44//! }
45//! JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
46//! let n = stream.read(&mut buf).unwrap();
47//! arg = Some(&buf[..n]);
48//! }
49//! JmapCoroutineState::Complete(Ok(out)) => break out,
50//! JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
51//! }
52//! };
53//!
54//! println!("new state {}", out.new_state);
55//! ```
56
57use alloc::{collections::BTreeMap, string::String, vec, vec::Vec};
58
59use secrecy::SecretString;
60use serde::{Deserialize, Serialize};
61use thiserror::Error;
62
63use crate::{
64 coroutine::*,
65 jmap_try,
66 rfc8620::{JMAP_CORE_CAPABILITY, request::JmapBatch, send::*, session::JmapSession, set::*},
67 rfc9610::{JMAP_CONTACTS_CAPABILITY, contact_card::JmapContactCard},
68};
69
70/// Patch object for `ContactCard/set` update requests (RFC 8620 §5.3): JSON
71/// pointer paths mapped to their new values; a `null` value removes the
72/// pointed property.
73#[derive(Clone, Debug, Default, Serialize)]
74#[serde(transparent)]
75pub struct JmapContactCardPatch(pub BTreeMap<String, serde_json::Value>);
76
77/// Per-object error returned in `ContactCard/set` responses (RFC 9610 §3.5).
78#[derive(Clone, Debug, Deserialize)]
79#[serde(tag = "type", rename_all = "camelCase")]
80pub enum JmapContactCardSetItemError {
81 /// One or more blob IDs in the card (e.g. a Media `blobId`) were not
82 /// found (RFC 9610 §3).
83 BlobNotFound {
84 /// Optional human-readable detail.
85 description: Option<String>,
86 },
87 /// Standard set error (RFC 8620 §5.3): the change is not allowed.
88 Forbidden {
89 /// Optional human-readable detail.
90 description: Option<String>,
91 },
92 /// Standard set error (RFC 8620 §5.3): target id not found.
93 NotFound {
94 /// Optional human-readable detail.
95 description: Option<String>,
96 },
97 /// Standard set error (RFC 8620 §5.3): patch could not be applied.
98 InvalidPatch {
99 /// Optional human-readable detail.
100 description: Option<String>,
101 },
102 /// Standard set error (RFC 8620 §5.3): would destroy an object already
103 /// queued for destruction in the same request.
104 WillDestroy {
105 /// Optional human-readable detail.
106 description: Option<String>,
107 },
108 /// Standard set error (RFC 8620 §5.3): one or more properties were
109 /// invalid.
110 InvalidProperties {
111 /// Optional human-readable detail.
112 description: Option<String>,
113 /// The invalid property names.
114 #[serde(default)]
115 properties: Vec<String>,
116 },
117 /// Catch-all for set errors not modelled above.
118 #[serde(other)]
119 Unknown,
120}
121
122/// Failure causes during a JMAP `ContactCard/set` flow.
123#[derive(Debug, Error)]
124pub enum JmapContactCardSetError {
125 /// The inner send coroutine failed.
126 #[error("JMAP ContactCard/set failed: {0}")]
127 Send(#[from] JmapSendError),
128 /// The method arguments could not be serialized.
129 #[error("JMAP ContactCard/set failed: serialize args: {0}")]
130 SerializeArgs(#[source] serde_json::Error),
131 /// The inner generic set coroutine failed.
132 #[error("JMAP ContactCard/set failed: {0}")]
133 Set(#[from] JmapSetError),
134}
135
136/// Arguments for a `ContactCard/set` request.
137#[derive(Clone, Debug, Default, Serialize)]
138#[serde(rename_all = "camelCase")]
139pub struct JmapContactCardSetArgs {
140 /// Objects to create (client ID → ContactCard object).
141 #[serde(skip_serializing_if = "Option::is_none")]
142 pub create: Option<BTreeMap<String, JmapContactCard>>,
143 /// Objects to update (ContactCard ID → patch object).
144 #[serde(skip_serializing_if = "Option::is_none")]
145 pub update: Option<BTreeMap<String, JmapContactCardPatch>>,
146 /// IDs of objects to destroy.
147 #[serde(skip_serializing_if = "Option::is_none")]
148 pub destroy: Option<Vec<String>>,
149}
150
151/// Successful terminal output of [`JmapContactCardSet`].
152#[derive(Clone, Debug)]
153pub struct JmapContactCardSetOutput {
154 /// The new server state after the call.
155 pub new_state: String,
156 /// The created cards, keyed by client id.
157 pub created: BTreeMap<String, JmapContactCard>,
158 /// The updated cards, keyed by id.
159 pub updated: BTreeMap<String, Option<JmapContactCard>>,
160 /// Ids of the destroyed objects.
161 pub destroyed: Vec<String>,
162 /// The failed creates, keyed by client id.
163 pub not_created: BTreeMap<String, JmapContactCardSetItemError>,
164 /// The failed updates, keyed by id.
165 pub not_updated: BTreeMap<String, JmapContactCardSetItemError>,
166 /// The failed destroys, keyed by id.
167 pub not_destroyed: BTreeMap<String, JmapContactCardSetItemError>,
168 /// Whether the server indicated the connection can be reused.
169 pub keep_alive: bool,
170}
171
172/// I/O-free coroutine for the JMAP `ContactCard/set` method.
173pub struct JmapContactCardSet {
174 state: State,
175}
176
177impl JmapContactCardSet {
178 /// Prepares the method call request and builds the coroutine.
179 pub fn new(
180 session: &JmapSession,
181 http_auth: &SecretString,
182 args: JmapContactCardSetArgs,
183 ) -> Result<Self, JmapContactCardSetError> {
184 let account_id = session
185 .primary_accounts
186 .get(JMAP_CONTACTS_CAPABILITY)
187 .cloned()
188 .unwrap_or_default();
189 let api_url = &session.api_url;
190
191 let json_args = serde_json::to_value(ContactCardSetRequest { account_id, args })
192 .map_err(JmapContactCardSetError::SerializeArgs)?;
193
194 let mut batch = JmapBatch::new();
195 batch.add("ContactCard/set", json_args);
196 let request = batch.into_request(vec![
197 JMAP_CORE_CAPABILITY.into(),
198 JMAP_CONTACTS_CAPABILITY.into(),
199 ]);
200
201 let send = JmapSend::new(http_auth, api_url, request)?;
202 Ok(Self {
203 state: State::Set(JmapSet::from_send(send)),
204 })
205 }
206}
207
208impl JmapCoroutine for JmapContactCardSet {
209 type Yield = JmapYield;
210 type Return = Result<JmapContactCardSetOutput, JmapContactCardSetError>;
211
212 fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
213 match &mut self.state {
214 State::Set(set) => {
215 let JmapSetOutput {
216 new_state,
217 created,
218 updated,
219 destroyed,
220 not_created,
221 not_updated,
222 not_destroyed,
223 keep_alive,
224 } = jmap_try!(set, arg);
225 let parse = |map: BTreeMap<String, serde_json::Value>| {
226 map.into_iter()
227 .map(|(k, v)| {
228 let e = serde_json::from_value(v)
229 .unwrap_or(JmapContactCardSetItemError::Unknown);
230 (k, e)
231 })
232 .collect()
233 };
234 JmapCoroutineState::Complete(Ok(JmapContactCardSetOutput {
235 new_state,
236 created,
237 updated,
238 destroyed,
239 not_created: parse(not_created),
240 not_updated: parse(not_updated),
241 not_destroyed: parse(not_destroyed),
242 keep_alive,
243 }))
244 }
245 }
246 }
247}
248
249enum State {
250 Set(JmapSet<JmapContactCard>),
251}
252
253#[derive(Serialize)]
254struct ContactCardSetRequest {
255 #[serde(rename = "accountId")]
256 account_id: String,
257 #[serde(flatten)]
258 args: JmapContactCardSetArgs,
259}