use alloc::{collections::BTreeMap, format, string::String, vec::Vec};
use base64_codec::codec::Base64Codec;
use io_http::rfc6750::bearer::HttpAuthBearer;
use log::{debug, trace};
use serde::{
Deserialize, Serialize,
de::{DeserializeOwned, Error as _},
};
use serde_json::Value;
use url::Url;
use crate::{
coroutine::*,
msgraph_try,
v1::send::{
MSGRAPH_API_BASE, MsgraphApiError, MsgraphSend, MsgraphSendError, MsgraphSendOutput,
},
};
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 headers = self.headers.iter();
let headers = headers.map(|(name, value)| (name.as_str(), value.as_str()));
let mut err = MsgraphApiError::parse(self.status, headers, &body);
err.keep_alive = true;
Err(err.into())
}
pub fn bytes(self) -> Result<Vec<u8>, MsgraphSendError> {
let Some(encoded) = self.parse::<Option<String>>()? else {
return Ok(Vec::new());
};
let mut decoded = Vec::new();
if !Base64Codec::default().decode_vec(encoded.as_bytes(), &mut decoded) {
let err = serde_json::Error::custom("Graph batch body is not base64");
return Err(MsgraphSendError::ParseResponse(err));
}
Ok(decoded)
}
pub fn retry_after(&self) -> Option<u64> {
self.headers
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
.and_then(|(_, value)| value.trim().parse().ok())
}
}
#[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))
}
}