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, MsgraphApiError, MsgraphSend, MsgraphSendError, MsgraphSendOutput,
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    ///
71    /// The error holds the headers of the response and no method, the
72    /// request being the caller's; the connection is the batch's own, so
73    /// it reads as reusable.
74    pub fn parse<T: DeserializeOwned>(self) -> Result<T, MsgraphSendError> {
75        let body = self.body.unwrap_or(Value::Null);
76
77        if (200..300).contains(&self.status) {
78            return serde_json::from_value(body).map_err(MsgraphSendError::ParseResponse);
79        }
80
81        let body = serde_json::to_vec(&body).unwrap_or_default();
82        let headers = self.headers.iter();
83        let headers = headers.map(|(name, value)| (name.as_str(), value.as_str()));
84
85        let mut err = MsgraphApiError::parse(self.status, headers, &body);
86        err.keep_alive = true;
87
88        Err(err.into())
89    }
90
91    /// Decodes the body of a 2xx response answered as a JSON string
92    /// holding base64, or turns any other status into
93    /// [`MsgraphSendError::Api`]. A missing body reads as empty.
94    ///
95    /// Line breaks, blanks and missing padding are accepted, any other byte
96    /// outside the alphabet fails with [`MsgraphSendError::ParseResponse`].
97    ///
98    /// Graph encodes that way an inner body that is not JSON, such as
99    /// the MIME message of a `$value` request. The documentation only
100    /// shows JSON bodies, the encoding is community-observed:
101    /// <https://learn.microsoft.com/en-us/graph/json-batching>.
102    pub fn bytes(self) -> Result<Vec<u8>, MsgraphSendError> {
103        let Some(encoded) = self.parse::<Option<String>>()? else {
104            return Ok(Vec::new());
105        };
106
107        let mut decoded = Vec::new();
108
109        if !Base64Codec::default().decode_vec(encoded.as_bytes(), &mut decoded) {
110            let err = serde_json::Error::custom("Graph batch body is not base64");
111            return Err(MsgraphSendError::ParseResponse(err));
112        }
113
114        Ok(decoded)
115    }
116
117    /// Returns the delay of the `Retry-After` header in seconds, `None`
118    /// when absent or given as an HTTP date (RFC 9110 ยง10.2.3).
119    ///
120    /// Graph sends it on a throttled (429) inner response.
121    pub fn retry_after(&self) -> Option<u64> {
122        self.headers
123            .iter()
124            .find(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
125            .and_then(|(_, value)| value.trim().parse().ok())
126    }
127}
128
129/// The batch response body, in no particular order.
130#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
131pub struct MsgraphBatchResponses {
132    /// The responses, one per request.
133    #[serde(default)]
134    pub responses: Vec<MsgraphBatchResponse>,
135}
136
137#[derive(Serialize)]
138struct Body<'a> {
139    requests: &'a [MsgraphBatchRequest],
140}
141
142/// Sends a Microsoft Graph batch.
143pub struct MsgraphBatch {
144    send: MsgraphSend<MsgraphBatchResponses>,
145}
146
147impl MsgraphBatch {
148    /// Sends `requests`, between 1 and [`MSGRAPH_BATCH_MAX_REQUESTS`]
149    /// with unique ids.
150    pub fn new(
151        auth: &HttpAuthBearer,
152        requests: &[MsgraphBatchRequest],
153    ) -> Result<Self, MsgraphSendError> {
154        debug!("prepare microsoft graph batch");
155        trace!("requests: {requests:?}");
156
157        if requests.is_empty() || requests.len() > MSGRAPH_BATCH_MAX_REQUESTS {
158            let err = MsgraphSendError::InvalidRequest(format!(
159                "Batch must hold between 1 and {MSGRAPH_BATCH_MAX_REQUESTS} requests"
160            ));
161            return Err(err);
162        }
163
164        for (i, request) in requests.iter().enumerate() {
165            if requests[..i].iter().any(|prev| prev.id == request.id) {
166                let err = MsgraphSendError::InvalidRequest(format!(
167                    "Batch request id `{}` is not unique",
168                    request.id
169                ));
170                return Err(err);
171            }
172        }
173
174        let url = Url::parse(MSGRAPH_API_BASE)?.join("$batch")?;
175        let send = MsgraphSend::post_json(auth, url, &Body { requests })?;
176
177        Ok(Self { send })
178    }
179}
180
181impl MsgraphCoroutine for MsgraphBatch {
182    type Yield = MsgraphYield;
183    type Return = Result<MsgraphSendOutput<MsgraphBatchResponses>, MsgraphSendError>;
184
185    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
186        let out = msgraph_try!(&mut self.send, arg);
187        debug!("batch sent");
188        trace!("out: {out:?}");
189        MsgraphCoroutineState::Complete(Ok(out))
190    }
191}