Skip to content

Commit

Permalink
Merge pull request #528 from mzeitlin11/client_cleanups
Browse files Browse the repository at this point in the history
Simplify client, remove some allocations
  • Loading branch information
arlyon authored Apr 6, 2024
2 parents d295678 + cff37d3 commit 562c493
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 40 deletions.
14 changes: 8 additions & 6 deletions async-stripe/src/client/headers.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::{Display, Formatter};

use crate::AccountId;
use crate::ApiVersion;
use crate::ApplicationId;
Expand All @@ -9,16 +11,16 @@ pub struct AppInfo {
pub version: Option<String>,
}

impl ToString for AppInfo {
impl Display for AppInfo {
/// Formats a plugin's 'App Info' into a string that can be added to the end of an User-Agent string.
///
/// This formatting matches that of other libraries, and if changed then it should be changed everywhere.
fn to_string(&self) -> String {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match (&self.version, &self.url) {
(Some(a), Some(b)) => format!("{}/{} ({})", &self.name, a, b),
(Some(a), None) => format!("{}/{}", &self.name, a),
(None, Some(b)) => format!("{} ({})", &self.name, b),
_ => self.name.to_string(),
(Some(a), Some(b)) => write!(f, "{}/{a} ({b})", &self.name),
(Some(a), None) => write!(f, "{}/{a}", &self.name),
(None, Some(b)) => write!(f, "{} ({b})", &self.name),

Check warning on line 22 in async-stripe/src/client/headers.rs

View check run for this annotation

Codecov / codecov/patch

async-stripe/src/client/headers.rs#L21-L22

Added lines #L21 - L22 were not covered by tests
_ => f.write_str(&self.name),
}
}
}
Expand Down
21 changes: 7 additions & 14 deletions async-stripe/src/client/stripe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ pub struct Client {
secret_key: String,
headers: Headers,
strategy: RequestStrategy,
app_info: Option<AppInfo>,
api_base: Url,
api_root: String,
}

impl Client {
Expand All @@ -44,9 +42,7 @@ impl Client {
stripe_account: None,
},
strategy: RequestStrategy::Once,
app_info: None,
api_base: Url::parse(url.into()).expect("invalid url"),
api_root: "v1".to_string(),
}
}

Expand Down Expand Up @@ -80,8 +76,7 @@ impl Client {
url: Option<String>,
) -> Self {
let app_info = AppInfo { name, version, url };
self.headers.user_agent = format!("{} {}", USER_AGENT, app_info.to_string());
self.app_info = Some(app_info);
self.headers.user_agent = format!("{USER_AGENT} {app_info}");
self
}

Expand Down Expand Up @@ -156,9 +151,8 @@ impl Client {
return err(StripeError::QueryStringSerialize(qs_ser_err));
}

let body = std::str::from_utf8(params_buffer.as_slice())
.expect("Unable to extract string from params_buffer")
.to_string();
let body =
String::from_utf8(params_buffer).expect("Unable to extract string from params_buffer");

req.set_body(Body::from_string(body));

Expand All @@ -168,7 +162,7 @@ impl Client {

fn url(&self, path: &str) -> Url {
let mut url = self.api_base.clone();
url.set_path(&format!("{}/{}", self.api_root, path.trim_start_matches('/')));
url.set_path(&format!("v1/{}", path.trim_start_matches('/')));
url
}

Expand All @@ -179,17 +173,16 @@ impl Client {
let qs_ser = &mut serde_qs::Serializer::new(&mut params_buffer);
serde_path_to_error::serialize(&params, qs_ser).map_err(StripeError::from)?;

let params = std::str::from_utf8(params_buffer.as_slice())
.expect("Unable to extract string from params_buffer")
.to_string();
let params =
String::from_utf8(params_buffer).expect("Unable to extract string from params_buffer");

url.set_query(Some(&params));
Ok(url)
}

fn create_request(&self, method: Method, url: Url) -> Request {
let mut req = Request::new(method, url);
req.insert_header("authorization", &format!("Bearer {}", self.secret_key));
req.insert_header("authorization", format!("Bearer {}", self.secret_key));

for (key, value) in self.headers.to_array().iter().filter_map(|(k, v)| v.map(|v| (*k, v))) {
req.insert_header(key, value);
Expand Down
4 changes: 1 addition & 3 deletions openapi/src/url_finder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ impl UrlFinder {
}

pub fn url_for_object(&self, object: &str) -> Option<String> {
let Some(unprefixed_link) = self.doc_links.get(object) else {
return None;
};
let unprefixed_link = self.doc_links.get(object)?;
Some(format!("https://stripe.com/docs/api{}", unprefixed_link))
}
}
Expand Down
35 changes: 18 additions & 17 deletions stripe_webhook/src/webhook.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::collections::HashMap;
use std::str::FromStr;

use chrono::Utc;
Expand Down Expand Up @@ -138,22 +137,24 @@ struct Signature<'r> {

impl<'r> Signature<'r> {
fn parse(raw: &'r str) -> Result<Signature<'r>, WebhookError> {
let headers: HashMap<&str, &str> = raw
.split(',')
.map(|header| {
let mut key_and_value = header.split('=');
let key = key_and_value.next();
let value = key_and_value.next();
(key, value)
})
.filter_map(|(key, value)| match (key, value) {
(Some(key), Some(value)) => Some((key, value)),
_ => None,
})
.collect();
let t = headers.get("t").ok_or(WebhookError::BadSignature)?;
let v1 = headers.get("v1").ok_or(WebhookError::BadSignature)?;
Ok(Signature { t: t.parse::<i64>().map_err(WebhookError::BadHeader)?, v1 })
let mut t: Option<i64> = None;
let mut v1: Option<&'r str> = None;
for pair in raw.split(',') {
let (key, val) = pair.split_once('=').ok_or(WebhookError::BadSignature)?;
match key {
"t" => {
t = Some(val.parse().map_err(WebhookError::BadHeader)?);
}
"v1" => {
v1 = Some(val);
}
_ => {}
}
}
Ok(Signature {
t: t.ok_or(WebhookError::BadSignature)?,
v1: v1.ok_or(WebhookError::BadSignature)?,
})
}
}

Expand Down

0 comments on commit 562c493

Please sign in to comment.