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, MsgraphApiError, MsgraphSend, MsgraphSendError, MsgraphSendOutput,
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> {
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 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 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#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
131pub struct MsgraphBatchResponses {
132 #[serde(default)]
134 pub responses: Vec<MsgraphBatchResponse>,
135}
136
137#[derive(Serialize)]
138struct Body<'a> {
139 requests: &'a [MsgraphBatchRequest],
140}
141
142pub struct MsgraphBatch {
144 send: MsgraphSend<MsgraphBatchResponses>,
145}
146
147impl MsgraphBatch {
148 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}