Skip to main content

io_msgraph/v1/rest/
batch.rs

1//! Combine several Microsoft Graph requests into one HTTP call (`POST
2//! /$batch`).
3//!
4//! <https://learn.microsoft.com/en-us/graph/json-batching>
5
6use alloc::{collections::BTreeMap, format, string::String, vec::Vec};
7
8use base64_codec::codec::Base64Codec;
9use io_http::rfc6750::bearer::HttpAuthBearer;
10use log::{debug, trace};
11use serde::{
12    Deserialize, Serialize,
13    de::{DeserializeOwned, Error as _},
14};
15use serde_json::Value;
16use url::Url;
17
18use crate::{
19    coroutine::*,
20    msgraph_try,
21    v1::send::{
22        MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, parse_api_error,
23    },
24};
25
26/// Maximum number of requests Graph accepts in one batch.
27pub const MSGRAPH_BATCH_MAX_REQUESTS: usize = 20;
28
29/// One request of a batch.
30#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
31#[serde(rename_all = "camelCase")]
32pub struct MsgraphBatchRequest {
33    /// The id correlating the request with its response, unique within
34    /// the batch.
35    pub id: String,
36    /// The HTTP method.
37    pub method: String,
38    /// The URL relative to the API version, such as
39    /// `/me/mailFolders/inbox`.
40    pub url: String,
41    /// The request headers, `Content-Type` being required with a body.
42    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
43    pub headers: BTreeMap<String, String>,
44    /// The JSON request body.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub body: Option<Value>,
47    /// The ids of the requests this one runs after.
48    #[serde(default, skip_serializing_if = "Vec::is_empty")]
49    pub depends_on: Vec<String>,
50}
51
52/// One response of a batch.
53#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
54pub struct MsgraphBatchResponse {
55    /// The id of the request this response answers.
56    pub id: String,
57    /// The HTTP status of the response.
58    pub status: u16,
59    /// The response headers.
60    #[serde(default)]
61    pub headers: BTreeMap<String, String>,
62    /// The JSON response body, or the error envelope on failure.
63    #[serde(default)]
64    pub body: Option<Value>,
65}
66
67impl MsgraphBatchResponse {
68    /// Parses the body of a 2xx response into `T`, or turns any other
69    /// status into [`MsgraphSendError::Api`].
70    pub fn parse<T: DeserializeOwned>(self) -> Result<T, MsgraphSendError> {
71        let body = self.body.unwrap_or(Value::Null);
72
73        if (200..300).contains(&self.status) {
74            return serde_json::from_value(body).map_err(MsgraphSendError::ParseResponse);
75        }
76
77        let body = serde_json::to_vec(&body).unwrap_or_default();
78        let (status, code, message) = parse_api_error(self.status, &body);
79        Err(MsgraphSendError::Api {
80            status,
81            code,
82            message,
83        })
84    }
85
86    /// Decodes the body of a 2xx response answered as a JSON string
87    /// holding base64, or turns any other status into
88    /// [`MsgraphSendError::Api`]. A missing body reads as empty.
89    ///
90    /// Line breaks, blanks and missing padding are accepted, any other byte
91    /// outside the alphabet fails with [`MsgraphSendError::ParseResponse`].
92    ///
93    /// Graph encodes that way an inner body that is not JSON, such as
94    /// the MIME message of a `$value` request. The documentation only
95    /// shows JSON bodies, the encoding is community-observed:
96    /// <https://learn.microsoft.com/en-us/graph/json-batching>.
97    pub fn bytes(self) -> Result<Vec<u8>, MsgraphSendError> {
98        let Some(encoded) = self.parse::<Option<String>>()? else {
99            return Ok(Vec::new());
100        };
101
102        let mut decoded = Vec::new();
103
104        if !Base64Codec::default().decode_vec(encoded.as_bytes(), &mut decoded) {
105            let err = serde_json::Error::custom("Graph batch body is not base64");
106            return Err(MsgraphSendError::ParseResponse(err));
107        }
108
109        Ok(decoded)
110    }
111
112    /// Returns the delay of the `Retry-After` header in seconds, `None`
113    /// when absent or given as an HTTP date (RFC 9110 ยง10.2.3).
114    ///
115    /// Graph sends it on a throttled (429) inner response.
116    pub fn retry_after(&self) -> Option<u64> {
117        self.headers
118            .iter()
119            .find(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
120            .and_then(|(_, value)| value.trim().parse().ok())
121    }
122}
123
124/// The batch response body, in no particular order.
125#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
126pub struct MsgraphBatchResponses {
127    /// The responses, one per request.
128    #[serde(default)]
129    pub responses: Vec<MsgraphBatchResponse>,
130}
131
132#[derive(Serialize)]
133struct Body<'a> {
134    requests: &'a [MsgraphBatchRequest],
135}
136
137/// Sends a Microsoft Graph batch.
138pub struct MsgraphBatch {
139    send: MsgraphSend<MsgraphBatchResponses>,
140}
141
142impl MsgraphBatch {
143    /// Sends `requests`, between 1 and [`MSGRAPH_BATCH_MAX_REQUESTS`]
144    /// with unique ids.
145    pub fn new(
146        auth: &HttpAuthBearer,
147        requests: &[MsgraphBatchRequest],
148    ) -> Result<Self, MsgraphSendError> {
149        debug!("prepare microsoft graph batch");
150        trace!("requests: {requests:?}");
151
152        if requests.is_empty() || requests.len() > MSGRAPH_BATCH_MAX_REQUESTS {
153            let err = MsgraphSendError::InvalidRequest(format!(
154                "Batch must hold between 1 and {MSGRAPH_BATCH_MAX_REQUESTS} requests"
155            ));
156            return Err(err);
157        }
158
159        for (i, request) in requests.iter().enumerate() {
160            if requests[..i].iter().any(|prev| prev.id == request.id) {
161                let err = MsgraphSendError::InvalidRequest(format!(
162                    "Batch request id `{}` is not unique",
163                    request.id
164                ));
165                return Err(err);
166            }
167        }
168
169        let url = Url::parse(MSGRAPH_API_BASE)?.join("$batch")?;
170        let send = MsgraphSend::post_json(auth, url, &Body { requests })?;
171
172        Ok(Self { send })
173    }
174}
175
176impl MsgraphCoroutine for MsgraphBatch {
177    type Yield = MsgraphYield;
178    type Return = Result<MsgraphSendOutput<MsgraphBatchResponses>, MsgraphSendError>;
179
180    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
181        let out = msgraph_try!(&mut self.send, arg);
182        debug!("batch sent");
183        trace!("out: {out:?}");
184        MsgraphCoroutineState::Complete(Ok(out))
185    }
186}