Skip to main content

CacheHandle

Struct CacheHandle 

Source
pub struct CacheHandle { /* private fields */ }
Expand description

A cloneable handle for cache management — invalidating entries and (in PreGenerate mode) managing the list of pre-generated SSG snapshots at runtime.

Implementations§

Source§

impl CacheHandle

Source

pub fn new() -> Self

Create a new handle without snapshot support (Dynamic mode or tests).

Source

pub fn invalidate_all(&self)

Invalidate all cache entries.

Examples found in repository?
examples/library_usage.rs (line 43)
8async fn main() {
9    // Initialize tracing (optional but recommended)
10    // tracing_subscriber::fmt::init();
11
12    // Create proxy configuration
13    // You can specify method prefixes to filter by HTTP method
14    let proxy_config = CreateProxyConfig::new("http://localhost:8080".to_string())
15        .with_include_paths(vec![
16            "/api/*".to_string(),
17            "/public/*".to_string(),
18            "GET /admin/stats".to_string(), // Only cache GET requests to this endpoint
19        ])
20        .with_exclude_paths(vec![
21            "/api/admin/*".to_string(),
22            "POST *".to_string(),   // Don't cache any POST requests
23            "PUT *".to_string(),    // Don't cache any PUT requests
24            "DELETE *".to_string(), // Don't cache any DELETE requests
25        ])
26        .caching_strategy(CacheStrategy::None)
27        .compression_strategy(CompressStrategy::Brotli)
28        .with_cache_storage_mode(phantom_frame::CacheStorageMode::Filesystem)
29        .with_cache_directory(PathBuf::from("./.phantom-frame-cache"))
30        .with_websocket_enabled(true); // Enable WebSocket support (default: true)
31
32    // Create proxy - proxy_url is the backend server to proxy requests to
33    let (proxy_app, handle): (Router, CacheHandle) = create_proxy(proxy_config);
34
35    // You can clone and use the handle in your code
36    let handle_clone = handle.clone();
37
38    // Example: Trigger cache invalidation from another part of your application
39    tokio::spawn(async move {
40        tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
41
42        // Invalidate all cache entries
43        handle_clone.invalidate_all();
44        println!("All cache invalidated!");
45
46        tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
47
48        // Invalidate only cache entries matching a pattern (supports wildcards)
49        handle_clone.invalidate("GET:/api/*");
50        println!("Cache invalidated for GET:/api/* pattern!");
51    });
52
53    // Example: PreGenerate (SSG) mode with snapshot management
54    // let ssg_config = CreateProxyConfig::new("http://localhost:8080".to_string())
55    //     .with_proxy_mode(ProxyMode::PreGenerate {
56    //         paths: vec!["/".to_string(), "/about".to_string(), "/book/1".to_string()],
57    //         fallthrough: false, // return 404 on cache miss (default)
58    //     });
59    // let (ssg_app, ssg_handle) = create_proxy(ssg_config);
60    // // At runtime, manage snapshots:
61    // ssg_handle.add_snapshot("/book/2").await.unwrap();
62    // ssg_handle.refresh_snapshot("/book/1").await.unwrap();
63    // ssg_handle.remove_snapshot("/about").await.unwrap();
64    // ssg_handle.refresh_all_snapshots().await.unwrap();
65    let _ = ProxyMode::Dynamic; // suppress unused import warning
66
67    // Start the proxy server
68    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
69
70    println!("Proxy server listening on http://0.0.0.0:3000");
71    println!("Caching paths: /api/*, /public/*, GET /admin/stats");
72    println!("Excluding: /api/admin/*, POST *, PUT *, DELETE *");
73    println!("Cache strategy: none (proxy-only mode)");
74    println!("Compression strategy: brotli (applies only to cached responses)");
75    println!("Cache storage mode: filesystem (custom cache directory)");
76    println!("Note: Cache reads and writes are disabled in this example");
77    println!("WebSocket support: enabled");
78
79    axum::serve(listener, proxy_app).await.unwrap();
80}
Source

pub fn invalidate(&self, pattern: &str)

Invalidate cache entries whose key matches pattern. Supports wildcards: "/api/*", "GET:/api/*", etc.

