Skip to main content

io_jmap/rfc9610/address_book/
changes.rs

1//! JMAP `AddressBook/changes` coroutine (RFC 9610 ยง2.2): wraps the generic
2//! [`JmapChanges`] with the JMAP-Contacts 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//!     rfc9610::address_book::changes::{JmapAddressBookChanges, JmapAddressBookChangesOptions},
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:contacts": "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 = JmapAddressBookChanges::new(
36//!     &session,
37//!     &auth,
38//!     "s1",
39//!     JmapAddressBookChangesOptions::default(),
40//! )
41//! .unwrap();
42//! let mut arg = None;
43//!
44//! let out = loop {
45//!     match coroutine.resume(arg.take()) {
46//!         JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
47//!             stream.write_all(&bytes).unwrap();
48//!         }
49//!         JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
50//!             let n = stream.read(&mut buf).unwrap();
51//!             arg = Some(&buf[..n]);
52//!         }
53//!         JmapCoroutineState::Complete(Ok(out)) => break out,
54//!         JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
55//!     }
56//! };
57//!
58//! println!("new state {}", out.new_state);
59//! ```
60
61use alloc::{string::String, vec};
62
63use secrecy::SecretString;
64use thiserror::Error;
65
66use crate::{
67    coroutine::*,
68    jmap_try,
69    rfc8620::{JMAP_CORE_CAPABILITY, changes::*, session::JmapSession},
70    rfc9610::JMAP_CONTACTS_CAPABILITY,
71};
72
73/// Failure causes during a JMAP `AddressBook/changes` flow.
74#[derive(Debug, Error)]
75pub enum JmapAddressBookChangesError {
76    /// The inner generic changes coroutine failed.
77    #[error("JMAP AddressBook/changes failed: {0}")]
78    Changes(#[from] JmapChangesError),
79}
80
81/// Options for [`JmapAddressBookChanges::new`].
82#[derive(Clone, Debug, Default)]
83pub struct JmapAddressBookChangesOptions {
84    /// Server-side cap on the number of changes returned.
85    pub max_changes: Option<u64>,
86}
87
88/// I/O-free coroutine for the JMAP `AddressBook/changes` method.
89pub struct JmapAddressBookChanges {
90    state: State,
91}
92
93impl JmapAddressBookChanges {
94    /// Prepares the method call request and builds the coroutine.
95    pub fn new(
96        session: &JmapSession,
97        http_auth: &SecretString,
98        since_state: impl Into<String>,
99        opts: JmapAddressBookChangesOptions,
100    ) -> Result<Self, JmapAddressBookChangesError> {
101        let account_id = session
102            .primary_accounts
103            .get(JMAP_CONTACTS_CAPABILITY)
104            .cloned()
105            .unwrap_or_default();
106        let api_url = &session.api_url;
107
108        Ok(Self {
109            state: State::Changes(JmapChanges::new(
110                account_id,
111                http_auth,
112                api_url,
113                "AddressBook/changes",
114                vec![JMAP_CORE_CAPABILITY.into(), JMAP_CONTACTS_CAPABILITY.into()],
115                since_state,
116                JmapChangesOptions {
117                    max_changes: opts.max_changes,
118                },
119            )?),
120        })
121    }
122}
123
124impl JmapCoroutine for JmapAddressBookChanges {
125    type Yield = JmapYield;
126    type Return = Result<JmapChangesOutput, JmapAddressBookChangesError>;
127
128    fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
129        match &mut self.state {
130            State::Changes(changes) => {
131                let out = jmap_try!(changes, arg);
132                JmapCoroutineState::Complete(Ok(out))
133            }
134        }
135    }
136}
137
138enum State {
139    Changes(JmapChanges),
140}