r402-http 0.13.0

HTTP transport layer for the x402 payment protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! A [`r402::facilitator::Facilitator`] implementation that interacts with a _remote_ x402 Facilitator over HTTP.
//!
//! This [`FacilitatorClient`] handles the `/verify`, `/settle`, and `/supported` endpoints of a remote facilitator,
//! and implements the [`r402::facilitator::Facilitator`] trait for compatibility
//! with x402-based middleware and logic.
//!
//! ## Features
//!
//! - Uses `reqwest` for async HTTP requests
//! - Supports optional timeout and headers
//! - Integrates with `tracing` if the `telemetry` feature is enabled
//!
//! ## Error Handling
//!
//! Custom error types capture detailed failure contexts, including
//! - URL construction
//! - HTTP transport failures
//! - JSON deserialization errors
//! - Unexpected HTTP status responses
//!

use std::fmt::Display;
use std::sync::Arc;
use std::time::Duration;

use http::{HeaderMap, StatusCode};
use r402::facilitator::{BoxFuture, Facilitator, FacilitatorError};
use r402::proto::{
    SettleRequest, SettleResponse, SupportedResponse, VerifyRequest, VerifyResponse,
};
use reqwest::Client;
use tokio::sync::RwLock;
#[cfg(feature = "telemetry")]
use tracing::{Instrument, Span, instrument};
use url::Url;

/// TTL cache for [`SupportedResponse`].
#[derive(Clone, Debug)]
struct SupportedCacheState {
    /// The cached response
    response: SupportedResponse,
    /// When the cache expires
    expires_at: std::time::Instant,
}

/// An encapsulated TTL cache for the `/supported` endpoint response.
///
/// Clones share the same cache state via `Arc`, so cached responses are
/// visible across all clones (e.g. when the middleware clones the
/// facilitator per-request).
#[derive(Debug, Clone)]
pub struct SupportedCache {
    /// TTL for the cache
    ttl: Duration,
    /// Shared cache state (`Arc<RwLock>` so clones hit the same cache)
    state: Arc<RwLock<Option<SupportedCacheState>>>,
}

impl SupportedCache {
    /// Creates a new cache with the given TTL.
    #[must_use]
    pub fn new(ttl: Duration) -> Self {
        Self {
            ttl,
            state: Arc::new(RwLock::new(None)),
        }
    }

    /// Returns the cached response if valid, None otherwise.
    #[allow(
        clippy::significant_drop_tightening,
        reason = "read guard scope matches data access"
    )]
    pub async fn get(&self) -> Option<SupportedResponse> {
        let guard = self.state.read().await;
        let cache = guard.as_ref()?;
        if std::time::Instant::now() < cache.expires_at {
            Some(cache.response.clone())
        } else {
            None
        }
    }

    /// Stores a response in the cache with the configured TTL.
    pub async fn set(&self, response: SupportedResponse) {
        let mut guard = self.state.write().await;
        *guard = Some(SupportedCacheState {
            response,
            expires_at: std::time::Instant::now() + self.ttl,
        });
    }

    /// Clears the cache.
    pub async fn clear(&self) {
        let mut guard = self.state.write().await;
        *guard = None;
    }
}

/// A client for communicating with a remote x402 facilitator.
///
/// Handles `/verify`, `/settle`, and `/supported` endpoints via JSON HTTP.
#[derive(Clone, Debug)]
pub struct FacilitatorClient {
    /// Base URL of the facilitator (e.g. `https://facilitator.example/`)
    base_url: Url,
    /// Full URL to `POST /verify` requests
    verify_url: Url,
    /// Full URL to `POST /settle` requests
    settle_url: Url,
    /// Full URL to `GET /supported` requests
    supported_url: Url,
    /// Shared Reqwest HTTP client
    client: Client,
    /// Optional custom headers sent with each request
    headers: HeaderMap,
    /// Optional request timeout
    timeout: Option<Duration>,
    /// Cache for the supported endpoint response
    supported_cache: SupportedCache,
}

