paperclip-ng 0.1.3

Experimental OpenAPI V3.0.3 Code Generator
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
#![allow(clippy::type_complexity)]
use super::body::BodyStreamExt;

pub use hyper::{body, service::Service, Body, Request, Response, Uri};

use std::{sync::Arc, time::Duration};
use tokio::sync::Mutex;
use tower::{util::BoxCloneService, Layer, ServiceExt};

#[cfg(feature = "tower-trace")]
use opentelemetry::global;
#[cfg(feature = "tower-trace")]
use opentelemetry_http::HeaderInjector;

#[cfg(all(feature = "tower-client-rls", not(feature = "tower-client-tls")))]
use rustls::{
    client::{ServerCertVerified, ServerCertVerifier},
    Certificate, Error as TLSError,
};

use tower_http::map_response_body::MapResponseBodyLayer;
#[cfg(feature = "tower-trace")]
use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};

#[cfg(feature = "tower-trace")]
use tracing::Span;
#[cfg(feature = "tower-trace")]
use tracing_opentelemetry::OpenTelemetrySpanExt;

/// Tower Service Error
pub type BoxedError = Box<dyn std::error::Error + Send + Sync>;

/// `ConfigurationBuilder` that can be used to build a `Configuration`.
#[derive(Clone)]
pub struct ConfigurationBuilder {
    /// Timeout for each HTTP Request.
    timeout: Option<std::time::Duration>,
    /// Bearer Access Token for bearer-configured routes.
    bearer_token: Option<String>,
    /// OpenTel and Tracing layer.
    #[cfg(feature = "tower-trace")]
    tracing_layer: bool,
    certificate: Option<Vec<u8>>,
    concurrency_limit: Option<usize>,
}

impl Default for ConfigurationBuilder {
    fn default() -> Self {
        Self {
            timeout: Some(std::time::Duration::from_secs(5)),
            bearer_token: None,
            #[cfg(feature = "tower-trace")]
            tracing_layer: true,
            certificate: None,
            concurrency_limit: None,
        }
    }
}

impl ConfigurationBuilder {
    /// Return a new `Self`.
    pub fn new() -> Self {
        Self::default()
    }
    /// Enable/Disable a request timeout layer with the given request timeout.
    pub fn with_timeout<O: Into<Option<Duration>>>(mut self, timeout: O) -> Self {
        self.timeout = timeout.into();
        self
    }
    /// Enable/Disable the given request bearer token.
    pub fn with_bearer_token(mut self, bearer_token: Option<String>) -> Self {
        self.bearer_token = bearer_token;
        self
    }
    /// Add a request concurrency limit.
    pub fn with_concurrency_limit(mut self, limit: Option<usize>) -> Self {
        self.concurrency_limit = limit;
        self
    }
    /// Add a PEM-format certificate file.
    pub fn with_certificate(mut self, certificate: &[u8]) -> Self {
        self.certificate = Some(certificate.to_vec());
        self
    }
    /// Enable/Disable the telemetry and tracing layer.
    #[cfg(feature = "tower-trace")]
    pub fn with_tracing(mut self, tracing_layer: bool) -> Self {
        self.tracing_layer = tracing_layer;
        self
    }
    /// Build a `Configuration` from the Self parameters.
    pub fn build(self, uri: hyper::Uri) -> Result<Configuration, Error> {
        Configuration::new(
            uri.to_string().parse().map_err(Error::UriToUrl)?,
            self.timeout.unwrap(),
            self.bearer_token,
            self.certificate.as_ref().map(|c| &c[..]),
            self.tracing_layer,
            self.concurrency_limit,
        )
    }
    /// Build a `Configuration` from the Self parameters.
    pub fn build_url(self, url: url::Url) -> Result<Configuration, Error> {
        Configuration::new(
            url,
            self.timeout.unwrap_or_else(|| Duration::from_secs(5)),
            self.bearer_token,
            self.certificate.as_ref().map(|c| &c[..]),
            self.tracing_layer,
            self.concurrency_limit,
        )
    }
    /// Build a `Configuration` from the Self parameters.
    pub fn build_with_svc<S>(
        self,
        uri: hyper::Uri,
        client_service: S,
    ) -> Result<Configuration, Error>
    where
        S: Service<Request<Body>, Response = Response<Body>> + Sync + Send + Clone + 'static,
        S::Future: Send + 'static,
        S::Error: Into<BoxedError> + std::fmt::Debug,
    {
        #[cfg(feature = "tower-trace")]
        let tracing_layer = self.tracing_layer;
        #[cfg(not(feature = "tower-trace"))]
        let tracing_layer = false;
        Configuration::new_with_client(
            uri,
            client_service,
            self.timeout,
            self.bearer_token,
            tracing_layer,
            self.concurrency_limit,
        )
    }
}

