Skip to main content

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

1//! Track changes to Microsoft Graph messages
2//! (`GET /me/messages/delta` or
3//! `GET /me/mailFolders/{id}/messages/delta`).
4//!
5//! An initial request (no delta link) enumerates every message and
6//! ends with an `@odata.deltaLink`; feeding that link back through
7//! [`MsgraphMessagesDelta::from_link`] returns only what changed
8//! since. Changed rows carry the full message, or only the properties
9//! named by `$select`. The delta endpoint takes no `$search`, and a
10//! `$filter` only on the reception date (`receivedDateTime ge
11//! {instant}` or `gt`); see [`MsgraphMessagesDeltaParams`]. Pages
12//! hold 10 messages unless the request prefers more
13//! ([`MsgraphMessagesDelta::max_page_size`]). Removals arrive as
14//! `@removed`-marked rows carrying a reason. A round is over when
15//! `@odata.deltaLink` replaces `@odata.nextLink` in the page. An
16//! expired link answers HTTP 410; the consumer falls back to an
17//! initial request.
18//!
19//! <https://learn.microsoft.com/en-us/graph/api/message-delta>
20
21use alloc::{format, string::String, vec::Vec};
22
23use io_http::rfc6750::bearer::HttpAuthBearer;
24use log::{debug, trace};
25use serde::{Deserialize, Serialize};
26use url::Url;
27
28use crate::{
29    coroutine::*,
30    msgraph_try,
31    v1::{
32        query::to_query_pairs,
33        rest::users::{contacts::delta::MsgraphRemoved, messages::MsgraphMessage},
34        send::{MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, user_path},
35    },
36};
37
38/// One page of a messages delta round.
39///
40/// More pages follow through `next_link`; the round ends when
41/// `delta_link` arrives (the token of the next round).
42#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
43pub struct MsgraphMessagesDeltaResponse {
44    /// The changed messages of the page.
45    #[serde(default)]
46    pub value: Vec<MsgraphMessageDelta>,
47    /// The URL of the next page of the round, when one exists.
48    #[serde(default, rename = "@odata.nextLink")]
49    pub next_link: Option<String>,
50    /// The URL closing the round, carrying the next round's token.
51    #[serde(default, rename = "@odata.deltaLink")]
52    pub delta_link: Option<String>,
53}
54
55/// One message row of a delta page: the message (only its id when the
56/// row is a removal), plus the `@removed` marker.
57#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
58pub struct MsgraphMessageDelta {
59    /// The changed message.
60    #[serde(flatten)]
61    pub message: MsgraphMessage,
62    /// The removal marker, present when the row is a removal.
63    #[serde(default, rename = "@removed", skip_serializing_if = "Option::is_none")]
64    pub removed: Option<MsgraphRemoved>,
65}
66
67/// OData options of a messages delta round, sent on its first request
68/// (the links Graph hands back carry them on).
69#[derive(Debug, Clone, Default, Serialize, Eq, PartialEq)]
70pub struct MsgraphMessagesDeltaParams<'a> {
71    /// Comma-separated properties to return (`$select`); the id always
72    /// rides along.
73    #[serde(rename = "$select")]
74    pub select: Option<&'a str>,
75    /// OData filter expression (`$filter`). The delta endpoint only
76    /// takes one on the reception date, such as
77    /// `receivedDateTime ge 2026-01-01T00:00:00Z`.
78    #[serde(rename = "$filter")]
79    pub filter: Option<&'a str>,
80    /// Navigation properties to expand (`$expand`), such as
81    /// `singleValueExtendedProperties($filter=id eq 'Integer 0x0E08')`.
82    #[serde(rename = "$expand")]
83    pub expand: Option<&'a str>,
84    /// At most this many messages per page
85    /// (`Prefer: odata.maxpagesize`), a header rather than a query
86    /// option.
87    #[serde(skip)]
88    pub max_page_size: Option<u32>,
89}
90
91/// I/O-free coroutine for one messages delta request: the initial
92/// request through [`new`](Self::new), later pages and rounds through
93/// [`from_link`](Self::from_link).
94pub struct MsgraphMessagesDelta {
95    send: MsgraphSend<MsgraphMessagesDeltaResponse>,
96}
97
98impl MsgraphMessagesDelta {
99    /// Starts a delta round over the whole mailbox, or over `folder`
100    /// when given (a folder id or a well-known name such as `inbox`).
101    ///
102    /// `select` trims each row to the named properties (the id always
103    /// rides along).
104    pub fn new(
105        auth: &HttpAuthBearer,
106        user_id: &str,
107        folder: Option<&str>,
108        select: Option<&str>,
109    ) -> Result<Self, MsgraphSendError> {
110        let params = MsgraphMessagesDeltaParams {
111            select,
112            ..Default::default()
113        };
114
115        Self::with_params(auth, user_id, folder, &params)
116    }
117
118    /// Starts a delta round like [`new`](Self::new), with the OData
119    /// options of `params`. Its page size, when set, goes on this first
120    /// request only: chain [`max_page_size`](Self::max_page_size) on
121    /// every [`from_link`](Self::from_link) of the round.
122    pub fn with_params(
123        auth: &HttpAuthBearer,
124        user_id: &str,
125        folder: Option<&str>,
126        params: &MsgraphMessagesDeltaParams,
127    ) -> Result<Self, MsgraphSendError> {
128        debug!("prepare microsoft graph messages delta");
129        trace!("folder: {folder:?}");
130        trace!("params: {params:?}");
131
132        let user = user_path(user_id);
133        let path = match folder {
134            Some(folder) => format!("{user}/mailFolders/{folder}/messages/delta"),
135            None => format!("{user}/messages/delta"),
136        };
137        let mut url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
138        url.query_pairs_mut().extend_pairs(to_query_pairs(params));
139
140        let mut send = MsgraphSend::get(auth, url);
141        if let Some(size) = params.max_page_size {
142            send = send.max_page_size(size);
143        }
144
145        Ok(Self { send })
146    }
147
148    /// Continues a round from an `@odata.nextLink`, or starts the next
149    /// round from a saved `@odata.deltaLink`.
150    ///
151    /// The link already carries the server-issued token, so it is sent
152    /// as-is through a plain GET.
153    pub fn from_link(auth: &HttpAuthBearer, link: &str) -> Result<Self, MsgraphSendError> {
154        debug!("prepare microsoft graph messages delta from link");
155        trace!("link: {link:?}");
156
157        let url = Url::parse(link)?;
158        let send = MsgraphSend::get(auth, url);
159
160        Ok(Self { send })
161    }
162
163    /// Asks Graph for at most `size` items per page
164    /// (`Prefer: odata.maxpagesize={size}`), see
165    /// [`MsgraphSend::max_page_size`]. Graph keeps no memory of it
166    /// across pages: chain it on every page request, the ones built
167    /// from an `@odata.nextLink` included.
168    pub fn max_page_size(mut self, size: u32) -> Self {
169        self.send = self.send.max_page_size(size);
170        self
171    }
172}
173
174impl MsgraphCoroutine for MsgraphMessagesDelta {
175    type Yield = MsgraphYield;
176    type Return = Result<MsgraphSendOutput<MsgraphMessagesDeltaResponse>, MsgraphSendError>;
177
178    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
179        let out = msgraph_try!(&mut self.send, arg);
180        debug!("messages delta page received");
181        trace!("out: {out:?}");
182        MsgraphCoroutineState::Complete(Ok(out))
183    }
184}