graph-http 3.0.0

Http client and utilities for the graph-rs-sdk crate
Documentation
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use crate::blocking::BlockingClient;
use graph_core::identity::{ClientApplication, ForceTokenRefresh};
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, USER_AGENT};
use reqwest::redirect::Policy;
use reqwest::tls::Version;
use reqwest::Proxy;
use reqwest::{Request, Response};
use std::env::VarError;
use std::ffi::OsStr;
use std::fmt::{Debug, Formatter};
use std::time::Duration;
use tower::limit::ConcurrencyLimitLayer;
use tower::retry::RetryLayer;
use tower::util::BoxCloneService;
use tower::ServiceExt;

fn user_agent_header_from_env() -> Option<HeaderValue> {
    let header = std::option_env!("GRAPH_CLIENT_USER_AGENT")?;
    HeaderValue::from_str(header).ok()
}

#[derive(Default, Clone)]
struct ServiceLayersConfiguration {
    concurrency_limit: Option<usize>,
    retry: Option<usize>,
    wait_for_retry_after_headers: Option<()>,
}

#[derive(Clone)]
struct ClientConfiguration {
    client_application: Option<Box<dyn ClientApplication>>,
    headers: HeaderMap,
    referer: bool,
    timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
    connection_verbose: bool,
    https_only: bool,
    /// TLS 1.2 required to support all features in Microsoft Graph
    /// See [Reliability and Support](https://learn.microsoft.com/en-us/graph/best-practices-concept#reliability-and-support)
    min_tls_version: Version,
    service_layers_configuration: ServiceLayersConfiguration,
    proxy: Option<Proxy>,
}

impl ClientConfiguration {
    pub fn new() -> ClientConfiguration {
        let mut headers: HeaderMap<HeaderValue> = HeaderMap::with_capacity(2);
        headers.insert(ACCEPT, HeaderValue::from_static("*/*"));

        if let Some(user_agent) = user_agent_header_from_env() {
            headers.insert(USER_AGENT, user_agent);
        }

        ClientConfiguration {
            client_application: None,
            headers,
            referer: true,
            timeout: None,
            connect_timeout: None,
            connection_verbose: false,
            https_only: true,
            min_tls_version: Version::TLS_1_2,
            service_layers_configuration: ServiceLayersConfiguration::default(),
            proxy: None,
        }
    }
}

impl PartialEq for ClientConfiguration {
    fn eq(&self, other: &Self) -> bool {
        self.headers == other.headers
            && self.referer == other.referer
            && self.connect_timeout == other.connect_timeout
            && self.connection_verbose == other.connection_verbose
            && self.https_only == other.https_only
            && self.min_tls_version == other.min_tls_version
    }
}

impl Debug for ClientConfiguration {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientConfiguration")
            .field("headers", &self.headers)
            .field("referer", &self.referer)
            .field("timeout", &self.timeout)
            .field("connect_timeout", &self.connect_timeout)
            .field("https_only", &self.https_only)
            .field("min_tls_version", &self.min_tls_version)
            .field("proxy", &self.proxy)
            .finish()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct GraphClientConfiguration {
    config: ClientConfiguration,
}

impl GraphClientConfiguration {
    pub fn new() -> GraphClientConfiguration {
        GraphClientConfiguration {
            config: ClientConfiguration::new(),
        }
    }

    pub fn access_token<AT: ToString>(mut self, access_token: AT) -> GraphClientConfiguration {
        self.config.client_application = Some(Box::new(access_token.to_string()));
        self
    }

    pub fn client_application<CA: ClientApplication + 'static>(mut self, client_app: CA) -> Self {
        self.config.client_application = Some(Box::new(client_app));
        self
    }

    pub fn default_headers(mut self, headers: HeaderMap) -> GraphClientConfiguration {
        for (key, value) in headers.iter() {
            self.config.headers.insert(key, value.clone());
        }
        self
    }

    /// Enable or disable automatic setting of the `Referer` header.
    ///
    /// Default is `true`.
    pub fn referer(mut self, enable: bool) -> GraphClientConfiguration {
        self.config.referer = enable;
        self
    }

    /// Enables a request timeout.
    ///
    /// The timeout is applied from when the request starts connecting until the
    /// response body has finished.
    ///
    /// Default is no timeout.
    pub fn timeout(mut self, timeout: Duration) -> GraphClientConfiguration {
        self.config.timeout = Some(timeout);
        self
    }

    /// Set a timeout for only the connect phase of a `Client`.
    ///
    /// Default is `None`.
    ///
    /// # Note
    ///
    /// This **requires** the futures be executed in a tokio runtime with
    /// a tokio timer enabled.
    pub fn connect_timeout(mut self, timeout: Duration) -> GraphClientConfiguration {
        self.config.connect_timeout = Some(timeout);
        self
    }

    /// Set whether connections should emit verbose logs.
    ///
    /// Enabling this option will emit [log][] messages at the `TRACE` level
    /// for read and write operations on connections.
    ///
    /// [log]: https://crates.io/crates/log
    pub fn connection_verbose(mut self, verbose: bool) -> GraphClientConfiguration {
        self.config.connection_verbose = verbose;
        self
    }