/// Errors that can occur while interacting with a remote facilitator.
#[derive(Debug, thiserror::Error)]
pub enum FacilitatorClientError {
    /// URL parse error.
    #[error("URL parse error: {context}: {source}")]
    UrlParse {
        /// Human-readable context.
        context: &'static str,
        /// The underlying parse error.
        #[source]
        source: url::ParseError,
    },
    /// HTTP transport error.
    #[error("HTTP error: {context}: {source}")]
    Http {
        /// Human-readable context.
        context: &'static str,
        /// The underlying reqwest error.
        #[source]
        source: reqwest::Error,
    },
    /// JSON deserialization error.
    #[error("Failed to deserialize JSON: {context}: {source}")]
    JsonDeserialization {
        /// Human-readable context.
        context: &'static str,
        /// The underlying reqwest error.
        #[source]
        source: reqwest::Error,
    },
    /// Unexpected HTTP status code.
    #[error("Unexpected HTTP status {status}: {context}: {body}")]
    HttpStatus {
        /// Human-readable context.
        context: &'static str,
        /// The HTTP status code.
        status: StatusCode,
        /// The response body.
        body: String,
    },
    /// Failed to read response body.
    #[error("Failed to read response body as text: {context}: {source}")]
    ResponseBodyRead {
        /// Human-readable context.
        context: &'static str,
        /// The underlying reqwest error.
        #[source]
        source: reqwest::Error,
    },
}

impl FacilitatorClient {
    /// Default TTL for caching the supported endpoint response (10 minutes).
    pub const DEFAULT_SUPPORTED_CACHE_TTL: Duration = Duration::from_mins(10);

    /// Returns the base URL used by this client.
    #[must_use]
    pub const fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// Returns the computed `./verify` URL relative to [`FacilitatorClient::base_url`].
    #[must_use]
    pub const fn verify_url(&self) -> &Url {
        &self.verify_url
    }

    /// Returns the computed `./settle` URL relative to [`FacilitatorClient::base_url`].
    #[must_use]
    pub const fn settle_url(&self) -> &Url {
        &self.settle_url
    }

    /// Returns the computed `./supported` URL relative to [`FacilitatorClient::base_url`].
    #[must_use]
    pub const fn supported_url(&self) -> &Url {
        &self.supported_url
    }

    /// Returns any custom headers configured on the client.
    #[must_use]
    pub const fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// Returns the configured timeout, if any.
    #[must_use]
    pub const fn timeout(&self) -> Option<&Duration> {
        self.timeout.as_ref()
    }

    /// Returns a reference to the supported cache.
    #[must_use]
    pub const fn supported_cache(&self) -> &SupportedCache {
        &self.supported_cache
    }

    /// Constructs a new [`FacilitatorClient`] from a base URL.
    ///
    /// This sets up `./verify`, `./settle`, and `./supported` endpoint URLs relative to the base.
    ///
    /// # Errors
    ///
    /// Returns [`FacilitatorClientError`] if URL construction fails.
    pub fn try_new(base_url: Url) -> Result<Self, FacilitatorClientError> {
        let client = Client::new();
        let verify_url =
            base_url
                .join("./verify")
                .map_err(|e| FacilitatorClientError::UrlParse {
                    context: "Failed to construct ./verify URL",
                    source: e,
                })?;
        let settle_url =
            base_url
                .join("./settle")
                .map_err(|e| FacilitatorClientError::UrlParse {
                    context: "Failed to construct ./settle URL",
                    source: e,
                })?;
        let supported_url =
            base_url
                .join("./supported")
                .map_err(|e| FacilitatorClientError::UrlParse {
                    context: "Failed to construct ./supported URL",
                    source: e,
                })?;
        Ok(Self {
            client,
            base_url,
            verify_url,
            settle_url,
            supported_url,
            headers: HeaderMap::new(),
            timeout: None,
            supported_cache: SupportedCache::new(Self::DEFAULT_SUPPORTED_CACHE_TTL),
        })
    }

    /// Attaches custom headers to all future requests.
    #[must_use]
    pub fn with_headers(mut self, headers: HeaderMap) -> Self {
        self.headers = headers;
        self
    }

