1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use crate::blocking::BlockingRequestHandler;
use crate::internal::{
    BodyRead, Client, GraphClientConfiguration, HttpResponseBuilderExt, ODataNextLink, ODataQuery,
    RequestComponents,
};
use async_stream::try_stream;
use futures::Stream;
use graph_error::{ErrorMessage, GraphFailure, GraphResult};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_TYPE};
use serde::de::DeserializeOwned;
use std::collections::VecDeque;
use std::fmt::Debug;
use std::time::Duration;
use url::Url;

#[derive(Default)]
pub struct RequestHandler {
    pub(crate) inner: reqwest::Client,
    pub(crate) access_token: String,
    pub(crate) request_components: RequestComponents,
    pub(crate) error: Option<GraphFailure>,
    pub(crate) body: Option<BodyRead>,
    pub(crate) client_builder: GraphClientConfiguration,
}

impl RequestHandler {
    pub fn new(
        inner: Client,
        mut request_components: RequestComponents,
        err: Option<GraphFailure>,
        body: Option<BodyRead>,
    ) -> RequestHandler {
        let mut original_headers = inner.headers;
        original_headers.extend(request_components.headers.clone());
        request_components.headers = original_headers;

        let mut error = None;
        if let Some(err) = err {
            error = Some(GraphFailure::PreFlightError {
                url: Some(request_components.url.clone()),
                headers: request_components.headers.clone(),
                error: Box::new(err),
            });
        }

        RequestHandler {
            inner: inner.inner.clone(),
            access_token: inner.access_token,
            request_components,
            error,
            body,
            client_builder: inner.builder,
        }
    }

    pub fn into_blocking(self) -> BlockingRequestHandler {
        BlockingRequestHandler::new(
            self.client_builder
                .access_token(self.access_token)
                .build_blocking(),
            self.request_components,
            self.error,
            self.body,
        )
    }

    /// Returns true if any errors occurred prior to sending the request.
    ///
    /// # Example
    /// ```rust,ignore
    /// let client = Graph::new("ACCESS_TOKEN");
    /// let request_handler = client.groups().list_group();
    /// println!("{:#?}", request_handler.is_err());
    /// ```
    pub fn is_err(&self) -> bool {
        self.error.is_some()
    }

    /// Returns any error wrapped in an Option that occurred prior to sending a request
    ///
    /// # Example
    /// ```rust,ignore
    /// let client = Graph::new("ACCESS_TOKEN");
    /// let request_handler = client.groups().list_group();
    /// println!("{:#?}", request_handler.err());
    /// ```
    pub fn err(&self) -> Option<&GraphFailure> {
        self.error.as_ref()
    }

    #[inline]
    pub fn url(&self) -> Url {
        self.request_components.url.clone()
    }

    #[inline]
    pub fn query<T: serde::Serialize + ?Sized>(mut self, query: &T) -> Self {
        if let Err(err) = self.request_components.query(query) {
            if self.error.is_none() {
                self.error = Some(err);
            }
        }

        if let Some("") = self.request_components.url.query() {
            self.request_components.url.set_query(None);
        }
        self
    }

    #[inline]
    pub fn append_query_pair<KV: AsRef<str>>(mut self, key: KV, value: KV) -> Self {
        self.request_components
            .url
            .query_pairs_mut()
            .append_pair(key.as_ref(), value.as_ref());
        self
    }

    #[inline]
    pub fn extend_path<I: AsRef<str>>(mut self, path: &[I]) -> Self {
        if let Ok(mut p) = self.request_components.url.path_segments_mut() {
            p.extend(path);
        }
        self
    }

    /// Insert a header for the request.
    #[inline]
    pub fn header<K: Into<HeaderName>, V: Into<HeaderValue>>(
        mut self,
        header_name: K,
        header_value: V,
    ) -> Self {
        self.request_components
            .headers
            .insert(header_name.into(), header_value.into());
        self
    }

    /// Set the headers for the request using reqwest::HeaderMap
    #[inline]
    pub fn headers(mut self, header_map: HeaderMap) -> Self {
        self.request_components.headers.extend(header_map);
        self
    }

    /// Get a mutable reference to the headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        self.request_components.as_mut()
    }

    pub fn paging(self) -> Paging {
        Paging(self)
    }

    pub(crate) fn default_request_builder(&mut self) -> reqwest::RequestBuilder {
        let request_builder = self
            .inner
            .request(
                self.request_components.method.clone(),
                self.request_components.url.clone(),
            )
            .bearer_auth(self.access_token.as_str())
            .headers(self.request_components.headers.clone());

        if let Some(body) = self.body.take() {
            self.request_components
                .headers
                .entry(CONTENT_TYPE)
                .or_insert(HeaderValue::from_static("application/json"));
            return request_builder
                .body::<reqwest::Body>(body.into())
                .headers(self.request_components.headers.clone());
        }
        request_builder
    }

    /// Builds the request and returns a [`reqwest::RequestBuilder`].
    #[inline]
    pub fn build(mut self) -> GraphResult<reqwest::RequestBuilder> {
        if let Some(err) = self.error {
            return Err(err);
        }
        Ok(self.default_request_builder())
    }

    #[inline]
    pub async fn send(self) -> GraphResult<reqwest::Response> {
        let request_builder = self.build()?;
        request_builder.send().await.map_err(GraphFailure::from)
    }
}

