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;
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        page::{MsgraphPage, link_url},
33        query::to_query_pairs,
34        rest::users::{contacts::delta::MsgraphRemoved, messages::MsgraphMessage},
35        send::{
36            MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, path_segment,
37            user_path,
38        },
39    },
40};
41
42/// One page of a messages delta round.
43///
44/// More pages follow through `next_link`; the round ends when
45/// `delta_link` arrives (the token of the next round).
46pub type MsgraphMessagesDeltaResponse = MsgraphPage<MsgraphMessageDelta>;
47
48/// One message row of a delta page: the message (only its id when the
49/// row is a removal), plus the `@removed` marker.
50#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
51pub struct MsgraphMessageDelta {
52    /// The changed message.
53    #[serde(flatten)]
54    pub message: MsgraphMessage,
55    /// The removal marker, present when the row is a removal.
56    #[serde(default, rename = "@removed", skip_serializing_if = "Option::is_none")]
57    pub removed: Option<MsgraphRemoved>,
58}
59
60/// OData options of a messages delta round, sent on its first request
61/// (the links Graph hands back carry them on).
62#[derive(Debug, Clone, Default, Serialize, Eq, PartialEq)]
63pub struct MsgraphMessagesDeltaParams<'a> {
64    /// Comma-separated properties to return (`$select`); the id always
65    /// rides along.
66    #[serde(rename = "$select")]
67    pub select: Option<&'a str>,
68    /// OData filter expression (`$filter`). The delta endpoint only
69    /// takes one on the reception date, such as
70    /// `receivedDateTime ge 2026-01-01T00:00:00Z`.
71    #[serde(rename = "$filter")]
72    pub filter: Option<&'a str>,
73    /// Navigation properties to expand (`$expand`), such as
74    /// `singleValueExtendedProperties($filter=id eq 'Integer 0x0E08')`.
75    #[serde(rename = "$expand")]
76    pub expand: Option<&'a str>,
77    /// At most this many messages per page
78    /// (`Prefer: odata.maxpagesize`), a header rather than a query
79    /// option.
80    #[serde(skip)]
81    pub max_page_size: Option<u32>,
82}
83
84/// I/O-free coroutine for one messages delta request: the initial
85/// request through [`new`](Self::new), later pages and rounds through
86/// [`from_link`](Self::from_link).
87pub struct MsgraphMessagesDelta {
88    send: MsgraphSend<MsgraphMessagesDeltaResponse>,
89}
90
91impl MsgraphMessagesDelta {
92    /// Starts a delta round over the whole mailbox, or over `folder`
93    /// when given (a folder id or a well-known name such as `inbox`).
94    ///
95    /// `select` trims each row to the named properties (the id always
96    /// rides along).
97    pub fn new(
98        auth: &HttpAuthBearer,
99        user_id: &str,
100        folder: Option<&str>,
101        select: Option<&str>,
102    ) -> Result<Self, MsgraphSendError> {
103        let params = MsgraphMessagesDeltaParams {
104            select,
105            ..Default::default()
106        };
107
108        Self::with_params(auth, user_id, folder, &params)
109    }
110
111    /// Starts a delta round like [`new`](Self::new), with the OData
112    /// options of `params`. Its page size, when set, goes on this first
113    /// request only: chain [`max_page_size`](Self::max_page_size) on
114    /// every [`from_link`](Self::from_link) of the round.
115    pub fn with_params(
116        auth: &HttpAuthBearer,
117        user_id: &str,
118        folder: Option<&str>,
119        params: &MsgraphMessagesDeltaParams,
120    ) -> Result<Self, MsgraphSendError> {
121        debug!("prepare microsoft graph messages delta");
122        trace!("folder: {folder:?}");
123        trace!("params: {params:?}");
124
125        let user = user_path(user_id)?;
126        let path = match folder {
127            Some(folder) => format!(
128                "{user}/mailFolders/{}/messages/delta",
129                path_segment(folder)?
130            ),
131            None => format!("{user}/messages/delta"),
132        };
133        let mut url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
134        url.query_pairs_mut().extend_pairs(to_query_pairs(params));
135
136        let mut send = MsgraphSend::get(auth, url);
137        if let Some(size) = params.max_page_size {
138            send = send.max_page_size(size);
139        }
140
141        Ok(Self { send })
142    }
143
144    /// Continues a round from an `@odata.nextLink`, or starts the next
145    /// round from a saved `@odata.deltaLink`.
146    ///
147    /// The link already carries the server-issued token, so it is sent
148    /// as-is through a plain GET. A link off the Microsoft Graph origin
149    /// is refused.
150    pub fn from_link(auth: &HttpAuthBearer, link: &str) -> Result<Self, MsgraphSendError> {
151        debug!("prepare microsoft graph messages delta from link");
152        trace!("link: {link:?}");
153
154        let url = link_url(link)?;
155        let send = MsgraphSend::get(auth, url);
156
157        Ok(Self { send })
158    }
159
160    /// Asks Graph for at most `size` items per page
161    /// (`Prefer: odata.maxpagesize={size}`), see
162    /// [`MsgraphSend::max_page_size`]. Graph keeps no memory of it
163    /// across pages: chain it on every page request, the ones built
164    /// from an `@odata.nextLink` included.
165    pub fn max_page_size(mut self, size: u32) -> Self {
166        self.send = self.send.max_page_size(size);
167        self
168    }
169}
170
171impl MsgraphCoroutine for MsgraphMessagesDelta {
172    type Yield = MsgraphYield;
173    type Return = Result<MsgraphSendOutput<MsgraphMessagesDeltaResponse>, MsgraphSendError>;
174
175    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
176        let out = msgraph_try!(&mut self.send, arg);
177        debug!("messages delta page received");
178        trace!("out: {out:?}");
179        MsgraphCoroutineState::Complete(Ok(out))
180    }
181}