    /// Sets a timeout for all future requests.
    #[must_use]
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Sets the TTL for caching the supported endpoint response.
    ///
    /// Default is 10 minutes. Use [`Self::without_supported_cache()`] to disable caching.
    #[must_use]
    pub fn with_supported_cache_ttl(mut self, ttl: Duration) -> Self {
        self.supported_cache = SupportedCache::new(ttl);
        self
    }

    /// Disables caching for the supported endpoint.
    #[must_use]
    pub fn without_supported_cache(self) -> Self {
        self.with_supported_cache_ttl(Duration::ZERO)
    }

    /// Sends a `POST /verify` request to the facilitator.
    ///
    /// # Errors
    ///
    /// Returns [`FacilitatorClientError`] if the HTTP request fails.
    pub async fn verify(
        &self,
        request: &VerifyRequest,
    ) -> Result<VerifyResponse, FacilitatorClientError> {
        self.post_json(&self.verify_url, "POST /verify", request)
            .await
    }

    /// Sends a `POST /settle` request to the facilitator.
    ///
    /// # Errors
    ///
    /// Returns [`FacilitatorClientError`] if the HTTP request fails.
    pub async fn settle(
        &self,
        request: &SettleRequest,
    ) -> Result<SettleResponse, FacilitatorClientError> {
        self.post_json(&self.settle_url, "POST /settle", request)
            .await
    }

    /// Sends a `GET /supported` request to the facilitator.
    /// This is the inner method that always makes an HTTP request.
    #[cfg_attr(
        feature = "telemetry",
        instrument(name = "x402.facilitator_client.supported", skip_all, err)
    )]
    async fn supported_inner(&self) -> Result<SupportedResponse, FacilitatorClientError> {
        self.get_json(&self.supported_url, "GET /supported").await
    }

    /// Sends a `GET /supported` request to the facilitator.
    /// Results are cached with a configurable TTL (default: 10 minutes).
    /// Use `supported_inner()` to bypass the cache.
    ///
    /// # Errors
    ///
    /// Returns [`FacilitatorClientError`] if the HTTP request fails.
    pub async fn supported(&self) -> Result<SupportedResponse, FacilitatorClientError> {
        // Try to get from cache
        if let Some(response) = self.supported_cache.get().await {
            return Ok(response);
        }

        // Cache miss - fetch and cache
        #[cfg(feature = "telemetry")]
        tracing::info!("x402.facilitator_client.supported_cache_miss");

        let response = self.supported_inner().await?;
        self.supported_cache.set(response.clone()).await;

        Ok(response)
    }

    /// Generic POST helper that handles JSON serialization, error mapping,
    /// timeout application, and telemetry integration.
    ///
    /// `context` is a human-readable identifier used in tracing and error messages (e.g. `"POST /verify"`).
    #[allow(
        clippy::needless_pass_by_value,
        reason = "context is a static str, clone cost is zero"
    )]
    async fn post_json<T, R>(
        &self,
        url: &Url,
        context: &'static str,
        payload: &T,
    ) -> Result<R, FacilitatorClientError>
    where
        T: serde::Serialize + Sync + ?Sized,
        R: serde::de::DeserializeOwned,
    {
        let req = self.client.post(url.clone()).json(payload);
        self.send_and_parse(req, context).await
    }

    /// Generic GET helper that handles error mapping, timeout application,
    /// and telemetry integration.
    ///
    /// `context` is a human-readable identifier used in tracing and error messages (e.g. `"GET /supported"`).
    async fn get_json<R>(
        &self,
        url: &Url,
        context: &'static str,
    ) -> Result<R, FacilitatorClientError>
    where
        R: serde::de::DeserializeOwned,
    {
        let req = self.client.get(url.clone());
        self.send_and_parse(req, context).await
    }

    /// Applies headers, timeout, sends the request, and parses the JSON response.
    async fn send_and_parse<R>(
        &self,
        mut req: reqwest::RequestBuilder,
        context: &'static str,
    ) -> Result<R, FacilitatorClientError>
    where
        R: serde::de::DeserializeOwned,
    {
        for (key, value) in &self.headers {
            req = req.header(key, value);
        }
        if let Some(timeout) = self.timeout {
            req = req.timeout(timeout);
        }
        let http_response = req
            .send()
            .await
            .map_err(|e| FacilitatorClientError::Http { context, source: e })?;

        let result = if http_response.status() == StatusCode::OK {
            http_response
                .json::<R>()
                .await
                .map_err(|e| FacilitatorClientError::JsonDeserialization { context, source: e })
        } else {
            let status = http_response.status();
            let body = http_response
                .text()
                .await
                .map_err(|e| FacilitatorClientError::ResponseBodyRead { context, source: e })?;
            Err(FacilitatorClientError::HttpStatus {
                context,
                status,
                body,
            })
        };

        record_result_on_span(&result);

        result
    }
}

