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 /// At most this many messages per page
81 /// (`Prefer: odata.maxpagesize`), a header rather than a query
82 /// option.
83 #[serde(skip)]
84 pub max_page_size: Option<u32>,
85}
86
87/// I/O-free coroutine for one messages delta request: the initial
88/// request through [`new`](Self::new), later pages and rounds through
89/// [`from_link`](Self::from_link).
90pub struct MsgraphMessagesDelta {
91 send: MsgraphSend<MsgraphMessagesDeltaResponse>,
92}
93
94impl MsgraphMessagesDelta {
95 /// Starts a delta round over the whole mailbox, or over `folder`
96 /// when given (a folder id or a well-known name such as `inbox`).
97 ///
98 /// `select` trims each row to the named properties (the id always
99 /// rides along).
100 pub fn new(
101 auth: &HttpAuthBearer,
102 user_id: &str,
103 folder: Option<&str>,
104 select: Option<&str>,
105 ) -> Result<Self, MsgraphSendError> {
106 let params = MsgraphMessagesDeltaParams {
107 select,
108 ..Default::default()
109 };
110
111 Self::with_params(auth, user_id, folder, ¶ms)
112 }
113
114 /// Starts a delta round like [`new`](Self::new), with the OData
115 /// options of `params`. Its page size, when set, goes on this first
116 /// request only: chain [`max_page_size`](Self::max_page_size) on
117 /// every [`from_link`](Self::from_link) of the round.
118 pub fn with_params(
119 auth: &HttpAuthBearer,
120 user_id: &str,
121 folder: Option<&str>,
122 params: &MsgraphMessagesDeltaParams,
123 ) -> Result<Self, MsgraphSendError> {
124 debug!("prepare microsoft graph messages delta");
125 trace!("folder: {folder:?}");
126 trace!("params: {params:?}");
127
128 let user = user_path(user_id);
129 let path = match folder {
130 Some(folder) => format!("{user}/mailFolders/{folder}/messages/delta"),
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.
149 pub fn from_link(auth: &HttpAuthBearer, link: &str) -> Result<Self, MsgraphSendError> {
150 debug!("prepare microsoft graph messages delta from link");
151 trace!("link: {link:?}");
152
153 let url = Url::parse(link)?;
154 let send = MsgraphSend::get(auth, url);
155
156 Ok(Self { send })
157 }
158
159 /// Asks Graph for at most `size` items per page
160 /// (`Prefer: odata.maxpagesize={size}`), see
161 /// [`MsgraphSend::max_page_size`]. Graph keeps no memory of it
162 /// across pages: chain it on every page request, the ones built
163 /// from an `@odata.nextLink` included.
164 pub fn max_page_size(mut self, size: u32) -> Self {
165 self.send = self.send.max_page_size(size);
166 self
167 }
168}
169
170impl MsgraphCoroutine for MsgraphMessagesDelta {
171 type Yield = MsgraphYield;
172 type Return = Result<MsgraphSendOutput<MsgraphMessagesDeltaResponse>, MsgraphSendError>;
173
174 fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
175 let out = msgraph_try!(&mut self.send, arg);
176 debug!("messages delta page received");
177 trace!("out: {out:?}");
178 MsgraphCoroutineState::Complete(Ok(out))
179 }
180}