Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make hyper and tokio optional dependencies #269

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,20 @@ license = "MIT"
[features]
openssl = ["hyper-tls"]
rustls = ["hyper-rustls"]
default = ["openssl"]
runtime-tokio = ["tokio"]
connector-hyper = ["hyper", "runtime-tokio"]
default = ["openssl", "connector-hyper"]
[dependencies]
bytes = "1.0.1"
tokio = { version = "1.2", features = ["fs", "rt"]}

tracing = "0.1.23"
tracing-futures = "0.2"
multipart = { version = "0.17", default-features = false, features = ["client"] }

telegram-bot-raw = { version = "0.9.0", path = "../raw" }

hyper = { version = "0.14", features = ["client", "http1"] }
tokio = { version = "1.2", features = ["fs", "rt"], optional = true }
hyper = { version = "0.14", features = ["client", "http1"], optional = true }
hyper-tls = { version = "0.5", optional = true }
futures = "0.3"
hyper-rustls = { version = "0.22", optional = true }
Expand Down
15 changes: 12 additions & 3 deletions lib/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@ use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
use std::time::Duration;

use futures::{Future, FutureExt};
use tokio::time::timeout;

use tracing_futures::Instrument;

use telegram_bot_raw::{HttpRequest, Request, ResponseType};

use crate::connector::{default_connector, Connector};
use crate::connector::Connector;
use crate::errors::{Error, ErrorKind};
use crate::stream::UpdatesStream;

#[cfg(feature = "runtime-tokio")]
use tokio::time::timeout;
#[cfg(feature = "runtime-tokio")]
use std::time::Duration;
#[cfg(feature = "connector-hyper")]
use crate::connector::default_connector;

/// Main type for sending requests to the Telegram bot API.
#[derive(Clone)]
pub struct Api(Arc<ApiInner>);
Expand All @@ -39,6 +45,7 @@ impl Api {
/// let api = Api::new(telegram_token);
/// # }
/// ```
#[cfg(feature = "connector-hyper")]
pub fn new<T: AsRef<str>>(token: T) -> Self {
Self::with_connector(token, default_connector())
}
Expand Down Expand Up @@ -91,6 +98,7 @@ impl Api {
/// # }
/// # }
/// ```
#[cfg(feature = "runtime-tokio")]
pub fn spawn<Req: Request>(&self, request: Req) {
let api = self.clone();
if let Ok(request) = request.serialize() {
Expand Down Expand Up @@ -119,6 +127,7 @@ impl Api {
/// # }
/// # }
/// ```
#[cfg(feature = "runtime-tokio")]
pub fn send_timeout<Req: Request>(
&self,
request: Req,
Expand Down
2 changes: 2 additions & 0 deletions lib/src/connector/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Connector with hyper backend.

#[cfg(feature = "connector-hyper")]
pub mod hyper;

use std::fmt::Debug;
Expand All @@ -18,6 +19,7 @@ pub trait Connector: Debug + Send + Sync {
) -> Pin<Box<dyn Future<Output = Result<HttpResponse, Error>> + Send>>;
}

#[cfg(feature = "hyper")]
pub fn default_connector() -> Box<dyn Connector> {
hyper::default_connector().unwrap()
}
20 changes: 19 additions & 1 deletion lib/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,25 @@ use std::fmt;
pub struct Error(ErrorKind);

#[derive(Debug)]
pub(crate) enum ErrorKind {
pub enum ErrorKind {
Raw(telegram_bot_raw::Error),
#[cfg(feature = "connector-hyper")]
Hyper(hyper::Error),
#[cfg(feature = "connector-hyper")]
Http(hyper::http::Error),
Io(std::io::Error),
InvalidMultipartFilename,
Generic(Box<dyn std::error::Error + Send>),
}

impl ErrorKind {
pub fn from_generic<E: std::error::Error + Send + 'static>(e: E) -> Self {
Self::Generic(Box::new(e))
}

pub fn from_generic_boxed(e: Box<dyn std::error::Error + Send>) -> Self {
Self::Generic(e)
}
}

impl From<telegram_bot_raw::Error> for ErrorKind {
Expand All @@ -19,12 +32,14 @@ impl From<telegram_bot_raw::Error> for ErrorKind {
}
}

#[cfg(feature = "connector-hyper")]
impl From<hyper::Error> for ErrorKind {
fn from(error: hyper::Error) -> Self {
ErrorKind::Hyper(error)
}
}

#[cfg(feature = "connector-hyper")]
impl From<hyper::http::Error> for ErrorKind {
fn from(error: hyper::http::Error) -> Self {
ErrorKind::Http(error)
Expand All @@ -47,10 +62,13 @@ impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
ErrorKind::Raw(error) => write!(f, "{}", error),
#[cfg(feature = "connector-hyper")]
ErrorKind::Hyper(error) => write!(f, "{}", error),
#[cfg(feature = "connector-hyper")]
ErrorKind::Http(error) => write!(f, "{}", error),
ErrorKind::Io(error) => write!(f, "{}", error),
ErrorKind::InvalidMultipartFilename => write!(f, "invalid multipart filename"),
ErrorKind::Generic(error) => write!(f, "{}", error),
}
}
}
Expand Down
1 change: 1 addition & 0 deletions lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod util;

pub use self::api::Api;
pub use self::errors::Error;
pub use self::errors::ErrorKind;
pub use prelude::*;
pub use stream::UpdatesStream;
pub use types::*;
21 changes: 21 additions & 0 deletions lib/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,18 @@ impl Stream for UpdatesStream {
.allowed_updates(&ref_mut.allowed_updates);
tracing::trace!(request = ?get_updates, timeout=?timeout, "preparing new request");

#[cfg(feature = "runtime-tokio")]
let request = ref_mut.api.send_timeout(get_updates, timeout);

#[cfg(not(feature = "runtime-tokio"))]
let request = {
let api = ref_mut.api.clone();
async move {
let req = api.clone().send(get_updates).await;
Some(req).transpose()
}
};

ref_mut.current_request = Some(Box::pin(request));
return Poll::Ready(Some(Err(err)));
}
Expand All @@ -115,7 +126,17 @@ impl Stream for UpdatesStream {
.allowed_updates(&ref_mut.allowed_updates);
tracing::trace!(request = ?get_updates, timeout=?timeout, "preparing new request");

#[cfg(feature = "runtime-tokio")]
let request = ref_mut.api.send_timeout(get_updates, timeout);

#[cfg(not(feature = "runtime-tokio"))]
let request = {
let api = ref_mut.api.clone();
async move {
let req = api.send(get_updates).await;
Some(req).transpose()
}
};
ref_mut.current_request = Some(Box::pin(request));

tracing::trace!("executing recursive call");
Expand Down