/// Configuration used by the `ApiClient`.
#[derive(Clone)]
pub struct Configuration {
    pub base_path: hyper::Uri,
    pub user_agent: Option<String>,
    pub client_service: Arc<Mutex<BoxCloneService<Request<Body>, Response<Body>, BoxedError>>>,
    pub basic_auth: Option<BasicAuth>,
    pub oauth_access_token: Option<String>,
    pub bearer_access_token: Option<String>,
    pub api_key: Option<ApiKey>,
}

/// Basic authentication.
pub type BasicAuth = (String, Option<String>);

/// ApiKey used for ApiKey authentication.
#[derive(Debug, Clone)]
pub struct ApiKey {
    pub prefix: Option<String>,
    pub key: String,
}

/// Configuration creation Error.
#[derive(Debug)]
pub enum Error {
    Certificate,
    TlsConnector,
    NoTracingFeature,
    UrlToUri(hyper::http::uri::InvalidUri),
    UriToUrl(url::ParseError),
    AddingVersionPath(hyper::http::uri::InvalidUri),
}

impl Configuration {
    /// Return a new `ConfigurationBuilder`.
    pub fn builder() -> ConfigurationBuilder {
        ConfigurationBuilder::new()
    }

    /// New `Self` with a provided client.
    pub fn new_with_client<S>(
        mut url: hyper::Uri,
        client_service: S,
        timeout: Option<std::time::Duration>,
        bearer_access_token: Option<String>,
        trace_requests: bool,
        concurrency_limit: Option<usize>,
    ) -> Result<Self, Error>
    where
        S: Service<Request<Body>, Response = Response<Body>> + Sync + Send + Clone + 'static,
        S::Future: Send + 'static,
        S::Error: Into<BoxedError> + std::fmt::Debug,
    {
        #[cfg(feature = "tower-trace")]
        let tracing_layer = tower::ServiceBuilder::new()
            .layer(
                TraceLayer::new_for_http()
                    .make_span_with(|request: &Request<Body>| {
                        tracing::info_span!(
                            "HTTP",
                            http.method = %request.method(),
                            http.url = %request.uri(),
                            http.status_code = tracing::field::Empty,
                            otel.name = %format!("{} {}", request.method(), request.uri()),
                            otel.kind = "client",
                            otel.status_code = tracing::field::Empty,
                        )
                    })
                    // to silence the default trace
                    .on_request(|request: &Request<Body>, _span: &Span| {
                        tracing::trace!("started {} {}", request.method(), request.uri().path())
                    })
                    .on_response(
                        |response: &Response<Body>, _latency: std::time::Duration, span: &Span| {
                            let status = response.status();
                            span.record("http.status_code", status.as_u16());
                            if status.is_client_error() || status.is_server_error() {
                                span.record("otel.status_code", "ERROR");
                            }
                        },
                    )
                    .on_body_chunk(())
                    .on_failure(
                        |ec: ServerErrorsFailureClass,
                         _latency: std::time::Duration,
                         span: &Span| {
                            span.record("otel.status_code", "ERROR");
                            match ec {
                                ServerErrorsFailureClass::StatusCode(status) => {
                                    span.record("http.status_code", status.as_u16());
                                    tracing::debug!(status=%status, "failed to issue request")
                                }
                                ServerErrorsFailureClass::Error(err) => {
                                    tracing::debug!(error=%err, "failed to issue request")
                                }
                            }
                        },
                    ),
            )
            // injects the telemetry context in the http headers
            .layer(OpenTelContext::new())
            .into_inner();

        url = format!("{}/v0", url.to_string().trim_end_matches('/'))
            .parse()
            .map_err(Error::AddingVersionPath)?;

        let backend_service = tower::ServiceBuilder::new()
            .option_layer(timeout.map(tower::timeout::TimeoutLayer::new))
            // .option_layer(
            //     bearer_access_token.map(|b| tower_http::auth::AddAuthorizationLayer::bearer(&b)),
            // )
            .service(client_service);

        let service_builder = tower::ServiceBuilder::new()
            .option_layer(concurrency_limit.map(tower::limit::ConcurrencyLimitLayer::new));

        match trace_requests {
            false => Ok(Self::new_with_client_inner(
                url,
                service_builder.service(backend_service),
                bearer_access_token,
            )),
            true => {
                #[cfg(feature = "tower-trace")]
                let result = Ok(Self::new_with_client_inner(
                    url,
                    service_builder
                        .layer(tracing_layer)
                        .service(backend_service),
                    bearer_access_token,
                ));
                #[cfg(not(feature = "tower-trace"))]
                let result = Err(Error::NoTracingFeature {});
                result
            }
        }
    }

