Reqwest: use middleware
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Aode (lion) 2021-12-05 16:53:16 -06:00
parent a1ad76b485
commit 2194d8fc1b
4 changed files with 22 additions and 13 deletions

View file

@ -13,9 +13,10 @@ edition = "2021"
[dependencies] [dependencies]
apub-core = { version = "0.2.0", path = "../apub-core/" } apub-core = { version = "0.2.0", path = "../apub-core/" }
async-trait = "0.1.51" async-trait = "0.1.51"
http-signature-normalization-reqwest = { version = "0.2.1", default-features = false, features = ["digest"] } http-signature-normalization-reqwest = { version = "0.3.0", default-features = false, features = ["digest", "middleware"] }
httpdate = "1.0.2" httpdate = "1.0.2"
reqwest = { version = "0.11.6", default-features = false, features = ["json"] } reqwest = { version = "0.11.6", default-features = false, features = ["json"] }
reqwest-middleware = "0.1.2"
serde = "1" serde = "1"
serde_json = "1" serde_json = "1"
thiserror = "1" thiserror = "1"

View file

@ -12,10 +12,8 @@ use http_signature_normalization_reqwest::{
digest::{DigestCreate, SignExt}, digest::{DigestCreate, SignExt},
prelude::{Sign as _, SignError}, prelude::{Sign as _, SignError},
}; };
use reqwest::{ use reqwest::header::{ACCEPT, CONTENT_TYPE, DATE};
header::{ACCEPT, CONTENT_TYPE, DATE}, use reqwest_middleware::ClientWithMiddleware;
Client,
};
use std::time::SystemTime; use std::time::SystemTime;
use url::Url; use url::Url;
@ -29,6 +27,7 @@ pub use http_signature_normalization_reqwest::Config as SignatureConfig;
/// ```rust /// ```rust
/// use apub_reqwest::{ReqwestClient, SignatureConfig}; /// use apub_reqwest::{ReqwestClient, SignatureConfig};
/// use apub_rustcrypto::Rustcrypto; /// use apub_rustcrypto::Rustcrypto;
/// use reqwest_middleware::ClientBuilder;
/// use rsa::RsaPrivateKey; /// use rsa::RsaPrivateKey;
/// ///
/// fn main() -> Result<(), Box<dyn std::error::Error>> { /// fn main() -> Result<(), Box<dyn std::error::Error>> {
@ -37,13 +36,14 @@ pub use http_signature_normalization_reqwest::Config as SignatureConfig;
/// let signature_config = SignatureConfig::default(); /// let signature_config = SignatureConfig::default();
/// ///
/// let client = reqwest::Client::new(); /// let client = reqwest::Client::new();
/// let client = ClientBuilder::new(client).build();
/// ///
/// let reqwest_client = ReqwestClient::new(client, signature_config, &crypto); /// let reqwest_client = ReqwestClient::new(client, signature_config, &crypto);
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
pub struct ReqwestClient<Crypto> { pub struct ReqwestClient<Crypto> {
client: Client, client: ClientWithMiddleware,
config: SignatureConfig, config: SignatureConfig,
crypto: Crypto, crypto: Crypto,
} }
@ -75,6 +75,10 @@ pub enum ReqwestError<E: std::error::Error + Send> {
#[error(transparent)] #[error(transparent)]
Reqwest(#[from] reqwest::Error), Reqwest(#[from] reqwest::Error),
/// Middleware errors
#[error(transparent)]
Middleware(#[from] reqwest_middleware::Error),
/// Failed to serialize the json request body /// Failed to serialize the json request body
#[error(transparent)] #[error(transparent)]
Json(#[from] serde_json::Error), Json(#[from] serde_json::Error),
@ -109,7 +113,7 @@ where
SignTraitError<Crypto>: std::error::Error, SignTraitError<Crypto>: std::error::Error,
{ {
/// Create a new Client & Repo implementation backed by the reqwest client /// Create a new Client & Repo implementation backed by the reqwest client
pub fn new(client: Client, config: SignatureConfig, crypto: Crypto) -> Self { pub fn new(client: ClientWithMiddleware, config: SignatureConfig, crypto: Crypto) -> Self {
Self { Self {
client, client,
config, config,
@ -124,7 +128,7 @@ where
where where
Id: Dereference, Id: Dereference,
{ {
let response = self let request = self
.client .client
.get(url.as_str()) .get(url.as_str())
.header(ACCEPT, "application/activity+json") .header(ACCEPT, "application/activity+json")
@ -133,9 +137,9 @@ where
let sign = self.crypto.signer(); let sign = self.crypto.signer();
move |signing_string| sign.sign(signing_string).map_err(SignatureError::Signer) move |signing_string| sign.sign(signing_string).map_err(SignatureError::Signer)
})? })?;
.send()
.await?; let response = self.client.execute(request).await?;
Ok(Some(response.json().await?)) Ok(Some(response.json().await?))
} }
@ -177,7 +181,7 @@ where
async move { async move {
let activity_string = serde_json::to_string(activity)?; let activity_string = serde_json::to_string(activity)?;
let response = self let request = self
.client .client
.post(inbox.as_str()) .post(inbox.as_str())
.header(CONTENT_TYPE, "application/activity+json") .header(CONTENT_TYPE, "application/activity+json")
@ -197,6 +201,8 @@ where
) )
.await?; .await?;
let response = self.client.execute(request).await?;
if !response.status().is_success() { if !response.status().is_success() {
return Err(ReqwestError::Status(response.status().as_u16())); return Err(ReqwestError::Status(response.status().as_u16()));
} }

View file

@ -10,4 +10,5 @@ apub = { version = "0.2.0", path = "../../", features = ["with-reqwest", "with-o
example-types = { version = "0.1.0", path = "../example-types/" } example-types = { version = "0.1.0", path = "../example-types/" }
openssl = "0.10.13" openssl = "0.10.13"
reqwest = "0.11.6" reqwest = "0.11.6"
reqwest-middleware = "0.1.2"
tokio = { version = "1.14.0", features = ["full"] } tokio = { version = "1.14.0", features = ["full"] }

View file

@ -6,6 +6,7 @@ use apub::{
}; };
use example_types::{object_id, NoteType, ObjectId}; use example_types::{object_id, NoteType, ObjectId};
use openssl::{pkey::PKey, rsa::Rsa}; use openssl::{pkey::PKey, rsa::Rsa};
use reqwest_middleware::ClientBuilder;
use std::time::Duration; use std::time::Duration;
#[tokio::main] #[tokio::main]
@ -17,7 +18,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut breakers = BreakerSession::limit(10, Duration::from_secs(60 * 60)); let mut breakers = BreakerSession::limit(10, Duration::from_secs(60 * 60));
let mut session = (RequestCountSession::max(30), &mut breakers); let mut session = (RequestCountSession::max(30), &mut breakers);
let client = reqwest::Client::new(); let client = ClientBuilder::new(reqwest::Client::new()).build();
let reqwest_client = ReqwestClient::new(client, config, &crypto); let reqwest_client = ReqwestClient::new(client, config, &crypto);