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
#![cfg_attr(docsrs, feature(doc_cfg))]

//! This crate gives an high level API to execute external HTTP requests.
//!
//! It is supposed to give the basics building blocks for building bridges to other services
//! while abstracting the low level stuff like adding custom headers and request tracing.
//!
//! It supports both REST and GraphQL requests.
//!
//! You should start by creating a [Bridge] instance.
//! This instance should live for all the application lifetime.
//!
//! **Do not create a new bridge on every request!**
//!
//! You should use something like [once_cell](https://crates.io/crates/once_cell) or [lazy_static](https://crates.io/crates/lazy_static), or some sort of inversion of control container to
//! pass around.
//!
//! The bridge implement a type state pattern to build the external request.
//!
//! ### Features
//! * `auth0` - enable auth0 integration, allowing bridge.rs to retrieve tokens from auth0  for authentication
//! * `gzip` - provides response body gzip decompression.
//! * `redis-tls` - add support for connecting to redis with tls
//! * `tracing-opentelemetry` adds support for integration with opentelemetry.
//!     This feature is an alias for the `tracing_opentelemetry_0_21` feature.
//!     `tracing_opentelemetry_0_20` is also available as to support the 0.20 opentelemetry
//!     libraries.
//!
//!     We are going to support at least the last 3 versions of opentelemetry. After that we mightremove support for older otel version without it being a breaking change.

use errors::PrimaBridgeError;
use http::{header::HeaderName, HeaderValue, Method};
use reqwest::{multipart::Form, Url};
use sealed::Sealed;

pub use self::{
    builder::BridgeBuilder,
    redirect::RedirectPolicy,
    request::{
        Body, DeliverableRequest, GraphQLMultipart, GraphQLRequest, MultipartFile, MultipartFormFileField, Request,
        RestMultipart, RestRequest,
    },
    response::graphql::{Error, ParsedGraphqlResponse, ParsedGraphqlResponseExt, PossiblyParsedData},
    response::Response,
};

mod builder;
mod errors;
pub mod prelude;
mod redirect;
mod request;
mod response;

#[cfg(feature = "auth0")]
#[cfg_attr(docsrs, doc(cfg(feature = "auth0")))]
pub mod auth0;

/// The basic Bridge type, using a [reqwest::Client] as the client.
pub type Bridge = BridgeImpl<reqwest::Client>;

/// A Bridge instance that's generic across the client. If the [BridgeBuilder] is used
/// to construct a bridge with middleware, this type will be used to wrap the [reqwest_middleware::ClientWithMiddleware].
#[derive(Debug)]
pub struct BridgeImpl<T: BridgeClient> {
    inner_client: T,
    endpoint: Url,
    #[cfg(feature = "auth0")]
    auth0_opt: Option<auth0::Auth0>,
}

/// A trait that abstracts the client used by the [BridgeImpl], such that both reqwest clients and reqwest
/// clients with middleware can be used, more or less interchangeably.
#[doc(hidden)]
pub trait BridgeClient: Sealed {
    type Builder: PrimaRequestBuilderInner;
    fn request(&self, method: http::Method, url: Url) -> PrimaRequestBuilder<Self::Builder>;
}

/// A trait which abstracts across request builders, to allow for both reqwest and reqwest with middleware
/// request builders to be used.
#[doc(hidden)]
#[async_trait::async_trait]
pub trait PrimaRequestBuilderInner: Send + Sealed {
    fn timeout(self, timeout: std::time::Duration) -> Self;
    fn header<K, V>(self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>;
    fn headers(self, headers: http::HeaderMap) -> Self;

    fn body(self, body: impl Into<reqwest::Body>) -> Self;
    fn multipart(self, multipart: Form) -> Self;
    async fn send(self, url: Url) -> Result<reqwest::Response, PrimaBridgeError>;
}

/// A wrapper around a generic request builder
#[doc(hidden)]
pub struct PrimaRequestBuilder<T: PrimaRequestBuilderInner> {
    url: Url,
    inner: T,
}

impl BridgeClient for reqwest::Client {
    type Builder = reqwest::RequestBuilder;
    fn request(&self, method: Method, url: Url) -> PrimaRequestBuilder<Self::Builder> {
        PrimaRequestBuilder::new(url.clone(), self.request(method, url))
    }
}

impl BridgeClient for reqwest_middleware::ClientWithMiddleware {
    type Builder = reqwest_middleware::RequestBuilder;
    fn request(&self, method: Method, url: Url) -> PrimaRequestBuilder<Self::Builder> {
        PrimaRequestBuilder::new(url.clone(), self.request(method, url))
    }
}

impl<T: PrimaRequestBuilderInner> PrimaRequestBuilder<T> {
    fn new(url: Url, inner: T) -> Self {
        Self { url, inner }
    }