    /// New `Self`.
    pub fn new(
        mut url: url::Url,
        timeout: std::time::Duration,
        bearer_access_token: Option<String>,
        certificate: Option<&[u8]>,
        trace_requests: bool,
        concurrency_limit: Option<usize>,
    ) -> Result<Self, Error> {
        #[cfg(all(not(feature = "tower-client-tls"), feature = "tower-client-rls"))]
        let client = {
            match certificate {
                None => {
                    let mut http = hyper::client::HttpConnector::new();

                    let tls = match url.scheme() == "https" {
                        true => {
                            http.enforce_http(false);
                            rustls::ClientConfig::builder()
                                .with_safe_defaults()
                                .with_custom_certificate_verifier(std::sync::Arc::new(
                                    DisableServerCertVerifier {},
                                ))
                                .with_no_client_auth()
                        }
                        false => rustls::ClientConfig::builder()
                            .with_safe_defaults()
                            .with_root_certificates(rustls::RootCertStore::empty())
                            .with_no_client_auth(),
                    };

                    let connector =
                        hyper_rustls::HttpsConnector::from((http, std::sync::Arc::new(tls)));
                    hyper::Client::builder().build(connector)
                }
                Some(bytes) => {
                    let mut cert_file = std::io::BufReader::new(bytes);
                    let mut root_store = rustls::RootCertStore::empty();
                    root_store.add_parsable_certificates(
                        &rustls_pemfile::certs(&mut cert_file).map_err(|_| Error::Certificate)?,
                    );
                    let config = rustls::ClientConfig::builder()
                        .with_safe_defaults()
                        .with_root_certificates(root_store)
                        .with_no_client_auth();

                    let mut http = hyper::client::HttpConnector::new();
                    http.enforce_http(false);
                    let connector =
                        hyper_rustls::HttpsConnector::from((http, std::sync::Arc::new(config)));
                    url.set_scheme("https").ok();
                    hyper::Client::builder().build(connector)
                }
            }
        };
        #[cfg(feature = "tower-client-tls")]
        let client = {
            match certificate {
                None => {
                    let mut http = hyper_tls::HttpsConnector::new();
                    if url.scheme() == "https" {
                        http.https_only(true);
                    }

                    let tls = hyper_tls::native_tls::TlsConnector::builder()
                        .danger_accept_invalid_certs(true)
                        .build()
                        .map_err(|_| Error::TlsConnector)?;
                    let tls = tokio_native_tls::TlsConnector::from(tls);

                    let connector = hyper_tls::HttpsConnector::from((http, tls));
                    hyper::Client::builder().build(connector)
                }
                Some(bytes) => {
                    let certificate = hyper_tls::native_tls::Certificate::from_pem(bytes)
                        .map_err(|_| Error::Certificate)?;

                    let tls = hyper_tls::native_tls::TlsConnector::builder()
                        .add_root_certificate(certificate)
                        .danger_accept_invalid_hostnames(true)
                        .disable_built_in_roots(true)
                        .build()
                        .map_err(|_| Error::TlsConnector)?;
                    let tls = tokio_native_tls::TlsConnector::from(tls);

                    let mut http = hyper_tls::HttpsConnector::new();
                    http.https_only(true);
                    let connector = hyper_tls::HttpsConnector::from((http, tls));
                    url.set_scheme("https").ok();
                    hyper::Client::builder().build(connector)
                }
            }
        };

        let uri = url.to_string().parse().map_err(Error::UrlToUri)?;
        Self::new_with_client(
            uri,
            client,
            Some(timeout),
            bearer_access_token,
            trace_requests,
            concurrency_limit,
        )
    }

