Skip to main content

CreateProxyConfig

Struct CreateProxyConfig 

Source
pub struct CreateProxyConfig {
Show 14 fields pub proxy_url: String, pub include_paths: Vec<String>, pub exclude_paths: Vec<String>, pub enable_websocket: bool, pub forward_get_only: bool, pub cache_key_fn: Arc<dyn Fn(&RequestInfo<'_>) -> String + Send + Sync>, pub cache_404_capacity: usize, pub use_404_meta: bool, pub cache_strategy: CacheStrategy, pub compress_strategy: CompressStrategy, pub cache_storage_mode: CacheStorageMode, pub cache_directory: Option<PathBuf>, pub proxy_mode: ProxyMode, pub webhooks: Vec<WebhookConfig>,
}
Expand description

Configuration for creating a proxy

Fields§

§proxy_url: String

The backend URL to proxy requests to

§include_paths: Vec<String>

Paths to include in caching (empty means include all) Supports wildcards and method prefixes: “/api/”, “POST /api/”, “GET /*/users”, etc.

§exclude_paths: Vec<String>

Paths to exclude from caching (empty means exclude none) Supports wildcards and method prefixes: “/admin/*”, “POST ”, “PUT /api/”, etc. Exclude overrides include

§enable_websocket: bool

Enable WebSocket and protocol upgrade support (default: true) When enabled, requests with Connection: Upgrade headers will bypass the cache and establish a direct bidirectional TCP tunnel

§forward_get_only: bool

Only allow GET requests, reject all others (default: false) When true, only GET requests are processed; POST, PUT, DELETE, etc. return 405 Method Not Allowed Useful for static site prerendering where mutations shouldn’t be allowed

§cache_key_fn: Arc<dyn Fn(&RequestInfo<'_>) -> String + Send + Sync>

Custom cache key generator Takes request info and returns a cache key Default: method + path + query string

§cache_404_capacity: usize

Capacity for special 404 cache. When 0, 404 caching is disabled.

§use_404_meta: bool

When true, treat a response containing the meta tag <meta name="phantom-404" content="true"> as a 404 This is an optional performance-affecting fallback to detect framework-generated 404 pages.

§cache_strategy: CacheStrategy

Controls which responses should be cached after the backend responds.

§compress_strategy: CompressStrategy

Controls how cached bodies are stored in memory.

§cache_storage_mode: CacheStorageMode

Controls where cached response bodies are stored.

§cache_directory: Option<PathBuf>

Optional override for filesystem-backed cache bodies.

§proxy_mode: ProxyMode

Controls the operating mode of the proxy (Dynamic vs PreGenerate/SSG).

§webhooks: Vec<WebhookConfig>

Webhooks called for every request before cache reads. Blocking webhooks gate access; notify webhooks are fire-and-forget.

Implementations§

Source§

impl CreateProxyConfig

Source

pub fn new(proxy_url: String) -> Self

Create a new config with default settings

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

pub fn with_include_paths(self, paths: Vec<String>) -> Self

Set include paths

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

pub fn with_exclude_paths(self, paths: Vec<String>) -> Self

Set exclude paths

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

pub fn with_websocket_enabled(self, enabled: bool) -> Self

Enable or disable WebSocket and protocol upgrade support

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

pub fn with_forward_get_only(self, enabled: bool) -> Self

Only allow GET requests, reject all others

Source

pub fn with_cache_key_fn<F>(self, f: F) -> Self
where F: Fn(&RequestInfo<'_>) -> String + Send + Sync + 'static,

Set custom cache key function

Source

pub fn with_cache_404_capacity(self, capacity: usize) -> Self

Set 404 cache capacity. When 0, 404 caching is disabled.

Source

pub fn with_use_404_meta(self, enabled: bool) -> Self

Treat pages that include the special meta tag as 404 pages

Source

pub fn with_cache_strategy(self, strategy: CacheStrategy) -> Self

Set the cache strategy used to decide which response types are stored.

Source

pub fn caching_strategy(self, strategy: CacheStrategy) -> Self

Alias for callers that prefer a more fluent builder name.

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

pub fn with_compress_strategy(self, strategy: CompressStrategy) -> Self

Set the compression strategy used for stored cache entries.

Source

pub fn compression_strategy(self, strategy: CompressStrategy) -> Self

Alias for callers that prefer a more fluent builder name.

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

pub fn with_cache_storage_mode(self, mode: CacheStorageMode) -> Self

Set the backing store for cached response bodies.

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

pub fn with_cache_directory(self, directory: impl Into<PathBuf>) -> Self

Set the filesystem directory used for disk-backed cache bodies.

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

pub fn with_proxy_mode(self, mode: ProxyMode) -> Self

Set the proxy operating mode. Use ProxyMode::PreGenerate { paths, fallthrough } to enable SSG mode.

Source

pub fn with_webhooks(self, webhooks: Vec<WebhookConfig>) -> Self

Set the webhooks for this server. Blocking webhooks gate access; notify webhooks are fire-and-forget.

Trait Implementations§

Source§

impl Clone for CreateProxyConfig

Source§

fn clone(&self) -> CreateProxyConfig

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

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