Skip to main content

io_msgraph/v1/
page.rs

1//! Paged collections: the page every listing and every delta round
2//! answers ([`MsgraphPage`]) and the coroutine following the links it
3//! carries ([`MsgraphPageGet`]).
4//!
5//! <https://learn.microsoft.com/en-us/graph/paging>
6
7use alloc::{format, string::String, vec::Vec};
8
9use io_http::rfc6750::bearer::HttpAuthBearer;
10use log::{debug, trace};
11use serde::{Deserialize, Serialize, de::DeserializeOwned};
12use url::Url;
13
14use crate::{
15    coroutine::*,
16    msgraph_try,
17    v1::send::{MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput},
18};
19
20/// One page of a collection: its items and the OData links to what
21/// follows.
22#[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq)]
23pub struct MsgraphPage<T> {
24    /// The items of the page.
25    #[serde(default = "Vec::new")]
26    pub value: Vec<T>,
27    /// The URL of the next page, when one exists.
28    #[serde(default, rename = "@odata.nextLink")]
29    pub next_link: Option<String>,
30    /// The URL closing a delta round, carrying the token of the next one.
31    #[serde(
32        default,
33        rename = "@odata.deltaLink",
34        skip_serializing_if = "Option::is_none"
35    )]
36    pub delta_link: Option<String>,
37    /// The number of items matching the query, when `$count` asked for
38    /// it.
39    #[serde(
40        default,
41        rename = "@odata.count",
42        skip_serializing_if = "Option::is_none"
43    )]
44    pub count: Option<u64>,
45}
46
47impl<T> Default for MsgraphPage<T> {
48    fn default() -> Self {
49        Self {
50            value: Vec::new(),
51            next_link: None,
52            delta_link: None,
53            count: None,
54        }
55    }
56}
57
58/// Gets the page of `T` an `@odata.nextLink` or an `@odata.deltaLink`
59/// names.
60pub struct MsgraphPageGet<T> {
61    send: MsgraphSend<MsgraphPage<T>>,
62}
63
64impl<T: DeserializeOwned> MsgraphPageGet<T> {
65    /// Gets the page behind `link`, sent as it is: it already carries
66    /// the query and the token Graph issued.
67    ///
68    /// A link off the origin of [`MSGRAPH_API_BASE`] is refused with
69    /// [`MsgraphSendError::InvalidRequest`].
70    pub fn new(auth: &HttpAuthBearer, link: &str) -> Result<Self, MsgraphSendError> {
71        debug!("prepare microsoft graph page retrieval");
72        trace!("link: {link:?}");
73
74        let send = MsgraphSend::get(auth, link_url(link)?);
75
76        Ok(Self { send })
77    }
78
79    /// Asks Graph for at most `size` items per page
80    /// (`Prefer: odata.maxpagesize={size}`), see
81    /// [`MsgraphSend::max_page_size`].
82    pub fn max_page_size(mut self, size: u32) -> Self {
83        self.send = self.send.max_page_size(size);
84        self
85    }
86}
87
88impl<T: DeserializeOwned> MsgraphCoroutine for MsgraphPageGet<T> {
89    type Yield = MsgraphYield;
90    type Return = Result<MsgraphSendOutput<MsgraphPage<T>>, MsgraphSendError>;
91
92    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
93        let out = msgraph_try!(&mut self.send, arg);
94        debug!("page received");
95        trace!("items: {}", out.response.value.len());
96        MsgraphCoroutineState::Complete(Ok(out))
97    }
98}
99
100/// Parses a link Graph issued, refused unless it stays on the origin of
101/// [`MSGRAPH_API_BASE`]: the request it builds carries the bearer token.
102pub(crate) fn link_url(link: &str) -> Result<Url, MsgraphSendError> {
103    let url = Url::parse(link)?;
104    let origin = url.origin();
105
106    if origin != Url::parse(MSGRAPH_API_BASE)?.origin() {
107        let origin = origin.ascii_serialization();
108        let reason = format!("a link to `{origin}` leaves the Microsoft Graph origin");
109        return Err(MsgraphSendError::InvalidRequest(reason));
110    }
111
112    Ok(url)
113}
114
115#[cfg(test)]
116mod tests {
117    use alloc::string::String;
118
119    use crate::v1::page::MsgraphPage;
120
121    #[test]
122    fn a_page_leaves_out_the_links_and_the_count_it_does_not_hold() {
123        let page = MsgraphPage::<String> {
124            value: [String::from("a")].into(),
125            ..Default::default()
126        };
127        assert_eq!(
128            serde_json::to_string(&page).unwrap(),
129            r#"{"value":["a"],"@odata.nextLink":null}"#
130        );
131
132        let read: MsgraphPage<String> =
133            serde_json::from_str(r#"{ "@odata.deltaLink": "d", "@odata.count": 3 }"#).unwrap();
134        assert!(read.value.is_empty());
135        assert_eq!(read.delta_link.as_deref(), Some("d"));
136        assert_eq!(read.count, Some(3));
137    }
138}