Skip to main content

Crate hitbox_http

Crate hitbox_http 

Source
Expand description

§hitbox-http

HTTP caching primitives for the Hitbox framework.

This crate provides the building blocks for caching HTTP requests and responses: predicates to determine cacheability, extractors to generate cache keys, and body utilities for transparent request/response handling.

§Core Concepts

  • Predicate: Evaluates whether a request or response should be cached. Returns Cacheable or NonCacheable.

  • Extractor: Generates cache key parts from HTTP components (method, path, headers, query parameters, body).

  • CacheableSubject: A trait that allows predicates and extractors to work uniformly with both requests and responses.

  • BufferedBody: A body wrapper with three states (Complete, Partial, Passthrough) enabling transparent caching without disrupting the HTTP stream.

§Quickstart

use std::time::Duration;

use hitbox::policy::PolicyConfig;
use hitbox::predicate::PredicateExt;
use hitbox_configuration::Endpoint;
use hitbox_http::{
    extractors::{Method, path::PathExtractor, query::QueryExtractor},
    predicates::{
        header::{Header, Operation as HeaderOperation},
        response::StatusCode,
   },
};

// Build a cache configuration for an endpoint
let config = Endpoint::builder()
    // Skip cache when Cache-Control: no-cache is present
    .request_predicate(
        Header::new(HeaderOperation::Contains(
            http::header::CACHE_CONTROL,
            "no-cache".to_string(),
        ))
        .not(),
    )
    // Only cache successful responses
    .response_predicate(StatusCode::new(http::StatusCode::OK))
    // Build cache key from method, path parameters, and query
    .extractor(
        Method::new()
            .path("/users/{user_id}/posts/{post_id}")
            .query("page".to_string()),
    )
    // Cache for 5 minutes
    .policy(PolicyConfig::builder().ttl(Duration::from_secs(300)).build())
    .build();

§Predicates

Predicates determine whether a request or response is cacheable.

§Request Predicates

PredicateDescription
predicates::request::MethodMatch by HTTP method (GET, POST, etc.)
predicates::request::PathMatch by path pattern
predicates::request::HeaderMatch by header presence or value
predicates::request::QueryMatch by query parameter
predicates::request::BodyMatch by request body content

§Response Predicates

PredicateDescription
predicates::response::StatusCodeMatch by status code or class
predicates::response::HeaderMatch by header presence or value
predicates::response::BodyMatch by response body content

§Combining Predicates

Use PredicateExt methods to combine predicates:

use hitbox::predicate::PredicateExt;
use hitbox_http::predicates::header::{Header, Operation};


// Skip cache when Cache-Control contains "no-cache"
let skip_no_cache = Header::new(Operation::Contains(
    http::header::CACHE_CONTROL,
    "no-cache".to_string(),
));
let skip_no_cache = skip_no_cache.not();

// Skip cache when Authorization header exists
let skip_auth = Header::new(Operation::Exist(
    http::header::AUTHORIZATION,
)).not();

// Combine: cache only if BOTH conditions pass
let combined = skip_no_cache.and(skip_auth);

§Extractors

Extractors generate cache key parts from HTTP components. Chain them using the builder pattern:

use hitbox_http::extractors::{Method, path::PathExtractor, query::QueryExtractor};

let extractor = Method::new()
    .path("/users/{user_id}")
    .query("page".to_string())
    .query("limit".to_string());
ExtractorDescription
extractors::MethodExtract HTTP method
extractors::PathExtract path parameters using patterns like /users/{id}
extractors::headerExtract header values
extractors::queryExtract query parameters
extractors::bodyExtract from body (hash, JQ, regex)
extractors::VersionExtract HTTP version

§Main Types

§Feature Flags

  • rkyv_format: Enables zero-copy deserialization using rkyv.

Re-exports§

pub use body::BufferedBody;
pub use body::CollectExactResult;
pub use body::PartialBufferedBody;
pub use body::Remaining;

Modules§

body
HTTP body buffering and streaming utilities for transparent caching.
extractors
Cache key extractors for HTTP requests.
predicates
Predicates for determining HTTP request and response cacheability.
query
Query string parsing utilities.

Structs§

CacheableHttpRequest
Wraps an HTTP request for cache policy evaluation.
CacheableHttpResponse
Wraps an HTTP response for cache storage and retrieval.
SerializableHttpResponse
Serialized form of an HTTP response for cache storage.

Constants§

DEFAULT_CACHE_STATUS_HEADER
Default header name for cache status (HIT/MISS/STALE).

Traits§

CacheableSubject
Enables predicates and extractors to work uniformly with requests and responses.