impl Facilitator for FacilitatorClient {
    fn verify(
        &self,
        request: VerifyRequest,
    ) -> BoxFuture<'_, Result<VerifyResponse, FacilitatorError>> {
        Box::pin(async move {
            #[cfg(feature = "telemetry")]
            let result = with_span(
                Self::verify(self, &request),
                tracing::info_span!("x402.facilitator_client.verify", timeout = ?self.timeout),
            )
            .await;
            #[cfg(not(feature = "telemetry"))]
            let result = Self::verify(self, &request).await;
            result.map_err(|e| FacilitatorError::Other(Box::new(e)))
        })
    }

    fn settle(
        &self,
        request: SettleRequest,
    ) -> BoxFuture<'_, Result<SettleResponse, FacilitatorError>> {
        Box::pin(async move {
            #[cfg(feature = "telemetry")]
            let result = with_span(
                Self::settle(self, &request),
                tracing::info_span!("x402.facilitator_client.settle", timeout = ?self.timeout),
            )
            .await;
            #[cfg(not(feature = "telemetry"))]
            let result = Self::settle(self, &request).await;
            result.map_err(|e| FacilitatorError::Other(Box::new(e)))
        })
    }

    fn supported(&self) -> BoxFuture<'_, Result<SupportedResponse, FacilitatorError>> {
        Box::pin(async move {
            Self::supported(self)
                .await
                .map_err(|e| FacilitatorError::Other(Box::new(e)))
        })
    }
}

/// Converts a string URL into a `FacilitatorClient`, parsing the URL and calling `try_new`.
impl TryFrom<&str> for FacilitatorClient {
    type Error = FacilitatorClientError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        // Normalize: strip trailing slashes and add a single trailing slash
        let mut normalized = value.trim_end_matches('/').to_owned();
        normalized.push('/');
        let url = Url::parse(&normalized).map_err(|e| FacilitatorClientError::UrlParse {
            context: "Failed to parse base url",
            source: e,
        })?;
        Self::try_new(url)
    }
}

/// Converts a String URL into a `FacilitatorClient`.
impl TryFrom<String> for FacilitatorClient {
    type Error = FacilitatorClientError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

/// Records the outcome of a request on a tracing span, including status and errors.
#[cfg(feature = "telemetry")]
fn record_result_on_span<R, E: Display>(result: &Result<R, E>) {
    let span = Span::current();
    match result {
        Ok(_) => {
            span.record("otel.status_code", "OK");
        }
        Err(err) => {
            span.record("otel.status_code", "ERROR");
            span.record("error.message", tracing::field::display(err));
            tracing::event!(tracing::Level::ERROR, error = %err, "Request to facilitator failed");
        }
    }
}

/// Records the outcome of a request on a tracing span, including status and errors.
/// Noop if telemetry feature is off.
#[cfg(not(feature = "telemetry"))]
const fn record_result_on_span<R, E: Display>(_result: &Result<R, E>) {}

/// Instruments a future with a given tracing span.
#[cfg(feature = "telemetry")]
fn with_span<F: Future>(fut: F, span: Span) -> impl Future<Output = F::Output> {
    fut.instrument(span)
}

#[cfg(test)]
#[allow(
    clippy::indexing_slicing,
    reason = "test assertions with known-length slices"
)]
mod tests {
    use std::collections::HashMap;

    use r402::proto::SupportedPaymentKind;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    use super::*;

    fn create_test_supported_response() -> SupportedResponse {
        SupportedResponse {
            kinds: vec![SupportedPaymentKind {
                x402_version: 1,
                scheme: "eip155-exact".to_owned(),
                network: "1".to_owned(),
                extra: None,
            }],
            extensions: vec![],
            signers: HashMap::new(),
        }
    }