    pub fn user_agent(mut self, value: HeaderValue) -> GraphClientConfiguration {
        self.config.headers.insert(USER_AGENT, value);
        self
    }

    /// TLS 1.2 required to support all features in Microsoft Graph
    /// See [Reliability and Support](https://learn.microsoft.com/en-us/graph/best-practices-concept#reliability-and-support)
    pub fn min_tls_version(mut self, version: Version) -> GraphClientConfiguration {
        self.config.min_tls_version = version;
        self
    }

    /// Set [`Proxy`] for all network operations.
    ///
    /// Default is no proxy.
    pub fn proxy(mut self, proxy: Proxy) -> GraphClientConfiguration {
        self.config.proxy = Some(proxy);
        self
    }

    #[cfg(feature = "test-util")]
    pub fn https_only(mut self, https_only: bool) -> GraphClientConfiguration {
        self.config.https_only = https_only;
        self
    }

    /// Enable a request retry for a failed request. The retry parameter can be used to
    /// change how many times the request should be retried.
    ///
    /// Some requests may fail on GraphAPI side and should be retried.
    /// Only server errors (HTTP code between 500 and 599) will be retried.
    ///
    /// Default is no retry.
    pub fn retry(mut self, retry: Option<usize>) -> GraphClientConfiguration {
        self.config.service_layers_configuration.retry = retry;
        self
    }

    /// Enable a request retry if we reach the throttling limits and GraphAPI returns a
    /// 429 Too Many Requests with a Retry-After header
    ///
    /// Retry attempts are executed when the response has a status code of 429, 500, 503, 504
    /// and the response has a Retry-After header. The Retry-After header provides a back-off
    /// time to wait for before retrying the request again.
    ///
    /// Be careful with this parameter as some API endpoints have quite
    /// low limits (reports for example) and the request may hang for hundreds of seconds.
    /// For maximum throughput you may want to not respect the Retry-After header as hitting
    /// another server thanks to load-balancing may lead to a successful response.
    ///
    /// Default is no retry.
    pub fn wait_for_retry_after_headers(mut self, retry: bool) -> GraphClientConfiguration {
        self.config
            .service_layers_configuration
            .wait_for_retry_after_headers = match retry {
            true => Some(()),
            false => None,
        };
        self
    }

    /// Enable a concurrency limit on the client.
    ///
    /// Every request through this client will be subject to a concurrency limit.
    /// Can be useful to stay under the API limits set by GraphAPI.
    ///
    /// Default is no concurrency limit.
    pub fn concurrency_limit(
        mut self,
        concurrency_limit: Option<usize>,
    ) -> GraphClientConfiguration {
        self.config.service_layers_configuration.concurrency_limit = concurrency_limit;
        self
    }

    pub(crate) fn build_tower_service(
        &self,
        client: &reqwest::Client,
    ) -> BoxCloneService<Request, Response, Box<dyn std::error::Error + Send + Sync>> {
        tower::ServiceBuilder::new()
            .option_layer(
                self.config
                    .service_layers_configuration
                    .retry
                    .map(|num| RetryLayer::new(crate::tower_services::Attempts(num))),
            )
            .option_layer(
                self.config
                    .service_layers_configuration
                    .wait_for_retry_after_headers
                    .map(|_| RetryLayer::new(crate::tower_services::WaitFor())),
            )
            .option_layer(
                self.config
                    .service_layers_configuration
                    .concurrency_limit
                    .map(ConcurrencyLimitLayer::new),
            )
            .service(client.clone())
            .boxed_clone()
    }

    fn build_http_client(&self) -> reqwest::Client {
        let headers = self.config.headers.clone();
        let mut builder = reqwest::ClientBuilder::new()
            .referer(self.config.referer)
            .connection_verbose(self.config.connection_verbose)
            .https_only(self.config.https_only)
            .min_tls_version(self.config.min_tls_version)
            .redirect(Policy::limited(2))
            .default_headers(headers);

        if let Some(timeout) = self.config.timeout {
            builder = builder.timeout(timeout);
        }

        if let Some(connect_timeout) = self.config.connect_timeout {
            builder = builder.connect_timeout(connect_timeout);
        }

        if let Some(proxy) = &self.config.proxy {
            builder = builder.proxy(proxy.clone());
        }

        builder.build().unwrap()
    }

    fn build_blocking_http_client(&self) -> reqwest::blocking::Client {
        let headers = self.config.headers.clone();
        let mut builder = reqwest::blocking::ClientBuilder::new()
            .referer(self.config.referer)
            .connection_verbose(self.config.connection_verbose)
            .https_only(self.config.https_only)
            .min_tls_version(self.config.min_tls_version)
            .redirect(Policy::limited(2))
            .default_headers(headers);

        if let Some(timeout) = self.config.timeout {
            builder = builder.timeout(timeout);
        }

        if let Some(connect_timeout) = self.config.connect_timeout {
            builder = builder.connect_timeout(connect_timeout);
        }

        if let Some(proxy) = &self.config.proxy {
            builder = builder.proxy(proxy.clone());
        }

        builder.build().unwrap()
    }

