Skip to main content

io_msgraph/v1/rest/users/contacts/
delta.rs

1//! Track changes to Microsoft Graph contacts (`GET /me/contacts/delta`
2//! or `GET /me/contactFolders/{id}/contacts/delta`).
3//!
4//! An initial request (no delta link) enumerates every contact and
5//! ends with an `@odata.deltaLink`; feeding that link back through
6//! [`MsgraphSend`] returns only what changed since, removals arriving
7//! as `@removed`-marked rows. An expired link answers HTTP 410; the
8//! consumer falls back to an initial request.
9//!
10//! <https://learn.microsoft.com/en-us/graph/api/contact-delta>
11
12use alloc::{format, string::String};
13
14use io_http::rfc6750::bearer::HttpAuthBearer;
15use log::{debug, trace};
16use serde::{Deserialize, Serialize};
17use url::Url;
18
19use crate::{
20    coroutine::*,
21    msgraph_try,
22    v1::{
23        page::{MsgraphPage, link_url},
24        rest::users::contacts::MsgraphContact,
25        send::{
26            MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, path_segment,
27            user_path,
28        },
29    },
30};
31
32/// One page of a contacts delta round.
33///
34/// More pages follow through `next_link`; the round ends when
35/// `delta_link` arrives (the token of the next round).
36pub type MsgraphContactsDeltaResponse = MsgraphPage<MsgraphContactDelta>;
37
38/// One contact row of a delta page: the contact (only its id when the
39/// row is a removal), plus the `@removed` marker.
40#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
41pub struct MsgraphContactDelta {
42    /// The changed contact.
43    #[serde(flatten)]
44    pub contact: MsgraphContact,
45    /// The removal marker, present when the row is a removal.
46    #[serde(default, rename = "@removed", skip_serializing_if = "Option::is_none")]
47    pub removed: Option<MsgraphRemoved>,
48}
49
50/// The `@removed` marker of a delta row.
51///
52/// <https://learn.microsoft.com/en-us/graph/delta-query-overview>
53#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
54pub struct MsgraphRemoved {
55    /// `deleted` for a hard delete, `changed` for an item that left
56    /// the queried scope.
57    #[serde(default)]
58    pub reason: String,
59}
60
61/// I/O-free coroutine for a contacts delta request, opening a round
62/// with [`new`](Self::new) or continuing one with
63/// [`from_link`](Self::from_link).
64pub struct MsgraphContactsDelta {
65    send: MsgraphSend<MsgraphContactsDeltaResponse>,
66}
67
68impl MsgraphContactsDelta {
69    /// Starts a delta round over the default Contacts folder, or over
70    /// `folder` when given (a contact folder id).
71    ///
72    /// `select` trims each row to the named properties (the id always
73    /// rides along).
74    pub fn new(
75        auth: &HttpAuthBearer,
76        user_id: &str,
77        folder: Option<&str>,
78        select: Option<&str>,
79    ) -> Result<Self, MsgraphSendError> {
80        debug!("prepare microsoft graph contacts delta");
81        trace!("folder: {folder:?}");
82
83        let user = user_path(user_id)?;
84        let path = match folder {
85            Some(folder) => format!(
86                "{user}/contactFolders/{}/contacts/delta",
87                path_segment(folder)?
88            ),
89            None => format!("{user}/contacts/delta"),
90        };
91        let mut url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
92        if let Some(select) = select {
93            url.query_pairs_mut().append_pair("$select", select);
94        }
95
96        let send = MsgraphSend::get(auth, url);
97
98        Ok(Self { send })
99    }
100
101    /// Continues a round from an `@odata.nextLink`, or starts the next
102    /// round from a saved `@odata.deltaLink`.
103    ///
104    /// The link already carries the folder, the `$select` and the
105    /// server-issued token, so it is sent as-is through a plain GET. A
106    /// link off the Microsoft Graph origin is refused.
107    pub fn from_link(auth: &HttpAuthBearer, link: &str) -> Result<Self, MsgraphSendError> {
108        debug!("prepare microsoft graph contacts delta from link");
109        trace!("link: {link:?}");
110
111        let url = link_url(link)?;
112        let send = MsgraphSend::get(auth, url);
113
114        Ok(Self { send })
115    }
116
117    /// Asks Graph for at most `size` items per page
118    /// (`Prefer: odata.maxpagesize={size}`), see
119    /// [`MsgraphSend::max_page_size`]. Graph keeps no memory of it
120    /// across pages: chain it on every page request, the ones built
121    /// from an `@odata.nextLink` included.
122    pub fn max_page_size(mut self, size: u32) -> Self {
123        self.send = self.send.max_page_size(size);
124        self
125    }
126}
127
128impl MsgraphCoroutine for MsgraphContactsDelta {
129    type Yield = MsgraphYield;
130    type Return = Result<MsgraphSendOutput<MsgraphContactsDeltaResponse>, MsgraphSendError>;
131
132    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
133        let out = msgraph_try!(&mut self.send, arg);
134        debug!("contacts delta page received");
135        trace!("out: {out:?}");
136        MsgraphCoroutineState::Complete(Ok(out))
137    }
138}