Skip to main content

twilight_http/client/
builder.rs

1use super::Token;
2use crate::{Client, client::connector};
3use http::header::HeaderMap;
4use hyper_util::rt::TokioExecutor;
5use std::{
6    sync::{Arc, atomic::AtomicBool},
7    time::Duration,
8};
9use twilight_http_ratelimiting::RateLimiter;
10use twilight_model::channel::message::AllowedMentions;
11
12/// A builder for [`Client`].
13#[derive(Debug)]
14#[must_use = "has no effect if not built into a Client"]
15pub struct ClientBuilder {
16    pub(crate) default_allowed_mentions: Option<AllowedMentions>,
17    pub(crate) proxy: Option<Box<str>>,
18    ratelimiter: Option<RatelimiterConfiguration>,
19    remember_invalid_token: bool,
20    pub(crate) default_headers: Option<HeaderMap>,
21    pub(crate) timeout: Duration,
22    pub(super) token: Option<Token>,
23    pub(crate) use_http: bool,
24}
25
26/// Ratelimiter configured on a [`ClientBuilder`].
27///
28/// Creating a [`RateLimiter`] requires a Tokio runtime. By delaying
29/// instantiating one until the user calls [`ClientBuilder::build`], a user can
30/// disable it by passing `None` to [`ClientBuilder::ratelimiter`], which
31/// removes the need for a Tokio runtime. This is useful when the client is
32/// only used for building requests but not sending them.
33#[derive(Debug)]
34enum RatelimiterConfiguration {
35    Defined(RateLimiter),
36    Undefined,
37}
38
39impl ClientBuilder {
40    /// Create a new builder to create a [`Client`].
41    pub fn new() -> Self {
42        Self::default()
43    }
44
45    /// Build the [`Client`].
46    pub fn build(self) -> Client {
47        let connector = connector::create();
48
49        let http =
50            hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build(connector);
51
52        let token_invalidated = if self.remember_invalid_token {
53            Some(Arc::new(AtomicBool::new(false)))
54        } else {
55            None
56        };
57
58        let ratelimiter = self.ratelimiter.map(|rc| match rc {
59            RatelimiterConfiguration::Defined(r) => r,
60            RatelimiterConfiguration::Undefined => RateLimiter::default(),
61        });
62
63        Client {
64            http,
65            default_headers: self.default_headers,
66            proxy: self.proxy,
67            ratelimiter,
68            timeout: self.timeout,
69            token_invalidated,
70            token: self.token,
71            default_allowed_mentions: self.default_allowed_mentions,
72            use_http: self.use_http,
73        }
74    }
75
76    /// Set the default allowed mentions setting to use on all messages sent through the HTTP
77    /// client.
78    pub fn default_allowed_mentions(mut self, allowed_mentions: AllowedMentions) -> Self {
79        self.default_allowed_mentions.replace(allowed_mentions);
80
81        self
82    }
83
84    /// Set the proxy to use for all HTTP(S) requests.
85    ///
86    /// **Note** that this isn't currently a traditional proxy, but is for
87    /// working with something like [twilight's HTTP proxy server].
88    ///
89    /// # Examples
90    ///
91    /// Set the proxy to `twilight_http_proxy.internal`:
92    ///
93    /// ```no_run
94    /// use twilight_http::Client;
95    ///
96    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
97    /// let client = Client::builder()
98    ///     .proxy("twilight_http_proxy.internal".to_owned(), true)
99    ///     .build();
100    /// # Ok(()) }
101    /// ```
102    ///
103    /// [twilight's HTTP proxy server]: https://github.com/twilight-rs/http-proxy
104    pub fn proxy(mut self, proxy_url: String, use_http: bool) -> Self {
105        self.proxy.replace(proxy_url.into_boxed_str());
106        self.use_http = use_http;
107
108        self
109    }
110
111    /// Set a ratelimiter to use.
112    ///
113    /// If the argument is `None` then the client's ratelimiter will be skipped
114    /// before making a request.
115    ///
116    /// If not called, then a default [`RateLimiter`] will be created by
117    /// [`ClientBuilder::build`].
118    #[allow(clippy::missing_const_for_fn)]
119    pub fn ratelimiter(mut self, ratelimiter: Option<RateLimiter>) -> Self {
120        self.ratelimiter = ratelimiter.map(RatelimiterConfiguration::Defined);
121
122        self
123    }
124
125    /// Set the timeout for HTTP requests.
126    ///
127    /// The default is 10 seconds.
128    pub const fn timeout(mut self, duration: Duration) -> Self {
129        self.timeout = duration;
130
131        self
132    }
133
134    /// Set a group headers which are sent in every request.
135    pub fn default_headers(mut self, headers: HeaderMap) -> Self {
136        self.default_headers.replace(headers);
137
138        self
139    }
140
141    /// Whether to remember whether the client has encountered an Unauthorized
142    /// response status.
143    ///
144    /// If the client remembers encountering an Unauthorized response, then it
145    /// will not process future requests.
146    ///
147    /// Defaults to true.
148    pub const fn remember_invalid_token(mut self, remember: bool) -> Self {
149        self.remember_invalid_token = remember;
150
151        self
152    }
153
154    /// Set the token to use for HTTP requests.
155    pub fn token(mut self, mut token: String) -> Self {
156        let is_bot = token.starts_with("Bot ");
157        let is_bearer = token.starts_with("Bearer ");
158
159        // Make sure it is either a bot or bearer token, and assume it's a bot
160        // token if no prefix is given
161        if !is_bot && !is_bearer {
162            token.insert_str(0, "Bot ");
163        }
164
165        self.token.replace(Token::new(token.into_boxed_str()));
166
167        self
168    }
169}
170
171impl Default for ClientBuilder {
172    fn default() -> Self {
173        Self {
174            default_allowed_mentions: None,
175            default_headers: None,
176            proxy: None,
177            ratelimiter: (!cfg!(test)).then_some(RatelimiterConfiguration::Undefined),
178            remember_invalid_token: true,
179            timeout: Duration::from_secs(10),
180            token: None,
181            use_http: false,
182        }
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::ClientBuilder;
189    use static_assertions::assert_impl_all;
190    use std::fmt::Debug;
191
192    assert_impl_all!(ClientBuilder: Debug, Default, Send, Sync);
193
194    #[test]
195    fn client_debug() {
196        assert!(
197            format!("{:?}", ClientBuilder::new().token("Bot foo".to_owned()))
198                .contains("token: Some(<redacted>)")
199        );
200        assert!(format!("{:?}", ClientBuilder::new()).contains("token: None"));
201    }
202}