Examples found in repository?
examples/library_usage.rs (line 49)
8async fn main() {
9    // Initialize tracing (optional but recommended)
10    // tracing_subscriber::fmt::init();
11
12    // Create proxy configuration
13    // You can specify method prefixes to filter by HTTP method
14    let proxy_config = CreateProxyConfig::new("http://localhost:8080".to_string())
15        .with_include_paths(vec![
16            "/api/*".to_string(),
17            "/public/*".to_string(),
18            "GET /admin/stats".to_string(), // Only cache GET requests to this endpoint
19        ])
20        .with_exclude_paths(vec![
21            "/api/admin/*".to_string(),
22            "POST *".to_string(),   // Don't cache any POST requests
23            "PUT *".to_string(),    // Don't cache any PUT requests
24            "DELETE *".to_string(), // Don't cache any DELETE requests
25        ])
26        .caching_strategy(CacheStrategy::None)
27        .compression_strategy(CompressStrategy::Brotli)
28        .with_cache_storage_mode(phantom_frame::CacheStorageMode::Filesystem)
29        .with_cache_directory(PathBuf::from("./.phantom-frame-cache"))
30        .with_websocket_enabled(true); // Enable WebSocket support (default: true)
31
32    // Create proxy - proxy_url is the backend server to proxy requests to
33    let (proxy_app, handle): (Router, CacheHandle) = create_proxy(proxy_config);
34
35    // You can clone and use the handle in your code
36    let handle_clone = handle.clone();
37
38    // Example: Trigger cache invalidation from another part of your application
39    tokio::spawn(async move {
40        tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
41
42        // Invalidate all cache entries
43        handle_clone.invalidate_all();
44        println!("All cache invalidated!");
45
46        tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
47
48        // Invalidate only cache entries matching a pattern (supports wildcards)
49        handle_clone.invalidate("GET:/api/*");
50        println!("Cache invalidated for GET:/api/* pattern!");
51    });
52
53    // Example: PreGenerate (SSG) mode with snapshot management
54    // let ssg_config = CreateProxyConfig::new("http://localhost:8080".to_string())
55    //     .with_proxy_mode(ProxyMode::PreGenerate {
56    //         paths: vec!["/".to_string(), "/about".to_string(), "/book/1".to_string()],
57    //         fallthrough: false, // return 404 on cache miss (default)
58    //     });
59    // let (ssg_app, ssg_handle) = create_proxy(ssg_config);
60    // // At runtime, manage snapshots:
61    // ssg_handle.add_snapshot("/book/2").await.unwrap();
62    // ssg_handle.refresh_snapshot("/book/1").await.unwrap();
63    // ssg_handle.remove_snapshot("/about").await.unwrap();
64    // ssg_handle.refresh_all_snapshots().await.unwrap();
65    let _ = ProxyMode::Dynamic; // suppress unused import warning
66
67    // Start the proxy server
68    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
69
70    println!("Proxy server listening on http://0.0.0.0:3000");
71    println!("Caching paths: /api/*, /public/*, GET /admin/stats");
72    println!("Excluding: /api/admin/*, POST *, PUT *, DELETE *");
73    println!("Cache strategy: none (proxy-only mode)");
74    println!("Compression strategy: brotli (applies only to cached responses)");
75    println!("Cache storage mode: filesystem (custom cache directory)");
76    println!("Note: Cache reads and writes are disabled in this example");
77    println!("WebSocket support: enabled");
78
79    axum::serve(listener, proxy_app).await.unwrap();
80}
Source

pub fn is_snapshot_capable(&self) -> bool

Returns true when this handle is connected to a snapshot worker (i.e. the server is in ProxyMode::PreGenerate).

Source

pub fn subscribe(&self) -> Receiver<InvalidationMessage>

Subscribe to invalidation events.

Source

pub async fn add_snapshot(&self, path: &str) -> Result<()>

Fetch path from the upstream server, store it in the cache, and add it to the tracked snapshot list. Only available in PreGenerate mode.

Source

pub async fn refresh_snapshot(&self, path: &str) -> Result<()>

Re-fetch path from the upstream server and update its cached entry. Only available in PreGenerate mode.

Source

pub async fn remove_snapshot(&self, path: &str) -> Result<()>

Remove path from the cache and from the tracked snapshot list. Only available in PreGenerate mode.

Source

pub async fn refresh_all_snapshots(&self) -> Result<()>

Re-fetch every currently tracked snapshot path from the upstream server. Only available in PreGenerate mode.

Trait Implementations§

Source§

impl Clone for CacheHandle

Source§

fn clone(&self) -> CacheHandle

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 Default for CacheHandle

Source§

fn default() -> Self

Returns the “default value” for a type. 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> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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: 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> 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<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