impl ODataQuery for RequestHandler {
    fn append_query_pair<KV: AsRef<str>>(self, key: KV, value: KV) -> Self {
        self.append_query_pair(key.as_ref(), value.as_ref())
    }
}

impl AsRef<Url> for RequestHandler {
    fn as_ref(&self) -> &Url {
        self.request_components.as_ref()
    }
}

impl AsMut<Url> for RequestHandler {
    fn as_mut(&mut self) -> &mut Url {
        self.request_components.as_mut()
    }
}

pub type PagingResponse<T> = http::Response<Result<T, ErrorMessage>>;
pub type PagingResult<T> = GraphResult<PagingResponse<T>>;

pub struct Paging(RequestHandler);

impl Paging {
    async fn http_response<T: DeserializeOwned>(
        response: reqwest::Response,
    ) -> GraphResult<(Option<String>, PagingResponse<T>)> {
        let status = response.status();
        let url = response.url().clone();
        let headers = response.headers().clone();
        let version = response.version();

        let body: serde_json::Value = response.json().await?;
        let next_link = body.odata_next_link();
        let json = body.clone();
        let body_result: Result<T, ErrorMessage> = serde_json::from_value(body)
            .map_err(|_| serde_json::from_value(json.clone()).unwrap_or(ErrorMessage::default()));

        let mut builder = http::Response::builder()
            .url(url)
            .json(&json)
            .status(http::StatusCode::from(&status))
            .version(version);

        for builder_header in builder.headers_mut().iter_mut() {
            builder_header.extend(headers.clone());
        }

        Ok((next_link, builder.body(body_result)?))
    }

    /// Returns all next links as [`VecDeque<http::Response<T>>`]. This method may
    /// cause significant delay in returning when there is a high volume of next links.
    ///
    /// This method is mainly provided for convenience in cases where the caller is sure
    /// the requests will return successful without issue or where the caller is ok with
    /// a return delay or does not care if errors occur. It is not recommended to use this
    /// method in production environments.
    ///
    ///
    /// # Example
    /// ```rust,ignore
    /// let mut stream = client
    ///     .users()
    ///     .delta()
    ///     .paging()
    ///     .stream::<serde_json::Value>()
    ///     .unwrap();
    ///
    ///  while let Some(result) = stream.next().await {
    ///     println!("{result:#?}");
    ///  }
    /// ```
    pub async fn json<T: DeserializeOwned>(mut self) -> GraphResult<VecDeque<PagingResponse<T>>> {
        if let Some(err) = self.0.error {
            return Err(err);
        }

        let request = self.0.default_request_builder();
        let response = request.send().await?;

        let (next, http_response) = Paging::http_response(response).await?;
        let mut next_link = next;
        let mut vec = VecDeque::new();
        vec.push_back(http_response);

        let client = self.0.inner.clone();
        let access_token = self.0.access_token.clone();
        while let Some(next) = next_link {
            let response = client
                .get(next)
                .bearer_auth(access_token.as_str())
                .send()
                .await?;

            let (next, http_response) = Paging::http_response(response).await?;

            next_link = next;
            vec.push_back(http_response);
        }

        Ok(vec)
    }

