Skip to main content

StreamingManager

Struct StreamingManager 

Source
pub struct StreamingManager { /* private fields */ }
Available on crate feature streaming only.
Expand description

Streaming cache manager backed by redb (metadata) + tokio::fs (bodies).

This implementation provides:

  • Persistence across restarts: metadata lives in an on-disk redb database, not just in-memory moka — cached entries survive process restarts.
  • True streaming reads: Cached responses are streamed from disk in 64KB chunks, not loaded fully into memory.
  • Single-instance enforcement: redb’s file lock prevents multiple StreamingManagers from operating on the same cache_dir concurrently.
  • Crash-safe writes: atomic rename + 16-byte nonce header detect overwrite-crash corruption; orphan tmp files are swept on startup.
  • Body size limits: Configurable max body size to prevent memory exhaustion.

§Only one instance per cache directory

Only one StreamingManager may point at a given cache_dir at a time (enforced by redb’s internal file lock on metadata.redb). Cloning an existing StreamingManager is fine — construction via [new], [with_max_body_size], or [with_temp_dir] against a directory already in use will fail. This guarantee is reliable on local filesystems; on NFS or container overlay filesystems it is best-effort. Do not share a cache directory across hosts.

§Example

use http_cache::StreamingManager;
use std::path::PathBuf;

let manager = StreamingManager::new(PathBuf::from("./cache"), 10_000).await?;

Implementations§

Source§

impl StreamingManager

Source

pub async fn new( cache_dir: PathBuf, capacity: u64, ) -> Result<StreamingManager, Box<dyn Error + Send + Sync>>

Creates a new StreamingManager with disk-backed storage.

Uses the default maximum body size of 100MB. For custom limits, use StreamingManager::with_max_body_size.

§Single-instance invariant

Only one StreamingManager may operate on a given cache_dir at a time. Construction fails if another instance in any process currently holds the metadata.redb file lock.

§Arguments
  • cache_dir - Directory to store cached response bodies and metadata
  • capacity - Maximum number of metadata entries in the in-memory hot cache
§Example
use http_cache::StreamingManager;
use std::path::PathBuf;

let manager = StreamingManager::new(PathBuf::from("./cache"), 10_000).await?;
Source

pub async fn with_max_body_size( cache_dir: PathBuf, capacity: u64, max_body_size: u64, ) -> Result<StreamingManager, Box<dyn Error + Send + Sync>>

Creates a new StreamingManager with a custom maximum body size.

See StreamingManager::new for details on the single-instance invariant.

§Arguments
  • cache_dir - Directory to store cached response bodies and metadata
  • capacity - Maximum number of metadata entries in the in-memory hot cache
  • max_body_size - Maximum body size in bytes (responses larger than this are not cached — caching is declined and the body still streams through to the caller)
§Example
use http_cache::StreamingManager;
use std::path::PathBuf;

let manager = StreamingManager::with_max_body_size(
    PathBuf::from("./cache"),
    10_000,
    50 * 1024 * 1024,
).await?;
Source

pub async fn in_memory( capacity: u64, ) -> Result<StreamingManager, Box<dyn Error + Send + Sync>>

👎Deprecated since 1.1.0:

renamed to with_temp_dir() for clarity

Creates a new StreamingManager using a temporary directory.

Note: Despite the historical name, this still uses disk storage in a temp directory. Only metadata is kept in memory; response bodies are stored on disk and streamed.

Use StreamingManager::new with a persistent directory for production deployments.

§Arguments
  • capacity - Maximum number of entries in the cache
Source

pub async fn with_temp_dir( capacity: u64, ) -> Result<StreamingManager, Box<dyn Error + Send + Sync>>

Creates a new StreamingManager using a temporary directory.

This is useful for testing or when persistence is not needed. The cache directory is created in the system’s temporary directory with a unique name including process ID and random component for security.

Note: This still uses disk storage in a temp directory. Only metadata is kept in memory; response bodies are stored on disk and streamed.

