Skip to content

Commit

Permalink
feat(auth): remove VERB ,use http::Method
Browse files Browse the repository at this point in the history
减少一些转化操作
  • Loading branch information
tu6ge committed Dec 10, 2022
1 parent 3a1558c commit 06ed16b
Show file tree
Hide file tree
Showing 12 changed files with 102 additions and 283 deletions.
4 changes: 2 additions & 2 deletions examples/head_object.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use aliyun_oss_client::{errors::OssError, file::AlignBuilder, Client};
use aliyun_oss_client::{errors::OssError, file::AlignBuilder, Client, Method};
use dotenv::dotenv;

#[tokio::main]
Expand All @@ -14,7 +14,7 @@ pub async fn main() -> Result<(), OssError> {
"Sat, 01 Jan 2022 18:01:01 GMT".parse().unwrap(),
)];

let builder = client.builder_with_header("HEAD", url, resource, headers)?;
let builder = client.builder_with_header(Method::HEAD, url, resource, headers)?;

let response = builder.send().await?;

Expand Down
119 changes: 12 additions & 107 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,11 @@ use reqwest::Method;
use std::convert::TryInto;
use thiserror::Error;

#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Debug))]
#[non_exhaustive]
pub struct VERB(pub Method);

#[derive(Default, Clone)]
pub struct Auth {
access_key_id: KeyId,
access_key_secret: KeySecret,
verb: VERB,
method: Method,
content_md5: Option<ContentMd5>,
date: Date,
// pub canonicalized_oss_headers: &'a str, // TODO
Expand All @@ -39,8 +34,8 @@ impl Auth {
fn set_secret(&mut self, secret: KeySecret) {
self.access_key_secret = secret;
}
fn set_verb(&mut self, verb: VERB) {
self.verb = verb;
fn set_method(&mut self, method: Method) {
self.method = method;
}
fn set_content_md5(&mut self, content_md5: ContentMd5) {
self.content_md5 = Some(content_md5)
Expand Down Expand Up @@ -86,102 +81,12 @@ impl Auth {
}
}

impl VERB {
/// GET
pub const GET: VERB = VERB(Method::GET);

/// POST
pub const POST: VERB = VERB(Method::POST);

/// PUT
pub const PUT: VERB = VERB(Method::PUT);

/// DELETE
pub const DELETE: VERB = VERB(Method::DELETE);

/// HEAD
pub const HEAD: VERB = VERB(Method::HEAD);

/// OPTIONS
pub const OPTIONS: VERB = VERB(Method::OPTIONS);

/// CONNECT
pub const CONNECT: VERB = VERB(Method::CONNECT);

/// PATCH
pub const PATCH: VERB = VERB(Method::PATCH);

/// TRACE
pub const TRACE: VERB = VERB(Method::TRACE);

#[inline]
pub fn to_string(&self) -> String {
self.0.to_string()
}
}

impl TryInto<HeaderValue> for VERB {
type Error = AuthError;
fn try_into(self) -> AuthResult<HeaderValue> {
self.0
.to_string()
.parse::<HeaderValue>()
.map_err(AuthError::from)
}
}

impl From<VERB> for String {
fn from(verb: VERB) -> Self {
match verb.0 {
Method::GET => "GET".into(),
Method::POST => "POST".into(),
Method::PUT => "PUT".into(),
Method::DELETE => "DELETE".into(),
Method::HEAD => "HEAD".into(),
Method::OPTIONS => "OPTIONS".into(),
Method::CONNECT => "CONNECT".into(),
Method::PATCH => "PATCH".into(),
Method::TRACE => "TRACE".into(),
_ => panic!("undefined verb type"),
}
}
}

impl From<&str> for VERB {
fn from(str: &str) -> Self {
match str {
"POST" => VERB(Method::POST),
"GET" => VERB(Method::GET),
"PUT" => VERB(Method::PUT),
"DELETE" => VERB(Method::DELETE),
"HEAD" => VERB(Method::HEAD),
"OPTIONS" => VERB(Method::OPTIONS),
"CONNECT" => VERB(Method::CONNECT),
"PATCH" => VERB(Method::PATCH),
"TRACE" => VERB(Method::TRACE),
_ => panic!("undefined verb type"),
}
}
}

impl Into<Method> for VERB {
fn into(self) -> Method {
self.0
}
}

impl Default for VERB {
fn default() -> Self {
Self::GET
}
}

#[cfg_attr(test, automock)]
pub(crate) trait AuthToHeaderMap {
fn get_original_header(&self) -> HeaderMap;
fn get_header_key(&self) -> AuthResult<HeaderValue>;
fn get_header_secret(&self) -> AuthResult<HeaderValue>;
fn get_header_verb(&self) -> AuthResult<HeaderValue>;
fn get_header_method(&self) -> AuthResult<HeaderValue>;
fn get_header_md5(&self) -> AuthResult<Option<HeaderValue>>;
fn get_header_date(&self) -> AuthResult<HeaderValue>;
fn get_header_resource(&self) -> AuthResult<HeaderValue>;
Expand All @@ -199,8 +104,8 @@ impl AuthToHeaderMap for Auth {
let val: HeaderValue = self.access_key_secret.as_ref().try_into()?;
Ok(val)
}
fn get_header_verb(&self) -> AuthResult<HeaderValue> {
let val: HeaderValue = self.verb.clone().try_into()?;
fn get_header_method(&self) -> AuthResult<HeaderValue> {
let val: HeaderValue = self.method.as_str().try_into()?;
Ok(val)
}
fn get_header_md5(&self) -> AuthResult<Option<HeaderValue>> {
Expand Down Expand Up @@ -261,7 +166,7 @@ pub(crate) trait AuthSignString {
) -> (
&KeyId,
&KeySecret,
&VERB,
&Method,
ContentMd5,
ContentType,
&Date,
Expand All @@ -276,7 +181,7 @@ impl AuthSignString for Auth {
) -> (
&KeyId,
&KeySecret,
&VERB,
&Method,
ContentMd5,
ContentType,
&Date,
Expand All @@ -285,7 +190,7 @@ impl AuthSignString for Auth {
(
&self.access_key_id,
&self.access_key_secret,
&self.verb,
&self.method,
self.content_md5.clone().unwrap_or(ContentMd5::default()),
match self.headers.get(CONTENT_TYPE) {
Some(ct) => ct.to_owned().try_into().unwrap(),
Expand Down Expand Up @@ -338,7 +243,7 @@ impl AuthHeader for HeaderMap {

map.insert(ACCESS_KEY_ID, auth.get_header_key()?);
map.insert(SECRET_ACCESS_KEY, auth.get_header_secret()?);
map.insert(VERB_IDENT, auth.get_header_verb()?);
map.insert(VERB_IDENT, auth.get_header_method()?);

if let Some(a) = auth.get_header_md5()? {
map.insert(CONTENT_MD5, a);
Expand Down Expand Up @@ -556,8 +461,8 @@ impl AuthBuilder {
}

/// 给 verb 赋值
pub fn verb(&mut self, verb: &VERB) {
self.auth.set_verb(verb.to_owned());
pub fn method(&mut self, method: &Method) {
self.auth.set_method(method.to_owned());
}

/// 给 content_md5 赋值
Expand Down
6 changes: 3 additions & 3 deletions src/blocking/builder.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::auth::VERB;
use crate::builder::BuilderError;
use http::Method;
use reqwest::blocking::{self, Body, Request, Response};
use reqwest::{
header::{HeaderMap, HeaderName, HeaderValue},
Expand All @@ -25,9 +25,9 @@ impl ClientWithMiddleware {
}
}

pub fn request<U: IntoUrl>(&self, method: VERB, url: U) -> RequestBuilder {
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
RequestBuilder {
inner: self.inner.request(method.into(), url),
inner: self.inner.request(method, url),
middleware: self.middleware.clone(),
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/bucket.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::auth::VERB;
#[cfg(feature = "blocking")]
use crate::builder::RcPointer;
use crate::builder::{ArcPointer, BuilderError, PointerFamily};
Expand All @@ -17,6 +16,7 @@ use crate::types::{
};
use crate::BucketName;
use chrono::prelude::*;
use http::Method;
use oss_derive::oss_gen_rc;
use std::error::Error;
use std::fmt;
Expand Down Expand Up @@ -231,7 +231,7 @@ impl Bucket {

let (bucket_url, resource) = bucket_arc.get_url_resource(&query);

let response = self.builder(VERB::GET, bucket_url, resource)?;
let response = self.builder(Method::GET, bucket_url, resource)?;
let content = response.send_adjust_error().await?;

list.from_xml(
Expand Down Expand Up @@ -270,7 +270,7 @@ impl Bucket<RcPointer> {

let (bucket_url, resource) = bucket_arc.get_url_resource(&query);

let response = self.builder(VERB::GET, bucket_url, resource)?;
let response = self.builder(Method::GET, bucket_url, resource)?;
let content = response.send_adjust_error()?;

list.from_xml(&content.text().map_err(BuilderError::from)?, init_object)?;
Expand Down Expand Up @@ -388,7 +388,7 @@ impl ClientArc {

let canonicalized = CanonicalizedResource::default();

let response = self.builder(VERB::GET, url, canonicalized)?;
let response = self.builder(Method::GET, url, canonicalized)?;
let content = response.send_adjust_error().await?;

list.from_xml(
Expand Down Expand Up @@ -428,7 +428,7 @@ impl ClientArc {

let canonicalized = CanonicalizedResource::from_bucket(&self.get_bucket_base(), query);

let response = self.builder(VERB::GET, bucket_url, canonicalized)?;
let response = self.builder(Method::GET, bucket_url, canonicalized)?;
let content = response.send_adjust_error().await?;

bucket.from_xml(&content.text().await.map_err(BuilderError::from)?)?;
Expand Down Expand Up @@ -472,7 +472,7 @@ impl ClientRc {

let canonicalized = CanonicalizedResource::default();

let response = self.builder(VERB::GET, url, canonicalized)?;
let response = self.builder(Method::GET, url, canonicalized)?;
let content = response.send_adjust_error()?;

list.from_xml(&content.text().map_err(BuilderError::from)?, init_bucket)?;
Expand Down Expand Up @@ -509,7 +509,7 @@ impl ClientRc {

let canonicalized = CanonicalizedResource::from_bucket(&self.get_bucket_base(), query);

let response = self.builder(VERB::GET, bucket_url, canonicalized)?;
let response = self.builder(Method::GET, bucket_url, canonicalized)?;
let content = response.send_adjust_error()?;

bucket.from_xml(&content.text().map_err(BuilderError::from)?)?;
Expand Down
11 changes: 4 additions & 7 deletions src/builder.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use async_trait::async_trait;
use http::Method;
use reqwest::{
header::{HeaderMap, HeaderName, HeaderValue},
Body, IntoUrl,
Expand All @@ -10,11 +11,7 @@ use thiserror::Error;

#[cfg(feature = "blocking")]
use crate::blocking::builder::ClientWithMiddleware as BlockingClientWithMiddleware;
use crate::{
auth::{AuthError, VERB},
client::Client as AliClient,
config::BucketBase,
};
use crate::{auth::AuthError, client::Client as AliClient, config::BucketBase};
use reqwest::{Client, Request, Response};

pub trait PointerFamily
Expand Down Expand Up @@ -61,9 +58,9 @@ impl ClientWithMiddleware {
}
}

pub fn request<U: IntoUrl>(&self, method: VERB, url: U) -> RequestBuilder {
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
RequestBuilder {
inner: self.inner.request(method.into(), url),
inner: self.inner.request(method, url),
middleware: self.middleware.clone(),
}
}
Expand Down
17 changes: 8 additions & 9 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::auth::{AuthBuilder, AuthGetHeader, VERB};
use crate::auth::{AuthBuilder, AuthGetHeader};
#[cfg(feature = "blocking")]
use crate::blocking::builder::ClientWithMiddleware as BlockingClientWithMiddleware;
#[cfg(test)]
Expand All @@ -9,7 +9,7 @@ use crate::file::AlignBuilder;
use crate::types::{BucketName, CanonicalizedResource, EndPoint, KeyId, KeySecret};
use chrono::prelude::*;
use http::header::HeaderName;
use http::HeaderValue;
use http::{HeaderValue, Method};
use reqwest::header::HeaderMap;
use reqwest::Url;
use std::env;
Expand Down Expand Up @@ -156,16 +156,15 @@ impl AlignBuilder for Client<ClientWithMiddleware> {
/// builder 方法的异步实现
/// 带 header 参数
#[inline]
fn builder_with_header<M: Into<VERB>, H: IntoIterator<Item = (HeaderName, HeaderValue)>>(
fn builder_with_header<H: IntoIterator<Item = (HeaderName, HeaderValue)>>(
&self,
method: M,
method: Method,
url: Url,
resource: CanonicalizedResource,
headers: H,
) -> Result<RequestBuilder, BuilderError> {
let method = method.into();
let mut auth_builder = self.auth_builder.clone();
auth_builder.verb(&method);
auth_builder.method(&method);
auth_builder.date(now().into());
auth_builder.canonicalized_resource(resource);
auth_builder.extend_headers(HeaderMap::from_iter(headers));
Expand Down Expand Up @@ -210,16 +209,16 @@ impl crate::file::blocking::AlignBuilder for Client<BlockingClientWithMiddleware
///
/// 返回后,可以再加请求参数,然后可选的进行发起请求
#[inline]
fn builder_with_header<M: Into<VERB>, H: IntoIterator<Item = (HeaderName, HeaderValue)>>(
fn builder_with_header<H: IntoIterator<Item = (HeaderName, HeaderValue)>>(
&self,
method: M,
method: Method,
url: Url,
resource: CanonicalizedResource,
headers: H,
) -> Result<BlockingRequestBuilder, BuilderError> {
let method = method.into();
let mut auth_builder = self.auth_builder.clone();
auth_builder.verb(&method);
auth_builder.method(&method);
auth_builder.date(now().into());
auth_builder.canonicalized_resource(resource);
auth_builder.extend_headers(HeaderMap::from_iter(headers));
Expand Down
Loading

0 comments on commit 06ed16b

Please sign in to comment.