CacheControl

Struct CacheControl 

Source
pub struct CacheControl {
    pub max_age: u64,
    pub key: String,
}
Expand description

HTTP cache control configuration for optimizing response caching.

The CacheControl struct encapsulates caching metadata used to optimize HTTP response delivery through strategic cache management. It provides fine-grained control over cache behavior including cache duration and cache key generation for efficient content delivery.

§Purpose

This struct enables:

  • Cache Duration Control: Setting appropriate cache lifetimes via max_age
  • Cache Key Management: Generating unique identifiers for cached content
  • Performance Optimization: Reducing server load through intelligent caching
  • CDN Integration: Supporting Content Delivery Network caching strategies

§Cache Strategy

The cache control system implements a dual-approach strategy:

  1. Time-based Expiration: Uses max_age for cache lifetime management
  2. Content-based Invalidation: Uses key for cache versioning and invalidation

§Integration with Response

When attached to a Response, the CacheControl struct automatically:

  • Sets appropriate HTTP cache headers (Cache-Control, ETag, etc.)
  • Generates cache keys for storage systems
  • Enables conditional requests (304 Not Modified responses)
  • Supports cache invalidation strategies

§Examples

§Basic Cache Control

use ignitia::{Response, CacheControl};

let cache_control = CacheControl {
    max_age: 3600, // 1 hour
    key: "user_profile_123".to_string(),
};

let response = Response::json(user_data)?
    .with_cache_control(cache_control);

§Static Asset Caching

// Long-term caching for static assets
let static_cache = CacheControl {
    max_age: 31536000, // 1 year
    key: format!("static_{}_{}", filename, version_hash),
};

§API Response Caching

// Short-term caching for API responses
let api_cache = CacheControl {
    max_age: 300, // 5 minutes
    key: format!("api_{}_{}_{}", endpoint, user_id, timestamp),
};

§Dynamic Content Caching

// User-specific content with medium cache duration
let user_cache = CacheControl {
    max_age: 1800, // 30 minutes
    key: format!("content_{}_{}", content_id, last_modified),
};

Fields§

§max_age: u64

Maximum age for cached content in seconds.

This field determines how long the content should be considered fresh by browsers, CDNs, and intermediate caches. The value directly maps to the HTTP Cache-Control: max-age= directive.

§Common Values

  • 0: No caching (always revalidate)
  • 300: 5 minutes (dynamic API responses)
  • 3600: 1 hour (semi-static content)
  • 86400: 24 hours (daily updated content)
  • 31536000: 1 year (static assets with versioning)

§Performance Considerations

  • Longer cache times reduce server load but may serve stale content
  • Shorter cache times ensure freshness but increase server requests
  • Consider content update frequency when setting values

§Examples

// No caching for sensitive data
let sensitive = CacheControl { max_age: 0, key: "...".to_string() };

// Medium caching for API responses
let api = CacheControl { max_age: 600, key: "...".to_string() };

// Long caching for static assets
let static_content = CacheControl { max_age: 2592000, key: "...".to_string() };
§key: String

Unique identifier for cache entry management and invalidation.

The cache key serves multiple purposes in the caching infrastructure:

  • Uniqueness: Ensures different content versions are cached separately
  • Invalidation: Enables targeted cache clearing when content changes
  • Versioning: Supports content versioning through key changes
  • Debugging: Provides identifiable cache entries for troubleshooting

§Key Generation Strategies

§Content-Based Keys

Include content identifiers that change when content changes:

let key = format!("article_{}_{}", article_id, last_modified_timestamp);

§User-Specific Keys

Include user context for personalized content:

let key = format!("dashboard_{}_{}_{}", user_id, role, preferences_hash);

§Version-Based Keys

Include application or content version for cache busting:

let key = format!("api_response_{}_v{}", endpoint, api_version);

§Hierarchical Keys

Use hierarchical structure for organized cache management:

let key = format!("app:{}:user:{}:page:{}", app_version, user_id, page_id);

§Best Practices

  • Include all relevant context that affects content
  • Use consistent naming conventions across the application
  • Include version or timestamp information for automatic invalidation
  • Keep keys reasonably short while maintaining uniqueness
  • Avoid sensitive information in cache keys

§Performance Notes

  • Shorter keys reduce memory overhead in cache systems
  • Consistent key patterns improve cache hit rates
  • Include enough context to avoid cache collisions
  • Consider key distribution for cache sharding strategies

Trait Implementations§

Source§

impl Clone for CacheControl

Source§

fn clone(&self) -> CacheControl

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CacheControl

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,