    pub(crate) fn build(self) -> Client {
        let config = self.clone();
        let headers = self.config.headers.clone();
        let client = self.build_http_client();

        if let Some(client_application) = self.config.client_application {
            Client {
                client_application,
                inner: client,
                headers,
                builder: config,
            }
        } else {
            Client {
                client_application: Box::<String>::default(),
                inner: client,
                headers,
                builder: config,
            }
        }
    }

    pub(crate) fn build_blocking(self) -> BlockingClient {
        let headers = self.config.headers.clone();
        let client = self.build_blocking_http_client();

        if let Some(client_application) = self.config.client_application {
            BlockingClient {
                client_application,
                inner: client,
                headers,
            }
        } else {
            BlockingClient {
                client_application: Box::<String>::default(),
                inner: client,
                headers,
            }
        }
    }

    pub(crate) fn build_minimal_async_client(self) -> MinimalAsyncClient {
        let config = self.clone();
        let client = self.build_http_client();
        let service = self.build_tower_service(&client);
        MinimalAsyncClient {
            inner: client,
            builder: config,
            service,
        }
    }

    pub(crate) fn build_minimal_blocking_client(self) -> MinimalBlockingClient {
        let config = self.clone();
        let client = self.build_blocking();
        MinimalBlockingClient {
            inner: client.inner,
            builder: config,
        }
    }
}

impl Default for GraphClientConfiguration {
    fn default() -> Self {
        GraphClientConfiguration::new()
    }
}

#[derive(Clone)]
pub struct Client {
    pub(crate) client_application: Box<dyn ClientApplication>,
    pub(crate) inner: reqwest::Client,
    pub(crate) headers: HeaderMap,
    pub(crate) builder: GraphClientConfiguration,
}

impl Client {
    pub fn new<CA: ClientApplication + 'static>(client_app: CA) -> Self {
        GraphClientConfiguration::new()
            .client_application(client_app)
            .build()
    }

    pub fn from_access_token<T: AsRef<str>>(access_token: T) -> Self {
        GraphClientConfiguration::new()
            .access_token(access_token.as_ref())
            .build()
    }

    /// Create a new client and use the given environment variable
    /// for the access token.
    pub fn new_env<K: AsRef<OsStr>>(env_var: K) -> Result<Client, VarError> {
        Ok(GraphClientConfiguration::new()
            .access_token(std::env::var(env_var)?)
            .build())
    }

    pub fn builder() -> GraphClientConfiguration {
        GraphClientConfiguration::new()
    }

    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    pub fn with_force_token_refresh(&mut self, force_token_refresh: ForceTokenRefresh) {
        self.client_application
            .with_force_token_refresh(force_token_refresh);
    }
}

impl Default for Client {
    fn default() -> Self {
        GraphClientConfiguration::new().build()
    }
}

impl Debug for Client {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("inner", &self.inner)
            .field("headers", &self.headers)
            .field("builder", &self.builder)
            .finish()
    }
}

impl From<GraphClientConfiguration> for Client {
    fn from(value: GraphClientConfiguration) -> Self {
        value.build()
    }
}

#[derive(Clone)]
pub struct MinimalAsyncClient {
    pub inner: reqwest::Client,
    pub builder: GraphClientConfiguration,
    pub service: BoxCloneService<Request, Response, Box<dyn std::error::Error + Send + Sync>>,
}

/*
let service = inner.builder.build_tower_service(&inner.inner);
 */

impl From<GraphClientConfiguration> for MinimalAsyncClient {
    fn from(value: GraphClientConfiguration) -> Self {
        value.build_minimal_async_client()
    }
}

impl Default for MinimalAsyncClient {
    fn default() -> Self {
        GraphClientConfiguration::new().build_minimal_async_client()
    }
}

#[derive(Clone)]
pub struct MinimalBlockingClient {
    pub inner: reqwest::blocking::Client,
    pub builder: GraphClientConfiguration,
}

impl From<GraphClientConfiguration> for MinimalBlockingClient {
    fn from(value: GraphClientConfiguration) -> Self {
        value.build_minimal_blocking_client()
    }
}

impl Default for MinimalBlockingClient {
    fn default() -> Self {
        GraphClientConfiguration::new().build_minimal_blocking_client()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn compile_time_user_agent_header() {
        let client = GraphClientConfiguration::new()
            .access_token("access_token")
            .build();

        assert!(client.builder.config.headers.contains_key(USER_AGENT));
    }

    #[test]
    fn update_user_agent_header() {
        let client = GraphClientConfiguration::new()
            .access_token("access_token")
            .user_agent(HeaderValue::from_static("user_agent"))
            .build();

        assert!(client.builder.config.headers.contains_key(USER_AGENT));
        let user_agent_header = client.builder.config.headers.get(USER_AGENT).unwrap();
        assert_eq!("user_agent", user_agent_header.to_str().unwrap());
    }
}