Skip to main content

io_jmap/rfc8621/email/
changes.rs

1//! JMAP `Email/changes` coroutine (RFC 8621 ยง4.3): wraps the generic
2//! [`JmapChanges`] with the JMAP-Mail capability set.
3//!
4//! # Example
5//!
6//! ```rust,no_run
7//! use std::{
8//!     io::{Read, Write},
9//!     net::TcpStream,
10//! };
11//!
12//! use io_jmap::{
13//!     coroutine::{JmapCoroutine, JmapCoroutineState, JmapYield},
14//!     rfc8620::session::JmapSession,
15//!     rfc8621::email::changes::{JmapEmailChanges, JmapEmailChangesOptions},
16//! };
17//! use secrecy::SecretString;
18//!
19//! // Ready stream needed (TCP-connected, TLS-negociated)
20//! let mut stream = TcpStream::connect("api.example.com:443").unwrap();
21//! let mut buf = [0u8; 4096];
22//!
23//! let session: JmapSession = serde_json::from_str(r#"{
24//!     "username": "",
25//!     "accounts": {},
26//!     "primaryAccounts": {"urn:ietf:params:jmap:mail": "a1"},
27//!     "capabilities": {},
28//!     "apiUrl": "https://api.example.com/jmap/",
29//!     "downloadUrl": "",
30//!     "uploadUrl": "",
31//!     "eventSourceUrl": "",
32//!     "state": ""
33//! }"#).unwrap();
34//! let auth = SecretString::from("Bearer xyz");
35//! let mut coroutine =
36//!     JmapEmailChanges::new(&session, &auth, "s1", JmapEmailChangesOptions::default()).unwrap();
37//! let mut arg = None;
38//!
39//! let out = loop {
40//!     match coroutine.resume(arg.take()) {
41//!         JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
42//!             stream.write_all(&bytes).unwrap();
43//!         }
44//!         JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
45//!             let n = stream.read(&mut buf).unwrap();
46//!             arg = Some(&buf[..n]);
47//!         }
48//!         JmapCoroutineState::Complete(Ok(out)) => break out,
49//!         JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
50//!     }
51//! };
52//!
53//! println!("new state {}", out.new_state);
54//! ```
55
56use alloc::{string::String, vec};
57
58use secrecy::SecretString;
59use thiserror::Error;
60
61use crate::{
62    coroutine::*,
63    jmap_try,
64    rfc8620::{JMAP_CORE_CAPABILITY, changes::*, session::JmapSession},
65    rfc8621::JMAP_MAIL_CAPABILITY,
66};
67
68/// Failure causes during a JMAP `Email/changes` flow.
69#[derive(Debug, Error)]
70pub enum JmapEmailChangesError {
71    /// The inner generic changes coroutine failed.
72    #[error("JMAP Email/changes failed: {0}")]
73    Changes(#[from] JmapChangesError),
74}
75
76/// Options for [`JmapEmailChanges::new`].
77#[derive(Clone, Debug, Default)]
78pub struct JmapEmailChangesOptions {
79    /// Server-side cap on the number of changes returned.
80    pub max_changes: Option<u64>,
81}
82
83/// I/O-free coroutine for the JMAP `Email/changes` method.
84pub struct JmapEmailChanges {
85    state: State,
86}
87
88impl JmapEmailChanges {
89    /// Prepares the method call request and builds the coroutine.
90    pub fn new(
91        session: &JmapSession,
92        http_auth: &SecretString,
93        since_state: impl Into<String>,
94        opts: JmapEmailChangesOptions,
95    ) -> Result<Self, JmapEmailChangesError> {
96        let account_id = session
97            .primary_accounts
98            .get(JMAP_MAIL_CAPABILITY)
99            .cloned()
100            .unwrap_or_default();
101        let api_url = &session.api_url;
102
103        Ok(Self {
104            state: State::Changes(JmapChanges::new(
105                account_id,
106                http_auth,
107                api_url,
108                "Email/changes",
109                vec![JMAP_CORE_CAPABILITY.into(), JMAP_MAIL_CAPABILITY.into()],
110                since_state,
111                JmapChangesOptions {
112                    max_changes: opts.max_changes,
113                },
114            )?),
115        })
116    }
117}
118
119impl JmapCoroutine for JmapEmailChanges {
120    type Yield = JmapYield;
121    type Return = Result<JmapChangesOutput, JmapEmailChangesError>;
122
123    fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
124        match &mut self.state {
125            State::Changes(changes) => {
126                let out = jmap_try!(changes, arg);
127                JmapCoroutineState::Complete(Ok(out))
128            }
129        }
130    }
131}
132
133enum State {
134    Changes(JmapChanges),
135}