Skip to main content

io_jmap/rfc8621/identity/
set.rs

1//! JMAP `Identity/set` coroutine (RFC 8621 §6.4): builds a custom set batch
2//! (Identity has no generic `JmapSet` reuse because its set response is parsed
3//! loosely to tolerate partial server output).
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//!     rfc8621::identity::set::{JmapIdentitySet, JmapIdentitySetArgs},
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:mail": "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 args = JmapIdentitySetArgs::default();
37//! args.destroy("id1");
38//! let mut coroutine = JmapIdentitySet::new(&session, &auth, args).unwrap();
39//! let mut arg = None;
40//!
41//! let out = loop {
42//!     match coroutine.resume(arg.take()) {
43//!         JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
44//!             stream.write_all(&bytes).unwrap();
45//!         }
46//!         JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
47//!             let n = stream.read(&mut buf).unwrap();
48//!             arg = Some(&buf[..n]);
49//!         }
50//!         JmapCoroutineState::Complete(Ok(out)) => break out,
51//!         JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
52//!     }
53//! };
54//!
55//! println!("new state {}", out.new_state);
56//! ```
57
58use alloc::{collections::BTreeMap, string::String, vec, vec::Vec};
59
60use secrecy::SecretString;
61use serde::{Deserialize, Serialize};
62use thiserror::Error;
63
64use crate::{
65    coroutine::*,
66    jmap_try,
67    rfc8620::{
68        JMAP_CORE_CAPABILITY, error::JmapMethodError, request::JmapBatch, send::*,
69        session::JmapSession,
70    },
71    rfc8621::{
72        JMAP_MAIL_CAPABILITY, email::JmapEmailAddress,
73        email_submission::JMAP_SUBMISSION_CAPABILITY, identity::JmapIdentity,
74    },
75};
76
77/// A partial [`JmapIdentity`] object for `Identity/set` create requests.
78#[derive(Clone, Debug, Default, Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct JmapIdentityCreate {
81    /// The display name for the sender.
82    pub name: String,
83    /// The email address for the sender.
84    pub email: String,
85    /// `Reply-To` addresses to set on outgoing email.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub reply_to: Option<Vec<JmapEmailAddress>>,
88    /// `Bcc` addresses to add to all outgoing email.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub bcc: Option<Vec<JmapEmailAddress>>,
91    /// Plaintext signature to append to outgoing email.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub text_signature: Option<String>,
94    /// HTML signature to append to outgoing email.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub html_signature: Option<String>,
97}
98
99/// Patch object for `Identity/set` update requests.
100///
101/// Only `Some` fields are serialized.
102#[derive(Clone, Debug, Default, Serialize)]
103#[serde(rename_all = "camelCase")]
104pub struct JmapIdentityUpdate {
105    /// The display name for the sender.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub name: Option<String>,
108    /// `Reply-To` addresses to set on outgoing email.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub reply_to: Option<Vec<JmapEmailAddress>>,
111    /// `Bcc` addresses to add to all outgoing email.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub bcc: Option<Vec<JmapEmailAddress>>,
114    /// Plaintext signature to append to outgoing email.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub text_signature: Option<String>,
117    /// HTML signature to append to outgoing email.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub html_signature: Option<String>,
120}
121
122/// Per-object error returned in `Identity/set` responses (RFC 8621 §6.4).
123#[derive(Clone, Debug, Deserialize)]
124#[serde(tag = "type", rename_all = "camelCase")]
125pub enum JmapIdentitySetItemError {
126    /// Standard set error (RFC 8620 §5.3): target id not found.
127    NotFound {
128        /// Optional human-readable detail.
129        description: Option<String>,
130    },
131    /// Standard set error (RFC 8620 §5.3): patch could not be applied.
132    InvalidPatch {
133        /// Optional human-readable detail.
134        description: Option<String>,
135    },
136    /// Standard set error (RFC 8620 §5.3): would destroy an object already
137    /// queued for destruction in the same request.
138    WillDestroy {
139        /// Optional human-readable detail.
140        description: Option<String>,
141    },
142    /// Standard set error (RFC 8620 §5.3): one or more properties were invalid.
143    InvalidProperties {
144        /// Optional human-readable detail.
145        description: Option<String>,
146        /// The invalid property names.
147        #[serde(default)]
148        properties: Vec<String>,
149    },
150    /// Standard set error (RFC 8620 §5.3): tried to create/destroy a
151    /// server-managed singleton.
152    Singleton {
153        /// Optional human-readable detail.
154        description: Option<String>,
155    },
156    /// Catch-all for set errors not modelled above.
157    #[serde(other)]
158    Unknown,
159}
160
161/// Failure causes during a JMAP `Identity/set` flow.
162#[derive(Debug, Error)]
163pub enum JmapIdentitySetError {
164    /// The response carried no method response.
165    #[error("JMAP Identity/set failed: missing response in method_responses")]
166    MissingResponse,
167    /// The inner send coroutine failed.
168    #[error("JMAP Identity/set failed: {0}")]
169    Send(#[from] JmapSendError),
170    /// The method arguments could not be serialized.
171    #[error("JMAP Identity/set failed: serialize args: {0}")]
172    SerializeArgs(#[source] serde_json::Error),
173    /// The method response could not be parsed.
174    #[error("JMAP Identity/set failed: parse response: {0}")]
175    ParseResponse(#[source] serde_json::Error),
176    /// The server returned a method-level error.
177    #[error("JMAP Identity/set failed: {0}")]
178    Method(#[from] JmapMethodError),
179}
180
181/// Arguments for an `Identity/set` request.
182#[derive(Clone, Debug, Default)]
183pub struct JmapIdentitySetArgs {
184    /// The identities to create, keyed by client id.
185    pub create: BTreeMap<String, JmapIdentityCreate>,
186    /// The patches to apply, keyed by identity id.
187    pub update: BTreeMap<String, JmapIdentityUpdate>,
188    /// The ids of the objects to destroy.
189    pub destroy: Vec<String>,
190}
191
192impl JmapIdentitySetArgs {
193    /// Queues an object to create under the given client id.
194    pub fn create(
195        &mut self,
196        client_id: impl Into<String>,
197        identity: JmapIdentityCreate,
198    ) -> &mut Self {
199        self.create.insert(client_id.into(), identity);
200        self
201    }
202
203    /// Queues a patch for the identity with the given id.
204    pub fn update(&mut self, id: impl Into<String>, patch: JmapIdentityUpdate) -> &mut Self {
205        self.update.insert(id.into(), patch);
206        self
207    }
208
209    /// Queues the object with the given id for destruction.
210    pub fn destroy(&mut self, id: impl Into<String>) -> &mut Self {
211        self.destroy.push(id.into());
212        self
213    }
214}
215
216/// Successful terminal output of [`JmapIdentitySet`].
217#[derive(Clone, Debug)]
218pub struct JmapIdentitySetOutput {
219    /// The new server state after the call.
220    pub new_state: String,
221    /// The created identities, keyed by client id.
222    pub created: BTreeMap<String, JmapIdentity>,
223    /// The updated identities, keyed by id.
224    pub updated: BTreeMap<String, Option<JmapIdentity>>,
225    /// Ids of the destroyed objects.
226    pub destroyed: Vec<String>,
227    /// The failed creates, keyed by client id.
228    pub not_created: BTreeMap<String, JmapIdentitySetItemError>,
229    /// The failed updates, keyed by id.
230    pub not_updated: BTreeMap<String, JmapIdentitySetItemError>,
231    /// The failed destroys, keyed by id.
232    pub not_destroyed: BTreeMap<String, JmapIdentitySetItemError>,
233    /// Whether the server indicated the connection can be reused.
234    pub keep_alive: bool,
235}
236
237/// I/O-free coroutine for the JMAP `Identity/set` method.
238pub struct JmapIdentitySet {
239    state: State,
240}
241
242impl JmapIdentitySet {
243    /// Prepares the method call request and builds the coroutine.
244    pub fn new(
245        session: &JmapSession,
246        http_auth: &SecretString,
247        args: JmapIdentitySetArgs,
248    ) -> Result<Self, JmapIdentitySetError> {
249        let account_id = session
250            .primary_accounts
251            .get(JMAP_MAIL_CAPABILITY)
252            .cloned()
253            .unwrap_or_default();
254        let api_url = &session.api_url;
255
256        let json_args = serde_json::to_value(IdentitySetRequest {
257            account_id,
258            create: args.create,
259            update: args.update,
260            destroy: args.destroy,
261        })
262        .map_err(JmapIdentitySetError::SerializeArgs)?;
263
264        let mut batch = JmapBatch::new();
265        batch.add("Identity/set", json_args);
266        let request = batch.into_request(vec![
267            JMAP_CORE_CAPABILITY.into(),
268            JMAP_MAIL_CAPABILITY.into(),
269            JMAP_SUBMISSION_CAPABILITY.into(),
270        ]);
271
272        Ok(Self {
273            state: State::Send(JmapSend::new(http_auth, api_url, request)?),
274        })
275    }
276}
277
278impl JmapCoroutine for JmapIdentitySet {
279    type Yield = JmapYield;
280    type Return = Result<JmapIdentitySetOutput, JmapIdentitySetError>;
281
282    fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
283        match &mut self.state {
284            State::Send(send) => {
285                let JmapSendOutput {
286                    response,
287                    keep_alive,
288                } = jmap_try!(send, arg);
289
290                let Some((name, args, _)) = response.method_responses.into_iter().next() else {
291                    return JmapCoroutineState::Complete(Err(
292                        JmapIdentitySetError::MissingResponse,
293                    ));
294                };
295
296                if name == "error" {
297                    let err = serde_json::from_value::<JmapMethodError>(args)
298                        .unwrap_or(JmapMethodError::Unknown);
299                    return JmapCoroutineState::Complete(Err(err.into()));
300                }
301
302                match serde_json::from_value::<IdentitySetResponse>(args) {
303                    Ok(r) => JmapCoroutineState::Complete(Ok(JmapIdentitySetOutput {
304                        new_state: r.new_state.unwrap_or_default(),
305                        created: BTreeMap::new(),
306                        updated: BTreeMap::new(),
307                        destroyed: r.destroyed.unwrap_or_default(),
308                        not_created: r.not_created.unwrap_or_default(),
309                        not_updated: r.not_updated.unwrap_or_default(),
310                        not_destroyed: r.not_destroyed.unwrap_or_default(),
311                        keep_alive,
312                    })),
313                    Err(err) => {
314                        JmapCoroutineState::Complete(Err(JmapIdentitySetError::ParseResponse(err)))
315                    }
316                }
317            }
318        }
319    }
320}
321
322enum State {
323    Send(JmapSend),
324}
325
326#[derive(Serialize)]
327#[serde(rename_all = "camelCase")]
328struct IdentitySetRequest {
329    account_id: String,
330    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
331    create: BTreeMap<String, JmapIdentityCreate>,
332    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
333    update: BTreeMap<String, JmapIdentityUpdate>,
334    #[serde(skip_serializing_if = "Vec::is_empty")]
335    destroy: Vec<String>,
336}
337
338#[derive(Deserialize)]
339#[serde(rename_all = "camelCase")]
340struct IdentitySetResponse {
341    #[serde(default)]
342    new_state: Option<String>,
343    /// Parsed as raw JSON to avoid issues with partial server responses.
344    #[serde(default)]
345    #[allow(dead_code)]
346    created: Option<serde_json::Value>,
347    /// Parsed as raw JSON to avoid issues with partial server responses.
348    #[serde(default)]
349    #[allow(dead_code)]
350    updated: Option<serde_json::Value>,
351    #[serde(default)]
352    destroyed: Option<Vec<String>>,
353    #[serde(default)]
354    not_created: Option<BTreeMap<String, JmapIdentitySetItemError>>,
355    #[serde(default)]
356    not_updated: Option<BTreeMap<String, JmapIdentitySetItemError>>,
357    #[serde(default)]
358    not_destroyed: Option<BTreeMap<String, JmapIdentitySetItemError>>,
359}