    fn try_stream<'a, T: DeserializeOwned + 'a>(
        mut self,
    ) -> impl Stream<Item = PagingResult<T>> + 'a {
        try_stream! {
            let request = self.0.default_request_builder();
            let response = request.send().await?;
            let (next, http_response) = Paging::http_response(response).await?;
            let mut next_link = next;
            yield http_response;

            while let Some(url) = next_link {
                let response = self.0
                    .inner
                    .get(url)
                    .bearer_auth(self.0.access_token.as_str())
                    .send()
                    .await?;
                let (next, http_response) = Paging::http_response(response).await?;
                next_link = next;
                yield http_response;
            }
        }
    }

    /// Stream the current request along with any next link requests from the response body.
    /// Each stream.next() returns a [`GraphResult<http::Response<T>>`].
    ///
    /// # Example
    /// ```rust,ignore
    /// let mut stream = client
    ///     .users()
    ///     .delta()
    ///     .paging()
    ///     .stream::<serde_json::Value>()
    ///     .unwrap();
    ///
    ///  while let Some(result) = stream.next().await {
    ///     println!("{result:#?}");
    ///  }
    /// ```
    pub fn stream<'a, T: DeserializeOwned + 'a>(
        mut self,
    ) -> GraphResult<impl Stream<Item = PagingResult<T>> + 'a> {
        if let Some(err) = self.0.error.take() {
            return Err(err);
        }

        Ok(Box::pin(self.try_stream()))
    }

    /// Get next link responses using a channel Receiver [`tokio::sync::mpsc::Receiver<Option<GraphResult<http::Response<T>>>>`].
    ///
    /// By default channels use [`tokio::sync::mpsc::Sender::send_timeout`] with a buffer of 100
    /// and a timeout of 60. Use [`Paging::channel_timeout`] to set a custom timeout and use
    /// [`Paging::channel_buffer_timeout`] to set both the buffer and timeout.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let client = Graph::new("ACCESS_TOKEN");
    ///
    ///  let mut receiver = client
    ///     .users()
    ///     .list_user()
    ///     .top("5")
    ///     .paging()
    ///     .channel::<serde_json::Value>()
    ///     .await?;
    ///
    ///  while let Some(result) = receiver.recv().await {
    ///     let response = result?;
    ///     println!("{:#?}", response);
    ///  }
    /// ```
    pub async fn channel<T: DeserializeOwned + Debug + Send + 'static>(
        self,
    ) -> GraphResult<tokio::sync::mpsc::Receiver<PagingResult<T>>> {
        self.channel_buffer_timeout(100, Duration::from_secs(60))
            .await
    }

    /// Get next link responses using a channel Receiver,
    /// [`tokio::sync::mpsc::Receiver<Option<GraphResult<http::Response<T>>>>`].
    /// using a custom timeout [`Duration`]
    ///
    /// By default channels use [`tokio::sync::mpsc::Sender::send_timeout`] with a buffer of 100
    /// and a timeout of 60. Use [`Paging::channel_timeout`] to set a custom timeout and use
    /// [`Paging::channel_buffer_timeout`] to set both the buffer and timeout.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let client = Graph::new("ACCESS_TOKEN");
    ///
    ///  let mut receiver = client
    ///     .users()
    ///     .list_user()
    ///     .top("5")
    ///     .paging()
    ///     .channel::<serde_json::Value>()
    ///     .await?;
    ///
    ///  while let Some(result) = receiver.recv().await {
    ///     let response = result?;
    ///     println!("{:#?}", response);
    ///  }
    /// ```
    pub async fn channel_timeout<T: DeserializeOwned + Debug + Send + 'static>(
        self,
        timeout: Duration,
    ) -> GraphResult<tokio::sync::mpsc::Receiver<PagingResult<T>>> {
        self.channel_buffer_timeout(100, timeout).await
    }

    async fn send_channel_request<T: DeserializeOwned>(
        client: &reqwest::Client,
        url: &str,
        access_token: &str,
    ) -> GraphResult<(Option<String>, PagingResponse<T>)> {
        let response = client.get(url).bearer_auth(access_token).send().await?;

        Paging::http_response(response).await
    }

    /// Get next link responses using a channel Receiver,
    /// [`tokio::sync::mpsc::Receiver<Option<GraphResult<http::Response<T>>>>`].
    /// with a custom timeout [`Duration`] and buffer.
    ///
    /// By default channels use [`tokio::sync::mpsc::Sender::send_timeout`] with a buffer of 100
    /// and a timeout of 60. Use [`Paging::channel_timeout`] to set a custom timeout and use
    /// [`Paging::channel_buffer_timeout`] to set both the buffer and timeout.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let client = Graph::new("ACCESS_TOKEN");
    ///
    ///  let mut receiver = client
    ///     .users()
    ///     .list_user()
    ///     .top("5")
    ///     .paging()
    ///     .channel::<serde_json::Value>()
    ///     .await?;
    ///
    ///  while let Some(result) = receiver.recv().await {
    ///     let response = result?;
    ///     println!("{:#?}", response);
    ///  }
    /// ```
    #[allow(unused_assignments)] // Issue with Clippy not seeing next_link get assigned.
    pub async fn channel_buffer_timeout<T: DeserializeOwned + Debug + Send + 'static>(
        mut self,
        buffer: usize,
        timeout: Duration,
    ) -> GraphResult<tokio::sync::mpsc::Receiver<PagingResult<T>>> {
        let (sender, receiver) = tokio::sync::mpsc::channel(buffer);

        let request = self.0.default_request_builder();
        let response = request.send().await?;
        let (next, http_response) = Paging::http_response(response).await?;
        let mut next_link = next;
        sender
            .send_timeout(Ok(http_response), timeout)
            .await
            .unwrap();

        let client = self.0.inner.clone();
        let access_token = self.0.access_token.clone();

        tokio::spawn(async move {
            while let Some(next) = next_link {
                let result =
                    Paging::send_channel_request(&client, next.as_str(), access_token.as_str())
                        .await;

                match result {
                    Ok((next, response)) => {
                        next_link = next;
                        sender.send_timeout(Ok(response), timeout).await.unwrap();
                    }
                    Err(err) => {
                        sender.send_timeout(Err(err), timeout).await.unwrap();
                        next_link = None;
                        break;
                    }
                }
            }
        });

        Ok(receiver)
    }
}