    /// New `Self` with a provided client.
    pub fn new_with_client_inner<S, B>(
        url: hyper::Uri,
        client_service: S,
        bearer_access_token: Option<String>,
    ) -> Self
    where
        S: Service<Request<Body>, Response = Response<B>> + Sync + Send + Clone + 'static,
        S::Future: Send + 'static,
        S::Error: Into<BoxedError> + std::fmt::Debug,
        B: http_body::Body<Data = hyper::body::Bytes> + Send + 'static,
        B::Error: std::error::Error + Send + Sync + 'static,
    {
        // Transform response body to `hyper::Body` and use type erased error to avoid type
        // parameters.
        let client_service = MapResponseBodyLayer::new(|b: B| Body::wrap_stream(b.into_stream()))
            .layer(client_service)
            .map_err(|e| e.into());
        let client_service = Arc::new(Mutex::new(BoxCloneService::new(client_service)));
        Self {
            base_path: url,
            user_agent: None,
            client_service,
            basic_auth: None,
            oauth_access_token: None,
            bearer_access_token,
            api_key: None,
        }
    }
}

/// Add OpenTelemetry Span to the Http Headers.
#[cfg(feature = "tower-trace")]
pub struct OpenTelContext {}
#[cfg(feature = "tower-trace")]
impl OpenTelContext {
    fn new() -> Self {
        Self {}
    }
}
#[cfg(feature = "tower-trace")]
impl<S> Layer<S> for OpenTelContext {
    type Service = OpenTelContextService<S>;

    fn layer(&self, service: S) -> Self::Service {
        OpenTelContextService::new(service)
    }
}

/// OpenTelemetry Service that injects the current span into the Http Headers.
#[cfg(feature = "tower-trace")]
#[derive(Clone)]
pub struct OpenTelContextService<S> {
    service: S,
}
#[cfg(feature = "tower-trace")]
impl<S> OpenTelContextService<S> {
    fn new(service: S) -> Self {
        Self { service }
    }
}

#[cfg(feature = "tower-trace")]
impl<S> Service<hyper::Request<Body>> for OpenTelContextService<S>
where
    S: Service<hyper::Request<Body>>,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = S::Future;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, mut request: hyper::Request<Body>) -> Self::Future {
        let cx = tracing::Span::current().context();
        global::get_text_map_propagator(|propagator| {
            propagator.inject_context(&cx, &mut HeaderInjector(request.headers_mut()))
        });
        self.service.call(request)
    }
}

#[cfg(all(feature = "tower-client-rls", not(feature = "tower-client-tls")))]
struct DisableServerCertVerifier {}
#[cfg(all(feature = "tower-client-rls", not(feature = "tower-client-tls")))]
impl ServerCertVerifier for DisableServerCertVerifier {
    fn verify_server_cert(
        &self,
        _end_entity: &Certificate,
        _intermediates: &[Certificate],
        _server_name: &rustls::ServerName,
        _scts: &mut dyn Iterator<Item = &[u8]>,
        _ocsp_response: &[u8],
        _now: std::time::SystemTime,
    ) -> Result<ServerCertVerified, TLSError> {
        Ok(ServerCertVerified::assertion())
    }
}