use std::fmt;
use std::future::Future;
use std::pin::Pin;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HttpMethod {
Get,
Post,
Put,
Delete,
}
impl HttpMethod {
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn as_str(self) -> &'static str {
match self {
HttpMethod::Get => "GET",
HttpMethod::Post => "POST",
HttpMethod::Put => "PUT",
HttpMethod::Delete => "DELETE",
}
}
pub(crate) fn is_inherently_idempotent(self) -> bool {
matches!(self, HttpMethod::Get)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TransportErrorKind {
Timeout,
Connect,
Request,
Body,
Other,
}
#[derive(Debug)]
pub(crate) struct TransportError {
pub kind: TransportErrorKind,
pub source: Box<dyn std::error::Error + Send + Sync>,
}
impl TransportError {
pub(crate) fn is_retriable(&self) -> bool {
matches!(
self.kind,
TransportErrorKind::Timeout | TransportErrorKind::Connect | TransportErrorKind::Request
)
}
}
pub(crate) struct RawRequest<'a> {
pub method: HttpMethod,
pub url: &'a str,
pub headers: &'a [(&'a str, &'a str)],
pub query: &'a [(&'a str, String)],
pub body: Option<&'a [u8]>,
}
impl fmt::Debug for RawRequest<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let headers: Vec<(&str, &str)> = self
.headers
.iter()
.map(|(k, v)| {
if k.eq_ignore_ascii_case("api-key") || k.eq_ignore_ascii_case("idempotency-key") {
(*k, "[redacted]")
} else {
(*k, *v)
}
})
.collect();
let query_keys: Vec<&str> = self.query.iter().map(|(k, _)| *k).collect();
f.debug_struct("RawRequest")
.field("method", &self.method)
.field("url", &self.url)
.field("headers", &headers)
.field("query_keys", &query_keys)
.field("body_len", &self.body.map(<[u8]>::len))
.finish()
}
}
#[derive(Debug)]
pub(crate) struct RawResponse {
pub status: u16,
headers: Vec<(Box<str>, Box<str>)>,
pub body: Vec<u8>,
}
impl RawResponse {
pub(crate) fn new(status: u16, headers: Vec<(Box<str>, Box<str>)>, body: Vec<u8>) -> Self {
Self {
status,
headers,
body,
}
}
pub(crate) fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| &**v)
}
pub(crate) fn is_success(&self) -> bool {
(200..300).contains(&self.status)
}
pub(crate) fn is_server_error(&self) -> bool {
(500..600).contains(&self.status)
}
}
pub(crate) trait Transport: fmt::Debug + Send + Sync {
fn execute<'a>(
&'a self,
req: RawRequest<'a>,
) -> Pin<Box<dyn Future<Output = Result<RawResponse, TransportError>> + Send + 'a>>;
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
struct FakeError;
impl fmt::Display for FakeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "fake error")
}
}
impl std::error::Error for FakeError {}
fn error_of(kind: TransportErrorKind) -> TransportError {
TransportError {
kind,
source: Box::new(FakeError),
}
}
#[test]
fn only_get_is_inherently_idempotent() {
assert!(HttpMethod::Get.is_inherently_idempotent());
assert!(!HttpMethod::Post.is_inherently_idempotent());
assert!(!HttpMethod::Put.is_inherently_idempotent());
assert!(!HttpMethod::Delete.is_inherently_idempotent());
}
#[test]
fn body_read_failure_is_not_retriable_but_network_errors_are() {
assert!(!error_of(TransportErrorKind::Body).is_retriable());
assert!(error_of(TransportErrorKind::Timeout).is_retriable());
assert!(error_of(TransportErrorKind::Connect).is_retriable());
assert!(error_of(TransportErrorKind::Request).is_retriable());
}
#[test]
fn raw_request_debug_redacts_api_key() {
let headers = [
("api-key", "prd_super_secret"),
("idempotency-key", "idem_also_secret"),
("accept", "application/json"),
];
let query = [("customer_id", "cus_private_person".to_string())];
let req = RawRequest {
method: HttpMethod::Get,
url: "https://api.delopay.net/v1/payments",
headers: &headers,
query: &query,
body: Some(b"{\"amount\":1999}"),
};
let formatted = format!("{req:?}");
assert!(
!formatted.contains("prd_super_secret"),
"debug output must not contain the secret api key: {formatted}"
);
assert!(
!formatted.contains("idem_also_secret"),
"debug output must not contain the idempotency key: {formatted}"
);
assert!(
!formatted.contains("cus_private_person"),
"debug output must not contain query values, which carry PII: {formatted}"
);
assert!(
!formatted.contains("1999"),
"debug output must not contain the request body: {formatted}"
);
assert!(
formatted.contains("api-key") && formatted.contains("customer_id"),
"header and query parameter *names* stay visible for debugging: {formatted}"
);
}
}