1use core::{error::Error, fmt, marker::PhantomData, time::Duration};
9
10use alloc::{
11 boxed::Box,
12 format,
13 string::{String, ToString},
14 vec::Vec,
15};
16
17use io_http::{
18 coroutine::{HttpCoroutine, HttpCoroutineState},
19 rfc3986::path::{HttpUrlBuildError, http_url_build},
20 rfc6750::bearer::HttpAuthBearer,
21 rfc9110::{
22 request::HttpRequest,
23 response::HttpResponse,
24 send::{HttpSendOutput, HttpSendYield},
25 },
26 rfc9112::send::{Http11Send, Http11SendError},
27};
28use log::{debug, trace};
29use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
30use url::Url;
31
32use crate::coroutine::{MsgraphCoroutine, MsgraphCoroutineState, MsgraphYield};
33
34pub const MSGRAPH_API_BASE: &str = "https://graph.microsoft.com/v1.0/";
36
37pub fn user_path(user_id: &str) -> Result<String, MsgraphSendError> {
44 if user_id == "me" {
45 return Ok(String::from("me"));
46 }
47
48 Ok(format!("users/{}", path_segment(user_id)?))
49}
50
51pub fn path_segment(raw: &str) -> Result<String, MsgraphSendError> {
59 let url = match http_url_build(MSGRAPH_API_BASE, [raw]) {
60 Ok(url) => url,
61 Err(HttpUrlBuildError::InvalidBaseUrl(err, _)) => return Err(err.into()),
62 Err(HttpUrlBuildError::InvalidSegment(_)) => {
63 let reason = format!("{raw:?} is not a valid path segment");
64 return Err(MsgraphSendError::InvalidRequest(reason));
65 }
66 };
67
68 let (_, segment) = url.path().rsplit_once('/').unwrap_or_default();
69
70 Ok(segment.into())
71}
72
73#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
76pub struct MsgraphNoResponse;
77
78impl<'de> Deserialize<'de> for MsgraphNoResponse {
79 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
80 where
81 D: Deserializer<'de>,
82 {
83 let _ = serde::de::IgnoredAny::deserialize(deserializer)?;
84 Ok(Self)
85 }
86}
87
88#[derive(Debug)]
90pub enum MsgraphSendError {
91 Send(Http11SendError),
93 SerializeRequest(serde_json::Error),
95 ParseResponse(serde_json::Error),
97 ParseUrl(url::ParseError),
99 InvalidRequest(String),
101 Api(Box<MsgraphApiError>),
103 UnexpectedRedirect,
105}
106
107impl fmt::Display for MsgraphSendError {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 match self {
110 Self::Send(err) => write!(f, "Microsoft Graph HTTP request failed: {err}"),
111 Self::SerializeRequest(err) => {
112 write!(f, "Microsoft Graph request serialization failed: {err}")
113 }
114 Self::ParseResponse(err) => write!(f, "Microsoft Graph response parsing failed: {err}"),
115 Self::ParseUrl(err) => write!(f, "Microsoft Graph URL parsing failed: {err}"),
116 Self::InvalidRequest(reason) => write!(f, "Invalid Microsoft Graph request: {reason}"),
117 Self::Api(err) => err.fmt(f),
118 Self::UnexpectedRedirect => {
119 write!(f, "Microsoft Graph server returned an unexpected redirect")
120 }
121 }
122 }
123}
124
125impl Error for MsgraphSendError {
126 fn source(&self) -> Option<&(dyn Error + 'static)> {
127 match self {
128 Self::Send(err) => Some(err),
129 Self::SerializeRequest(err) | Self::ParseResponse(err) => Some(err),
130 Self::ParseUrl(err) => Some(err),
131 _ => None,
132 }
133 }
134}
135
136impl From<Http11SendError> for MsgraphSendError {
137 fn from(err: Http11SendError) -> Self {
138 match err {
139 Http11SendError::InvalidRequest(err) => Self::InvalidRequest(err.to_string()),
140 err => Self::Send(err),
141 }
142 }
143}
144
145impl From<MsgraphApiError> for MsgraphSendError {
146 fn from(err: MsgraphApiError) -> Self {
147 Self::Api(Box::new(err))
148 }
149}
150
151impl From<url::ParseError> for MsgraphSendError {
152 fn from(err: url::ParseError) -> Self {
153 Self::ParseUrl(err)
154 }
155}
156
157impl MsgraphSendError {
158 pub fn api(&self) -> Option<&MsgraphApiError> {
161 match self {
162 Self::Api(err) => Some(err.as_ref()),
163 _ => None,
164 }
165 }
166
167 pub fn status(&self) -> Option<u16> {
170 self.api().map(|err| err.status)
171 }
172
173 pub fn retry_after(&self) -> Option<Duration> {
176 self.api().and_then(|err| err.retry_after)
177 }
178
179 pub fn is_throttled(&self) -> bool {
182 self.api().is_some_and(MsgraphApiError::is_throttled)
183 }
184
185 pub fn is_retryable(&self) -> bool {
188 self.api().is_some_and(MsgraphApiError::is_retryable)
189 }
190}
191
192#[derive(Debug, Clone, Default, Eq, PartialEq)]
195pub struct MsgraphApiError {
196 pub status: u16,
198 pub code: String,
200 pub message: String,
202 pub method: String,
204 pub retry_after: Option<Duration>,
207 pub www_authenticate: Option<String>,
210 pub request_id: Option<String>,
213 pub keep_alive: bool,
215}
216
217impl MsgraphApiError {
218 pub fn parse<'a>(
224 status: u16,
225 headers: impl IntoIterator<Item = (&'a str, &'a str)>,
226 body: &[u8],
227 ) -> Self {
228 let envelope = serde_json::from_slice::<ErrorEnvelope>(body).ok();
229 let (status, code, message) = parse_api_error(status, body);
230
231 let mut err = Self {
232 status,
233 code,
234 message,
235 request_id: envelope
236 .and_then(|envelope| envelope.error.inner_error)
237 .and_then(|inner| inner.request_id),
238 ..Default::default()
239 };
240
241 for (name, value) in headers {
242 let value = value.trim();
243
244 if name.eq_ignore_ascii_case("retry-after") {
245 err.retry_after = value.parse().ok().map(Duration::from_secs);
246 } else if name.eq_ignore_ascii_case("www-authenticate") {
247 err.www_authenticate = Some(value.into());
248 } else if name.eq_ignore_ascii_case("request-id") {
249 err.request_id = Some(value.into());
250 }
251 }
252
253 err
254 }
255
256 pub(crate) fn of(method: &str, response: &HttpResponse, keep_alive: bool) -> Self {
258 let headers = response.headers.iter();
259 let headers = headers.map(|(name, value)| (name.as_str(), value.as_str()));
260
261 let mut err = Self::parse(*response.status, headers, &response.body);
262 err.method = method.into();
263 err.keep_alive = keep_alive;
264
265 err
266 }
267
268 pub fn is_throttled(&self) -> bool {
272 self.status == 429
273 }
274
275 pub fn is_retryable(&self) -> bool {
281 let transient = matches!(self.status, 500 | 502 | 503 | 504);
282 let idempotent = matches!(self.method.as_str(), "GET" | "HEAD" | "PUT" | "DELETE");
283
284 self.is_throttled() || (transient && idempotent)
285 }
286}
287
288impl fmt::Display for MsgraphApiError {
289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290 let Self {
291 status,
292 code,
293 message,
294 ..
295 } = self;
296
297 write!(
298 f,
299 "Microsoft Graph API returned HTTP {status} ({code}): {message}"
300 )
301 }
302}
303
304impl Error for MsgraphApiError {}
305
306#[derive(Clone, Debug)]
309pub struct MsgraphSendOutput<T> {
310 pub response: T,
312 pub headers: Vec<(String, String)>,
314 pub keep_alive: bool,
316}
317
318pub struct MsgraphSend<T> {
321 state: State,
322 method: String,
323 _phantom: PhantomData<T>,
324}
325
326impl<T: DeserializeOwned> MsgraphSend<T> {
327 pub fn get(auth: &HttpAuthBearer, url: Url) -> Self {
329 Self::with_method(auth, "GET", url, None, Vec::new())
330 }
331
332 pub fn delete(auth: &HttpAuthBearer, url: Url) -> Self {
334 Self::with_method(auth, "DELETE", url, None, Vec::new())
335 }
336
337 pub fn post_json<B: Serialize>(
339 auth: &HttpAuthBearer,
340 url: Url,
341 body: &B,
342 ) -> Result<Self, MsgraphSendError> {
343 let body = serde_json::to_vec(body).map_err(MsgraphSendError::SerializeRequest)?;
344 Ok(Self::with_method(
345 auth,
346 "POST",
347 url,
348 Some("application/json"),
349 body,
350 ))
351 }
352
353 pub fn patch_json<B: Serialize>(
355 auth: &HttpAuthBearer,
356 url: Url,
357 body: &B,
358 ) -> Result<Self, MsgraphSendError> {
359 let body = serde_json::to_vec(body).map_err(MsgraphSendError::SerializeRequest)?;
360 Ok(Self::with_method(
361 auth,
362 "PATCH",
363 url,
364 Some("application/json"),
365 body,
366 ))
367 }
368
369 pub fn post_text(auth: &HttpAuthBearer, url: Url, body: Vec<u8>) -> Self {
371 Self::with_method(auth, "POST", url, Some("text/plain"), body)
372 }
373
374 pub fn with_method(
376 auth: &HttpAuthBearer,
377 method: &str,
378 url: Url,
379 content_type: Option<&str>,
380 body: Vec<u8>,
381 ) -> Self {
382 let mut request = HttpRequest::get(url.clone())
383 .header("Accept", "application/json")
384 .header("Authorization", auth.to_authorization())
385 .body(body);
386
387 if let Some(content_type) = content_type {
388 request = request.header("Content-Type", content_type);
389 }
390
391 request.method = method.into();
392
393 debug!("prepare request to send");
394 trace!("method: {method}");
395 trace!("url: {url}");
396
397 Self {
398 state: State::Prepare(request),
399 method: method.into(),
400 _phantom: PhantomData,
401 }
402 }
403
404 pub fn header(mut self, name: impl ToString, value: impl ToString) -> Self {
410 if let State::Prepare(request) = &mut self.state {
411 request.headers.push((name.to_string(), value.to_string()));
412 }
413 self
414 }
415
416 pub fn max_page_size(self, size: u32) -> Self {
423 self.header("Prefer", format!("odata.maxpagesize={size}"))
424 }
425}
426
427impl<T: DeserializeOwned> MsgraphCoroutine for MsgraphSend<T> {
428 type Yield = MsgraphYield;
429 type Return = Result<MsgraphSendOutput<T>, MsgraphSendError>;
430
431 fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
432 if let State::Prepare(request) = &mut self.state {
433 let url = request.url.clone();
434 let request = core::mem::replace(request, HttpRequest::get(url));
435 self.state = State::Send(Http11Send::new(request));
436 }
437
438 match &mut self.state {
439 State::Prepare(_) => unreachable!("the request is sent on the first resume"),
440 State::Send(send) => match send.resume(arg) {
441 HttpCoroutineState::Yielded(HttpSendYield::WantsRead) => {
442 MsgraphCoroutineState::Yielded(MsgraphYield::WantsRead)
443 }
444 HttpCoroutineState::Yielded(HttpSendYield::WantsWrite(bytes)) => {
445 MsgraphCoroutineState::Yielded(MsgraphYield::WantsWrite(bytes))
446 }
447 HttpCoroutineState::Yielded(HttpSendYield::WantsRedirect { .. }) => {
448 MsgraphCoroutineState::Complete(Err(MsgraphSendError::UnexpectedRedirect))
449 }
450 HttpCoroutineState::Complete(Err(err)) => {
451 MsgraphCoroutineState::Complete(Err(err.into()))
452 }
453 HttpCoroutineState::Complete(Ok(HttpSendOutput {
454 response,
455 keep_alive,
456 ..
457 })) => {
458 if response.status.is_success() {
459 let body = if response.body.is_empty() {
460 b"null".as_slice()
461 } else {
462 response.body.as_slice()
463 };
464
465 match serde_json::from_slice::<T>(body) {
466 Ok(parsed) => MsgraphCoroutineState::Complete(Ok(MsgraphSendOutput {
467 response: parsed,
468 headers: response.headers,
469 keep_alive,
470 })),
471 Err(err) => MsgraphCoroutineState::Complete(Err(
472 MsgraphSendError::ParseResponse(err),
473 )),
474 }
475 } else {
476 let err = MsgraphApiError::of(&self.method, &response, keep_alive);
477 MsgraphCoroutineState::Complete(Err(err.into()))
478 }
479 }
480 },
481 }
482 }
483}
484
485enum State {
486 Prepare(HttpRequest),
488 Send(Http11Send),
489}
490
491#[derive(Debug, Deserialize)]
492struct ErrorEnvelope {
493 error: ErrorBody,
494}
495
496#[derive(Debug, Deserialize)]
497struct ErrorBody {
498 code: Option<String>,
499 message: Option<String>,
500 #[serde(rename = "innerError", alias = "innererror")]
501 inner_error: Option<InnerError>,
502}
503
504#[derive(Debug, Deserialize)]
505struct InnerError {
506 #[serde(rename = "request-id")]
507 request_id: Option<String>,
508}
509
510pub fn parse_api_error(http_status: u16, body: &[u8]) -> (u16, String, String) {
517 if let Ok(envelope) = serde_json::from_slice::<ErrorEnvelope>(body) {
518 let code = envelope
519 .error
520 .code
521 .filter(|code| !code.trim().is_empty())
522 .unwrap_or_else(|| String::from("unknown"));
523 let message = envelope
524 .error
525 .message
526 .filter(|message| !message.trim().is_empty())
527 .unwrap_or_else(|| String::from("unknown Microsoft Graph API error"));
528 return (http_status, code, message);
529 }
530
531 let message = String::from_utf8_lossy(body).trim().to_string();
532
533 if message.is_empty() {
534 (
535 http_status,
536 String::from("unknown"),
537 String::from("unknown Microsoft Graph API error"),
538 )
539 } else {
540 (http_status, String::from("unknown"), message)
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use crate::v1::send::{MsgraphSendError, path_segment, user_path};
547
548 #[test]
549 fn a_path_segment_keeps_a_graph_id_and_encodes_separators() {
550 let id = "AAMkAGI2T-_x=";
551 assert_eq!(path_segment(id).unwrap(), id);
552 assert_eq!(path_segment("A/B?c#d e%").unwrap(), "A%2FB%3Fc%23d%20e%25");
553 assert_eq!(path_segment("Envoyés").unwrap(), "Envoy%C3%A9s");
554 assert_eq!(
555 user_path("a b@example.org").unwrap(),
556 "users/a%20b@example.org"
557 );
558 assert_eq!(user_path("me").unwrap(), "me");
559 }
560
561 #[test]
562 fn a_path_segment_refuses_what_url_resolution_drops() {
563 for raw in ["", ".", "..", ".\t.", "a\nb"] {
564 let err = path_segment(raw).unwrap_err();
565 assert!(matches!(err, MsgraphSendError::InvalidRequest(_)));
566
567 let err = user_path(raw).unwrap_err();
568 assert!(matches!(err, MsgraphSendError::InvalidRequest(_)));
569 }
570 }
571}