use alloc::{collections::BTreeMap, format, string::String, vec::Vec};
use io_http::rfc6750::bearer::HttpAuthBearer;
use log::{debug, trace};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
use url::Url;
use crate::{
coroutine::*,
msgraph_try,
v1::send::{
MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, parse_api_error,
},
};
pub const MSGRAPH_BATCH_MAX_REQUESTS: usize = 20;
#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MsgraphBatchRequest {
pub id: String,
pub method: String,
pub url: String,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub headers: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub depends_on: Vec<String>,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct MsgraphBatchResponse {
pub id: String,
pub status: u16,
#[serde(default)]
pub headers: BTreeMap<String, String>,
#[serde(default)]
pub body: Option<Value>,
}
impl MsgraphBatchResponse {
pub fn parse<T: DeserializeOwned>(self) -> Result<T, MsgraphSendError> {
let body = self.body.unwrap_or(Value::Null);
if (200..300).contains(&self.status) {
return serde_json::from_value(body).map_err(MsgraphSendError::ParseResponse);
}
let body = serde_json::to_vec(&body).unwrap_or_default();
let (status, code, message) = parse_api_error(self.status, &body);
Err(MsgraphSendError::Api {
status,
code,
message,
})
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct MsgraphBatchResponses {
#[serde(default)]
pub responses: Vec<MsgraphBatchResponse>,
}
#[derive(Serialize)]
struct Body<'a> {
requests: &'a [MsgraphBatchRequest],
}
pub struct MsgraphBatch {
send: MsgraphSend<MsgraphBatchResponses>,
}
impl MsgraphBatch {
pub fn new(
auth: &HttpAuthBearer,
requests: &[MsgraphBatchRequest],
) -> Result<Self, MsgraphSendError> {
debug!("prepare microsoft graph batch");
trace!("requests: {requests:?}");
if requests.is_empty() || requests.len() > MSGRAPH_BATCH_MAX_REQUESTS {
let err = MsgraphSendError::InvalidRequest(format!(
"Batch must hold between 1 and {MSGRAPH_BATCH_MAX_REQUESTS} requests"
));
return Err(err);
}
for (i, request) in requests.iter().enumerate() {
if requests[..i].iter().any(|prev| prev.id == request.id) {
let err = MsgraphSendError::InvalidRequest(format!(
"Batch request id `{}` is not unique",
request.id
));
return Err(err);
}
}
let url = Url::parse(MSGRAPH_API_BASE)?.join("$batch")?;
let send = MsgraphSend::post_json(auth, url, &Body { requests })?;
Ok(Self { send })
}
}
impl MsgraphCoroutine for MsgraphBatch {
type Yield = MsgraphYield;
type Return = Result<MsgraphSendOutput<MsgraphBatchResponses>, MsgraphSendError>;
fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
let out = msgraph_try!(&mut self.send, arg);
debug!("batch sent");
trace!("out: {out:?}");
MsgraphCoroutineState::Complete(Ok(out))
}
}