Crate http_cache_ureq

Crate http_cache_ureq 

Source
Expand description

§http-cache-ureq

HTTP caching wrapper for the ureq HTTP client.

This crate provides a caching wrapper around the ureq HTTP client that implements HTTP caching according to RFC 7234. Since ureq is a synchronous HTTP client, this wrapper uses the smol async runtime to integrate with the async http-cache system.

§Features

  • json - Enables JSON request/response support via send_json() and into_json() methods (requires serde_json)
  • manager-cacache - Enable cacache cache manager (default)
  • manager-moka - Enable moka cache manager

§Basic Usage

use http_cache_ureq::{CachedAgent, CACacheManager, CacheMode};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    smol::block_on(async {
        let agent = CachedAgent::builder()
            .cache_manager(CACacheManager::new("./cache".into(), true))
            .cache_mode(CacheMode::Default)
            .build()?;
         
        // This request will be cached according to response headers
        let response = agent.get("https://httpbin.org/cache/60").call().await?;
        println!("Status: {}", response.status());
        println!("Cached: {}", response.is_cached());
        println!("Response: {}", response.into_string()?);
         
        // Subsequent identical requests may be served from cache
        let cached_response = agent.get("https://httpbin.org/cache/60").call().await?;
        println!("Cached status: {}", cached_response.status());
        println!("Is cached: {}", cached_response.is_cached());
        println!("Cached response: {}", cached_response.into_string()?);
         
        Ok(())
    })
}

§Cache Modes

Control caching behavior with different modes:

use http_cache_ureq::{CachedAgent, CACacheManager, CacheMode};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    smol::block_on(async {
        let agent = CachedAgent::builder()
            .cache_manager(CACacheManager::new("./cache".into(), true))
            .cache_mode(CacheMode::ForceCache) // Cache everything, ignore headers
            .build()?;
         
        // This will be cached even if headers say not to cache
        let response = agent.get("https://httpbin.org/uuid").call().await?;
        println!("Response: {}", response.into_string()?);
         
        Ok(())
    })
}

§JSON Support

Enable the json feature to send and parse JSON data:

use http_cache_ureq::{CachedAgent, CACacheManager, CacheMode};
use serde_json::json;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    smol::block_on(async {
        let agent = CachedAgent::builder()
            .cache_manager(CACacheManager::new("./cache".into(), true))
            .cache_mode(CacheMode::Default)
            .build()?;
         
        // Send JSON data
        let response = agent.post("https://httpbin.org/post")
            .send_json(json!({"key": "value"}))
            .await?;
         
        // Parse JSON response
        let json: serde_json::Value = response.into_json()?;
        println!("Response: {}", json);
         
        Ok(())
    })
}

§In-Memory Caching

Use the Moka in-memory cache:

use http_cache_ureq::{CachedAgent, MokaManager, MokaCache, CacheMode};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    smol::block_on(async {
        let agent = CachedAgent::builder()
            .cache_manager(MokaManager::new(MokaCache::new(1000))) // Max 1000 entries
            .cache_mode(CacheMode::Default)
            .build()?;
             
        let response = agent.get("https://httpbin.org/cache/60").call().await?;
        println!("Response: {}", response.into_string()?);
         
        Ok(())
    })
}

§Custom Cache Keys

Customize how cache keys are generated:

use http_cache_ureq::{CachedAgent, CACacheManager, CacheMode, HttpCacheOptions};
use std::sync::Arc;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    smol::block_on(async {
    let options = HttpCacheOptions {
        cache_key: Some(Arc::new(|parts: &http::request::Parts| {
            // Include query parameters in cache key
            format!("{}:{}", parts.method, parts.uri)
        })),
        ..Default::default()
    };
     
    let agent = CachedAgent::builder()
        .cache_manager(CACacheManager::new("./cache".into(), true))
        .cache_mode(CacheMode::Default)
        .cache_options(options)
        .build()?;
         
    let response = agent.get("https://httpbin.org/cache/60?param=value").call().await?;
    println!("Response: {}", response.into_string()?);
     
        Ok(())
    })
}

§Maximum TTL Control

Set a maximum time-to-live for cached responses, particularly useful with CacheMode::IgnoreRules:

use http_cache_ureq::{CachedAgent, CACacheManager, CacheMode, HttpCacheOptions};
use std::time::Duration;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    smol::block_on(async {
        let agent = CachedAgent::builder()
            .cache_manager(CACacheManager::new("./cache".into(), true))
            .cache_mode(CacheMode::IgnoreRules) // Ignore server cache-control headers
            .cache_options(HttpCacheOptions {
                max_ttl: Some(Duration::from_secs(300)), // Limit cache to 5 minutes regardless of server headers
                ..Default::default()
            })
            .build()?;
         
        // This will be cached for max 5 minutes even if server says cache longer
        let response = agent.get("https://httpbin.org/cache/3600").call().await?;
        println!("Response: {}", response.into_string()?);
         
        Ok(())
    })
}

Structs§

BadRequest
Error type for request parsing failure
CACacheManagermanager-cacache
Implements CacheManager with cacache as the backend.
CachedAgent
A cached HTTP agent that wraps ureq with HTTP caching capabilities
CachedAgentBuilder
Builder for creating a CachedAgent
CachedRequestBuilder
A cached HTTP request builder that integrates ureq requests with HTTP caching
CachedResponse
A response wrapper that can represent both cached and fresh responses
DirectRateLimiterrate-limiting
A direct (non-keyed) rate limiter for simple use cases where all requests share the same limit
DomainRateLimiterrate-limiting
A domain-based rate limiter using governor that limits requests per domain
HttpCache
Caches requests according to http spec.
HttpCacheOptions
Configuration options for customizing HTTP cache behavior on a per-request basis.
MokaCachemanager-moka
A thread-safe, futures-aware concurrent in-memory cache.
MokaCacheBuildermanager-moka
Builds a Cache with various configuration knobs.
MokaManagermanager-moka
Implements CacheManager with moka as the backend.
Parts
Component parts of an HTTP Request
Quotarate-limiting
A rate-limiting quota.

Enums§

CacheMode
Cache mode determines how the HTTP cache behaves for requests.
HttpCacheError
Unified error type for HTTP cache operations that works across all client libraries.

Traits§

CacheAwareRateLimiterrate-limiting
A trait for rate limiting that can be implemented by different rate limiting strategies

Type Aliases§

ResponseCacheModeFn
A closure that takes http::request::Parts, HttpResponse and returns a CacheMode to override caching behavior based on the response