§Arguments
  • capacity - Maximum number of entries in the cache
§Example
use http_cache::StreamingManager;

let manager = StreamingManager::with_temp_dir(1000).await?;
Source

pub fn cache_dir(&self) -> &Path

Returns the cache directory path.

Source

pub fn entry_count(&self) -> u64

Returns the current number of entries in the in-memory hot cache.

Note: this is not the total number of persisted entries. Hydration is lazy, so this reads 0 after a restart until keys are accessed, and once capacity is exceeded, cold entries remain on disk (reachable via get) but are not counted here.

Source

pub fn max_body_size(&self) -> u64

Returns the maximum body size for cached responses.

Source

pub async fn clear(&self) -> Result<(), Box<dyn Error + Send + Sync>>

Clears all entries from the cache — moka, redb, and on-disk bodies.

Source

pub async fn run_pending_tasks(&self)

Runs pending maintenance tasks (eviction, etc).

This is called automatically but can be invoked manually to force immediate cleanup.

Trait Implementations§

Source§

impl Clone for StreamingManager

Source§

fn clone(&self) -> StreamingManager

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for StreamingManager

Source§

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

Formats the value using the given formatter. Read more
Source§

impl StreamingCacheManager for StreamingManager

Source§

type Body = StreamingBody<UnsyncBoxBody<Bytes, StreamingError>>

The body type used by this cache manager
Source§

async fn get( &self, cache_key: &str, ) -> Result<Option<(Response<<StreamingManager as StreamingCacheManager>::Body>, CachePolicy)>, Box<dyn Error + Send + Sync>>

Attempts to pull a cached response and related policy from cache with streaming body.
Source§

async fn put<B>( &self, cache_key: String, response: Response<B>, policy: CachePolicy, _request_url: Url, user_metadata: Option<Vec<u8>>, ) -> Result<Response<<StreamingManager as StreamingCacheManager>::Body>, Box<dyn Error + Send + Sync>>

Attempts to cache a response with a streaming body and related policy. Read more
Source§

async fn update_metadata( &self, cache_key: &str, headers: &HeaderMap, policy: CachePolicy, user_metadata: Option<Vec<u8>>, token: Option<&CacheEntryToken>, ) -> Result<bool, Box<dyn Error + Send + Sync>>

Update the stored headers, cache policy, and user metadata for an existing entry WITHOUT touching the body file. Used by 304 revalidation, where the body is known-unchanged. Read more
Source§

async fn convert_body<B>( &self, response: Response<B>, ) -> Result<Response<<StreamingManager as StreamingCacheManager>::Body>, Box<dyn Error + Send + Sync>>

Converts a generic body to the manager’s body type for non-cacheable responses. This is called when a response should not be cached but still needs to be returned with the correct body type.
Source§

async fn delete( &self, cache_key: &str, ) -> Result<(), Box<dyn Error + Send + Sync>>

Attempts to remove a record from cache.
Source§

fn empty_body(&self) -> <StreamingManager as StreamingCacheManager>::Body

Creates an empty body of the manager’s body type. Used for returning 504 Gateway Timeout responses on OnlyIfCached cache misses.
Source§

fn body_to_bytes_stream( body: <StreamingManager as StreamingCacheManager>::Body, ) -> impl Stream<Item = Result<Bytes, Box<dyn Error + Send + Sync>>> + Send

Available on crate feature streaming only.
Convert the manager’s body type to a reqwest-compatible bytes stream. This enables efficient streaming without collecting the entire body.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Scope for T

Source§

fn with<F, R>(self, f: F) -> R
where Self: Sized, F: FnOnce(Self) -> R,

Scoped with ownership.
Source§

fn with_ref<F, R>(&self, f: F) -> R
where F: FnOnce(&Self) -> R,

Scoped with reference.
Source§

fn with_mut<F, R>(&mut self, f: F) -> R
where F: FnOnce(&mut Self) -> R,

Scoped with mutable reference.
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> Value for T
where T: Send + Sync + 'static,

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