Skip to content

Commit 34ce004

Browse files
cataggarctaggart
andauthored
add Method & StatusCode to azure_core (#852)
Co-authored-by: Cameron Taggart <[email protected]>
1 parent 433dd83 commit 34ce004

File tree

184 files changed

+345
-382
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

184 files changed

+345
-382
lines changed

sdk/core/src/error/http_error.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,11 @@ impl HttpError {
1818
pub async fn new(response: Response) -> Self {
1919
let status = response.status();
2020
let mut error_code = get_error_code_from_header(&response);
21-
let mut headers = HashMap::new();
22-
23-
for (name, value) in response.headers().iter() {
24-
headers.insert(name.as_str().to_string(), value.as_str().to_string());
25-
}
26-
21+
let headers: HashMap<String, String> = response
22+
.headers()
23+
.iter()
24+
.map(|(name, value)| (name.as_str().to_owned(), value.as_str().to_owned()))
25+
.collect();
2726
let body = response.into_body().await;
2827
error_code = error_code.or_else(|| get_error_code_from_body(&body));
2928
HttpError {

sdk/core/src/error/hyperium_http.rs

Lines changed: 0 additions & 34 deletions
This file was deleted.

sdk/core/src/error/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use std::borrow::Cow;
22
use std::fmt::{Debug, Display};
33
mod http_error;
4-
mod hyperium_http;
54
mod macros;
65
pub use http_error::HttpError;
76

sdk/core/src/headers/mod.rs

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
mod utilities;
33

44
use crate::error::{Error, ErrorKind, ResultExt};
5-
use std::{collections::HashMap, fmt::Debug, str::FromStr};
5+
use std::{fmt::Debug, str::FromStr};
66
pub use utilities::*;
77

88
/// A trait for converting a type into request headers
@@ -152,22 +152,6 @@ impl From<std::collections::HashMap<HeaderName, HeaderValue>> for Headers {
152152
}
153153
}
154154

155-
impl From<&http::HeaderMap> for Headers {
156-
fn from(map: &http::HeaderMap) -> Self {
157-
let map = map
158-
.into_iter()
159-
.map(|(k, v)| {
160-
let key = k.as_str().to_owned();
161-
let value = std::str::from_utf8(v.as_bytes())
162-
.expect("non-UTF8 header value")
163-
.to_owned();
164-
(key.into(), value.into())
165-
})
166-
.collect::<HashMap<HeaderName, HeaderValue>>();
167-
Self(map)
168-
}
169-
}
170-
171155
/// A header name
172156
#[derive(Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
173157
pub struct HeaderName(std::borrow::Cow<'static, str>);

sdk/core/src/http_client.rs renamed to sdk/core/src/http_client/mod.rs

Lines changed: 7 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
#[cfg(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls"))]
2+
#[cfg(not(target_arch = "wasm32"))]
3+
mod reqwest;
4+
5+
#[cfg(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls"))]
6+
#[cfg(not(target_arch = "wasm32"))]
7+
pub use self::reqwest::*;
18
#[allow(unused_imports)]
29
use crate::error::{Error, ErrorKind, ResultExt};
310
#[allow(unused_imports)]
@@ -10,13 +17,6 @@ use bytes::Bytes;
1017
use futures::TryStreamExt;
1118
use serde::Serialize;
1219

13-
/// Construct a new `HttpClient` with the `reqwest` backend.
14-
#[cfg(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls"))]
15-
#[cfg(not(target_arch = "wasm32"))]
16-
pub fn new_http_client() -> std::sync::Arc<dyn HttpClient> {
17-
std::sync::Arc::new(reqwest::Client::new())
18-
}
19-
2020
/// An HTTP client which can send requests.
2121
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
2222
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
@@ -45,53 +45,6 @@ pub trait HttpClient: Send + Sync + std::fmt::Debug {
4545
}
4646
}
4747

48-
#[cfg(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls"))]
49-
#[cfg(not(target_arch = "wasm32"))]
50-
#[async_trait]
51-
impl HttpClient for reqwest::Client {
52-
async fn execute_request(&self, request: &crate::Request) -> crate::Result<crate::Response> {
53-
let url = request.url().clone();
54-
let mut reqwest_request = self.request(request.method().clone(), url);
55-
for (name, value) in request.headers().iter() {
56-
reqwest_request = reqwest_request.header(name.as_str(), value.as_str());
57-
}
58-
59-
let body = request.body().clone();
60-
61-
let reqwest_request = match body {
62-
Body::Bytes(bytes) => reqwest_request
63-
.body(bytes)
64-
.build()
65-
.context(ErrorKind::Other, "failed to build request")?,
66-
Body::SeekableStream(mut seekable_stream) => {
67-
seekable_stream.reset().await.unwrap(); // TODO: remove unwrap when `HttpError` has been removed
68-
69-
reqwest_request
70-
.body(reqwest::Body::wrap_stream(seekable_stream))
71-
.build()
72-
.context(ErrorKind::Other, "failed to build request")?
73-
}
74-
};
75-
76-
let reqwest_response = self
77-
.execute(reqwest_request)
78-
.await
79-
.context(ErrorKind::Io, "failed to execute request")?;
80-
81-
let status = reqwest_response.status();
82-
let headers = Headers::from(reqwest_response.headers());
83-
let body: PinnedStream = Box::pin(reqwest_response.bytes_stream().map_err(|error| {
84-
Error::full(
85-
ErrorKind::Io,
86-
error,
87-
"error converting `reqwest` request into a byte stream",
88-
)
89-
}));
90-
91-
Ok(crate::Response::new(status, headers, body))
92-
}
93-
}
94-
9548
/// Serialize a type to json.
9649
pub fn to_json<T>(value: &T) -> crate::Result<Bytes>
9750
where

sdk/core/src/http_client/reqwest.rs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
use super::*;
2+
use std::collections::HashMap;
3+
4+
/// Construct a new `HttpClient` with the `reqwest` backend.
5+
pub fn new_http_client() -> std::sync::Arc<dyn HttpClient> {
6+
std::sync::Arc::new(::reqwest::Client::new())
7+
}
8+
9+
#[async_trait]
10+
impl HttpClient for ::reqwest::Client {
11+
async fn execute_request(&self, request: &crate::Request) -> crate::Result<crate::Response> {
12+
let url = request.url().clone();
13+
let mut req = self.request(request.method().clone(), url);
14+
for (name, value) in request.headers().iter() {
15+
req = req.header(name.as_str(), value.as_str());
16+
}
17+
18+
let body = request.body().clone();
19+
20+
let reqwest_request = match body {
21+
Body::Bytes(bytes) => req.body(bytes).build(),
22+
Body::SeekableStream(mut seekable_stream) => {
23+
seekable_stream.reset().await.unwrap(); // TODO: remove unwrap when `HttpError` has been removed
24+
req.body(::reqwest::Body::wrap_stream(seekable_stream))
25+
.build()
26+
}
27+
}
28+
.context(ErrorKind::Other, "failed to build `reqwest` request")?;
29+
30+
let rsp = self
31+
.execute(reqwest_request)
32+
.await
33+
.context(ErrorKind::Io, "failed to execute `reqwest` request")?;
34+
35+
let status = rsp.status();
36+
let headers = to_headers(rsp.headers())?;
37+
let body: PinnedStream = Box::pin(rsp.bytes_stream().map_err(|error| {
38+
Error::full(
39+
ErrorKind::Io,
40+
error,
41+
"error converting `reqwest` request into a byte stream",
42+
)
43+
}));
44+
45+
Ok(crate::Response::new(status, headers, body))
46+
}
47+
}
48+
49+
fn to_headers(map: &::reqwest::header::HeaderMap) -> crate::Result<crate::headers::Headers> {
50+
let map = map
51+
.iter()
52+
.filter_map(|(k, v)| {
53+
let key = k.as_str();
54+
match std::str::from_utf8(v.as_bytes()) {
55+
Ok(value) => Some((
56+
crate::headers::HeaderName::from(key.to_owned()),
57+
crate::headers::HeaderValue::from(value.to_owned()),
58+
)),
59+
Err(_) => {
60+
log::warn!("header value for `{key}` is not utf8");
61+
None
62+
}
63+
}
64+
})
65+
.collect::<HashMap<_, _>>();
66+
Ok(crate::headers::Headers::from(map))
67+
}

sdk/core/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ pub use response::*;
5757
pub use seekable_stream::*;
5858
pub use sleep::sleep;
5959

60+
// re-export important types at crate level
61+
pub use http::Method;
62+
pub use http::StatusCode;
6063
pub use url::Url;
6164

6265
/// A unique identifier for a request.

sdk/core/src/mock/mock_request.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
use crate::Method;
12
use crate::{Body, Request};
2-
use http::Method;
33
use serde::de::Visitor;
44
use serde::ser::{Serialize, SerializeStruct, Serializer};
55
use serde::{Deserialize, Deserializer};

sdk/core/src/mock/mock_response.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
use bytes::Bytes;
2-
use http::StatusCode;
3-
use serde::{Deserialize, Serialize};
4-
use std::collections::BTreeMap;
5-
61
use crate::{
72
collect_pinned_stream, error,
83
headers::{HeaderName, HeaderValue, Headers},
9-
BytesStream, Response,
4+
BytesStream, Response, StatusCode,
105
};
6+
use bytes::Bytes;
7+
use serde::{Deserialize, Serialize};
8+
use std::collections::BTreeMap;
119

1210
#[derive(Debug, Clone, PartialEq)]
1311
pub(crate) struct MockResponse {

sdk/core/src/policies/retry_policies/retry_policy.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
use crate::error::{Error, ErrorKind, HttpError};
22
use crate::policies::{Policy, PolicyResult, Request};
33
use crate::sleep::sleep;
4-
use crate::Context;
5-
4+
use crate::{Context, StatusCode};
65
use chrono::{DateTime, Local};
7-
use http::StatusCode;
86
use std::sync::Arc;
97
use std::time::Duration;
108

0 commit comments

Comments
 (0)