    fn timeout(self, timeout: std::time::Duration) -> Self {
        Self {
            inner: self.inner.timeout(timeout),
            ..self
        }
    }

    fn header<K, V>(self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        Self {
            inner: self.inner.header(key, value),
            ..self
        }
    }

    fn headers(self, headers: http::HeaderMap) -> Self {
        Self {
            inner: self.inner.headers(headers),
            ..self
        }
    }

    fn body(self, body: impl Into<reqwest::Body>) -> Self {
        Self {
            inner: self.inner.body(body),
            ..self
        }
    }

    fn multipart(self, multipart: Form) -> Self {
        Self {
            inner: self.inner.multipart(multipart),
            ..self
        }
    }

    async fn send(self) -> Result<reqwest::Response, PrimaBridgeError> {
        self.inner.send(self.url).await
    }
}

#[async_trait::async_trait]
impl PrimaRequestBuilderInner for reqwest::RequestBuilder {
    fn timeout(self, timeout: std::time::Duration) -> Self {
        self.timeout(timeout)
    }

    fn header<K, V>(self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        self.header(key, value)
    }
    fn headers(self, headers: http::HeaderMap) -> Self {
        self.headers(headers)
    }

    fn body(self, body: impl Into<reqwest::Body>) -> Self {
        self.body(body)
    }
    fn multipart(self, multipart: Form) -> Self {
        self.multipart(multipart)
    }
    async fn send(self, url: Url) -> Result<reqwest::Response, PrimaBridgeError> {
        self.send().await.map_err(|e| PrimaBridgeError::HttpError {
            source: e,
            url: url.clone(),
        })
    }
}

#[async_trait::async_trait]
impl PrimaRequestBuilderInner for reqwest_middleware::RequestBuilder {
    fn timeout(self, timeout: std::time::Duration) -> Self {
        self.timeout(timeout)
    }

    fn header<K, V>(self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        self.header(key, value)
    }
    fn headers(self, headers: http::HeaderMap) -> Self {
        self.headers(headers)
    }

    fn body(self, body: impl Into<reqwest::Body>) -> Self {
        self.body(body)
    }

    fn multipart(self, multipart: Form) -> Self {
        self.multipart(multipart)
    }

    async fn send(self, url: Url) -> Result<reqwest::Response, PrimaBridgeError> {
        self.send().await.map_err(|e| match e {
            reqwest_middleware::Error::Reqwest(e) => PrimaBridgeError::HttpError {
                source: e,
                url: url.clone(),
            },
            reqwest_middleware::Error::Middleware(e) => {
                PrimaBridgeError::MiddlewareError(reqwest_middleware::Error::from(e))
            }
        })
    }
}

impl Bridge {
    /// Creates an instance of a [BridgeBuilder].
    pub fn builder() -> BridgeBuilder {
        BridgeBuilder::create()
    }

    #[cfg(feature = "auth0")]
    #[cfg_attr(docsrs, doc(cfg(feature = "auth0")))]
    /// Gets the JWT token used by the Bridge, if it has been configured with Auth0 authentication via [BridgeBuilder.with_auth0](BridgeBuilder#with_auth0).
    pub fn token(&self) -> Option<auth0::Token> {
        self.auth0_opt.as_ref().map(|auth0| auth0.token())
    }
}

mod sealed {
    use crate::BridgeClient;

    pub trait Sealed {}

    impl Sealed for reqwest::Client {}
    impl Sealed for reqwest_middleware::ClientWithMiddleware {}
    impl Sealed for reqwest_middleware::RequestBuilder {}
    impl Sealed for reqwest::RequestBuilder {}
    impl<'a, Client: BridgeClient> Sealed for crate::request::RestRequest<'a, Client> {}
    impl<'a, Client: BridgeClient> Sealed for crate::request::GraphQLRequest<'a, Client> {}
}