delopay 0.2.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The transport boundary. Everything above this line is backend-independent.

use std::fmt;
use std::future::Future;
use std::pin::Pin;

/// HTTP method. Only the verbs this SDK issues.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HttpMethod {
    Get,
    Post,
    Put,
    Delete,
}

impl HttpMethod {
    // Only called from `mock.rs`, which is `#[cfg(test)]`-gated, so this is
    // genuinely dead code outside test builds — not a stale carry-over.
    #[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",
        }
    }

    /// Whether the verb is safe to replay without an idempotency key.
    ///
    /// `DELETE` and `PUT` are idempotent per HTTP semantics but are
    /// deliberately reported as `false` here: `DELETE` to preserve the SDK's
    /// existing retry behavior, and `PUT` because this API uses it for
    /// state-transition endpoints (e.g. payout updates) where a blind replay
    /// is not provably safe.
    pub(crate) fn is_inherently_idempotent(self) -> bool {
        matches!(self, HttpMethod::Get)
    }
}

/// Why a transport-level request failed, classified by the backend so the
/// retry policy above stays backend-independent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TransportErrorKind {
    Timeout,
    Connect,
    Request,
    /// Reading the response body failed after a successful (2xx) response.
    /// Deliberately excluded from `is_retriable`: the pre-refactor client
    /// never retried a 2xx body-read failure (it propagated `resp.bytes()`
    /// errors directly), and retrying here would mean re-issuing a request
    /// whose original attempt may have already taken effect server-side.
    Body,
    Other,
}

/// A transport-level failure: no HTTP response was obtained.
#[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
        )
    }
}

/// A fully-built request, ready to send.
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]>,
}

// Hand-written rather than derived: `headers` carries `api-key` and
// `idempotency-key` values verbatim, and `body` can carry customer PII.
// `Transport` requires `Debug`, and mock transports in tests make a
// `dbg!(&req)` or a `{req:?}` in an assertion message genuinely likely, so
// this redacts sensitive values instead of relying on callers never
// formatting the request.
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();
        // Query *values* can carry customer-identifying data (e.g. the
        // `customer_id` filter on payment list calls), so only the parameter
        // names are printed.
        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()
    }
}

/// A raw HTTP response. Header parsing stays above the transport so each
/// backend does not re-implement it.
#[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,
        }
    }

    /// Case-insensitive header lookup.
    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)
    }
}

/// An HTTP backend.
///
/// Boxed rather than generic: `Inner` stores `Arc<dyn Transport>`, and a
/// generic `Delopay<T>` would leak a type parameter into every public
/// signature. `async fn` in traits is stable since 1.75 but not dyn-compatible.
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() {
        // PUT and DELETE are idempotent in HTTP semantics but deliberately not
        // here (see the method's doc comment): a mutation flipping either to
        // `true` would let `send_raw` replay state-transition calls without an
        // idempotency key.
        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() {
        // This is the crux of Fix 1: a body-read failure on a 2xx response
        // must never be retried, or `send_raw` would re-issue a request the
        // pre-refactor client never retried (retry drift). Network-level
        // failures (no response obtained at all) must still be retriable.
        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}"
        );
    }
}