io_msgraph/v1/rest/
batch.rs1use 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
26pub const MSGRAPH_BATCH_MAX_REQUESTS: usize = 20;
28
29#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
31#[serde(rename_all = "camelCase")]
32pub struct MsgraphBatchRequest {
33 pub id: String,
36 pub method: String,
38 pub url: String,
41 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
43 pub headers: BTreeMap<String, String>,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub body: Option<Value>,
47 #[serde(default, skip_serializing_if = "Vec::is_empty")]
49 pub depends_on: Vec<String>,
50}
51
52#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
54pub struct MsgraphBatchResponse {
55 pub id: String,
57 pub status: u16,
59 #[serde(default)]
61 pub headers: BTreeMap<String, String>,
62 #[serde(default)]
64 pub body: Option<Value>,
65}
66
67impl MsgraphBatchResponse {
68 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 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 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#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
126pub struct MsgraphBatchResponses {
127 #[serde(default)]
129 pub responses: Vec<MsgraphBatchResponse>,
130}
131
132#[derive(Serialize)]
133struct Body<'a> {
134 requests: &'a [MsgraphBatchRequest],
135}
136
137pub struct MsgraphBatch {
139 send: MsgraphSend<MsgraphBatchResponses>,
140}
141
142impl MsgraphBatch {
143 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}