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::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 core::fmt;
57
58use alloc::{string::String, vec};
59
60use log::trace;
61use secrecy::SecretString;
62use thiserror::Error;
63
64use crate::{
65    coroutine::*,
66    jmap_try,
67    rfc8620::{CORE_CAPABILITY, JmapSession, changes::*},
68    rfc8621::MAIL_CAPABILITY,
69};
70
71/// Failure causes during a JMAP `Email/changes` flow.
72#[derive(Debug, Error)]
73pub enum JmapEmailChangesError {
74    #[error("JMAP Email/changes failed: {0}")]
75    Changes(#[from] JmapChangesError),
76}
77
78/// Options for [`JmapEmailChanges::new`].
79#[derive(Clone, Debug, Default)]
80pub struct JmapEmailChangesOptions {
81    /// Server-side cap on the number of changes returned.
82    pub max_changes: Option<u64>,
83}
84
85/// I/O-free coroutine for the JMAP `Email/changes` method.
86pub struct JmapEmailChanges {
87    state: State,
88}
89
90impl JmapEmailChanges {
91    pub fn new(
92        session: &JmapSession,
93        http_auth: &SecretString,
94        since_state: impl Into<String>,
95        opts: JmapEmailChangesOptions,
96    ) -> Result<Self, JmapEmailChangesError> {
97        let account_id = session
98            .primary_accounts
99            .get(MAIL_CAPABILITY)
100            .cloned()
101            .unwrap_or_default();
102        let api_url = &session.api_url;
103
104        Ok(Self {
105            state: State::Changes(JmapChanges::new(
106                account_id,
107                http_auth,
108                api_url,
109                "Email/changes",
110                vec![CORE_CAPABILITY.into(), MAIL_CAPABILITY.into()],
111                since_state,
112                JmapChangesOptions {
113                    max_changes: opts.max_changes,
114                },
115            )?),
116        })
117    }
118}
119
120impl JmapCoroutine for JmapEmailChanges {
121    type Yield = JmapYield;
122    type Return = Result<JmapChangesOutput, JmapEmailChangesError>;
123
124    fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
125        trace!("Email/changes: {}", self.state);
126        match &mut self.state {
127            State::Changes(changes) => {
128                let out = jmap_try!(changes, arg);
129                JmapCoroutineState::Complete(Ok(out))
130            }
131        }
132    }
133}
134
135enum State {
136    Changes(JmapChanges),
137}
138
139impl fmt::Display for State {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        match self {
142            Self::Changes(_) => f.write_str("changes"),
143        }
144    }
145}