Merge pull request #113 from teloxide/dont_reparse_url_on_every_request

Do not re-parse default tba url on every request
This commit is contained in:
Hirrolot 2021-08-31 07:50:21 -07:00 committed by GitHub
commit 16a3ba3349
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 31 deletions

View file

@ -4,14 +4,12 @@ use reqwest::Client;
use serde::{de::DeserializeOwned, Serialize}; use serde::{de::DeserializeOwned, Serialize};
use crate::{ use crate::{
bot::api_url::ApiUrl,
net, net,
requests::{MultipartPayload, Payload, ResponseResult}, requests::{MultipartPayload, Payload, ResponseResult},
serde_multipart, serde_multipart,
}; };
mod api; mod api;
mod api_url;
mod download; mod download;
const TELOXIDE_TOKEN: &str = "TELOXIDE_TOKEN"; const TELOXIDE_TOKEN: &str = "TELOXIDE_TOKEN";
@ -56,7 +54,7 @@ const TELOXIDE_TOKEN: &str = "TELOXIDE_TOKEN";
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Bot { pub struct Bot {
token: Arc<str>, token: Arc<str>,
api_url: ApiUrl, api_url: Arc<reqwest::Url>,
client: Client, client: Client,
} }
@ -93,9 +91,15 @@ impl Bot {
where where
S: Into<String>, S: Into<String>,
{ {
let token = Into::<String>::into(token).into();
let api_url = Arc::new(
reqwest::Url::parse(net::TELEGRAM_API_URL)
.expect("Failed to parse default Telegram bot API url"),
);
Self { Self {
token: Into::<Arc<str>>::into(Into::<String>::into(token)), token,
api_url: ApiUrl::Default, api_url,
client, client,
} }
} }
@ -174,7 +178,7 @@ impl Bot {
/// assert_ne!(bot2.api_url().as_str(), "https://example.com/"); /// assert_ne!(bot2.api_url().as_str(), "https://example.com/");
/// ``` /// ```
pub fn set_api_url(mut self, url: reqwest::Url) -> Self { pub fn set_api_url(mut self, url: reqwest::Url) -> Self {
self.api_url = ApiUrl::Custom(Arc::new(url)); self.api_url = Arc::new(url);
self self
} }
} }
@ -193,7 +197,7 @@ impl Bot {
/// Returns currently used token API url. /// Returns currently used token API url.
pub fn api_url(&self) -> reqwest::Url { pub fn api_url(&self) -> reqwest::Url {
self.api_url.get() reqwest::Url::clone(&*self.api_url)
} }
} }
@ -208,14 +212,23 @@ impl Bot {
{ {
let client = self.client.clone(); let client = self.client.clone();
let token = Arc::clone(&self.token); let token = Arc::clone(&self.token);
let api_url = self.api_url.clone(); let api_url = Arc::clone(&self.api_url);
let params = serde_json::to_vec(payload) let params = serde_json::to_vec(payload)
// this `expect` should be ok since we don't write request those may trigger error here // this `expect` should be ok since we don't write request those may trigger error here
.expect("serialization of request to be infallible"); .expect("serialization of request to be infallible");
// async move to capture client&token&api_url&params // async move to capture client&token&api_url&params
async move { net::request_json(&client, token.as_ref(), api_url.get(), P::NAME, params).await } async move {
net::request_json(
&client,
token.as_ref(),
reqwest::Url::clone(&*api_url),
P::NAME,
params,
)
.await
}
} }
pub(crate) fn execute_multipart<P>( pub(crate) fn execute_multipart<P>(
@ -228,14 +241,21 @@ impl Bot {
{ {
let client = self.client.clone(); let client = self.client.clone();
let token = Arc::clone(&self.token); let token = Arc::clone(&self.token);
let api_url = self.api_url.clone(); let api_url = Arc::clone(&self.api_url);
let params = serde_multipart::to_form(payload); let params = serde_multipart::to_form(payload);
// async move to capture client&token&api_url&params // async move to capture client&token&api_url&params
async move { async move {
let params = params.await?; let params = params.await?;
net::request_multipart(&client, token.as_ref(), api_url.get(), P::NAME, params).await net::request_multipart(
&client,
token.as_ref(),
reqwest::Url::clone(&*api_url),
P::NAME,
params,
)
.await
} }
} }
} }

View file

@ -1,18 +0,0 @@
use std::sync::Arc;
#[derive(Debug, Clone)]
pub(crate) enum ApiUrl {
Default,
Custom(Arc<reqwest::Url>),
}
impl ApiUrl {
pub(crate) fn get(&self) -> reqwest::Url {
match self {
// FIXME(waffle): parse once
ApiUrl::Default => reqwest::Url::parse(crate::net::TELEGRAM_API_URL)
.expect("failed to parse default url"),
ApiUrl::Custom(url) => (&**url).clone(),
}
}
}

View file

@ -22,7 +22,7 @@ impl<'w> Download<'w> for Bot {
) -> Self::Fut { ) -> Self::Fut {
net::download_file( net::download_file(
&self.client, &self.client,
self.api_url.get(), reqwest::Url::clone(&*self.api_url),
&self.token, &self.token,
path, path,
destination, destination,
@ -35,6 +35,12 @@ impl<'w> Download<'w> for Bot {
type Stream = BoxStream<'static, Result<Bytes, Self::StreamErr>>; type Stream = BoxStream<'static, Result<Bytes, Self::StreamErr>>;
fn download_file_stream(&self, path: &str) -> Self::Stream { fn download_file_stream(&self, path: &str) -> Self::Stream {
net::download_file_stream(&self.client, self.api_url.get(), &self.token, path).boxed() net::download_file_stream(
&self.client,
reqwest::Url::clone(&*self.api_url),
&self.token,
path,
)
.boxed()
} }
} }