    #[tokio::test]
    async fn test_supported_cache_caches_response() {
        let mock_server = MockServer::start().await;
        let test_response = create_test_supported_response();

        // Mock the supported endpoint
        Mock::given(method("GET"))
            .and(path("/supported"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&test_response))
            .mount(&mock_server)
            .await;

        let client = FacilitatorClient::try_new(mock_server.uri().parse::<Url>().unwrap()).unwrap();

        // First call should hit the network
        let result1 = client.supported().await.unwrap();
        assert_eq!(result1.kinds.len(), 1);

        // Second call should use cache (same mock call count)
        let result2 = client.supported().await.unwrap();
        assert_eq!(result2.kinds.len(), 1);

        // Both results should be equal
        assert_eq!(result1.kinds[0].scheme, result2.kinds[0].scheme);
    }

    #[tokio::test]
    async fn test_supported_cache_with_custom_ttl() {
        let mock_server = MockServer::start().await;
        let test_response = create_test_supported_response();

        // Mock the supported endpoint
        Mock::given(method("GET"))
            .and(path("/supported"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&test_response))
            .mount(&mock_server)
            .await;

        // Create client with 1ms TTL (essentially no caching)
        let client = FacilitatorClient::try_new(mock_server.uri().parse::<Url>().unwrap())
            .unwrap()
            .with_supported_cache_ttl(Duration::from_millis(1));

        // First call
        let result1 = client.supported().await.unwrap();
        assert_eq!(result1.kinds.len(), 1);

        // Wait for cache to expire
        tokio::time::sleep(Duration::from_millis(10)).await;

        // Second call should hit the network again due to expired cache
        let result2 = client.supported().await.unwrap();
        assert_eq!(result2.kinds.len(), 1);
    }

    #[tokio::test]
    async fn test_supported_cache_disabled() {
        let mock_server = MockServer::start().await;
        let test_response = create_test_supported_response();

        // Mock the supported endpoint
        Mock::given(method("GET"))
            .and(path("/supported"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&test_response))
            .mount(&mock_server)
            .await;

        // Create client with caching disabled
        let client = FacilitatorClient::try_new(mock_server.uri().parse::<Url>().unwrap())
            .unwrap()
            .without_supported_cache();

        // Each call should hit the network
        let result1 = client.supported().await.unwrap();
        let result2 = client.supported().await.unwrap();

        assert_eq!(result1.kinds.len(), 1);
        assert_eq!(result2.kinds.len(), 1);
    }

    #[tokio::test]
    async fn test_supported_cache_shared_across_clones() {
        let mock_server = MockServer::start().await;
        let test_response = create_test_supported_response();

        // Mock the supported endpoint — expect exactly 1 request
        Mock::given(method("GET"))
            .and(path("/supported"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&test_response))
            .expect(1)
            .mount(&mock_server)
            .await;

        let client = FacilitatorClient::try_new(mock_server.uri().parse::<Url>().unwrap()).unwrap();

        // Clone the client — clones share the same cache
        let client2 = client.clone();

        // Populate cache on first client
        let result1 = client.supported().await.unwrap();
        assert_eq!(result1.kinds.len(), 1);

        // Clone should hit the shared cache (no extra HTTP request)
        let result2 = client2.supported().await.unwrap();
        assert_eq!(result2.kinds.len(), 1);
        assert_eq!(result1.kinds[0].scheme, result2.kinds[0].scheme);
    }

    #[tokio::test]
    async fn test_supported_inner_bypasses_cache() {
        let mock_server = MockServer::start().await;
        let test_response = create_test_supported_response();

        // Mock the supported endpoint
        Mock::given(method("GET"))
            .and(path("/supported"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&test_response))
            .mount(&mock_server)
            .await;

        let client = FacilitatorClient::try_new(mock_server.uri().parse::<Url>().unwrap()).unwrap();

        // Populate cache
        let _ = client.supported().await.unwrap();

        // supported_inner() should always make HTTP request, bypassing cache
        let result = client.supported_inner().await.unwrap();
        assert_eq!(result.kinds.len(), 1);
    }
}