Skip to content

Commit

Permalink
Merge pull request #39 from BrowserSync/prevent-cache
Browse files Browse the repository at this point in the history
prevent the browser cache as a default
  • Loading branch information
shakyShane authored Nov 16, 2024
2 parents 69062da + fd93a52 commit d619274
Show file tree
Hide file tree
Showing 21 changed files with 121 additions and 16 deletions.
32 changes: 30 additions & 2 deletions crates/bsnext_core/src/optional_layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use axum::routing::MethodRouter;
use axum::{middleware, Extension};
use axum_extra::middleware::option_layer;
use bsnext_input::route::{CompType, CompressionOpts, CorsOpts, DelayKind, DelayOpts, Opts};
use bsnext_resp::cache_opts::CacheOpts;
use bsnext_resp::{response_modifications_layer, InjectHandling};
use http::header::{CACHE_CONTROL, EXPIRES, PRAGMA};
use http::{HeaderName, HeaderValue};
use std::collections::BTreeMap;
use std::convert::Infallible;
Expand Down Expand Up @@ -38,10 +40,25 @@ pub fn optional_layers(app: MethodRouter, opts: &Opts) -> MethodRouter {
let set_response_headers_layer = opts
.headers
.as_ref()
.map(|headers| map_response_with_state(headers.clone(), set_resp_headers));
.map(|headers| map_response_with_state(headers.clone(), set_resp_headers_from_strs));

let prevent_cache_headers_layer = matches!(opts.cache, CacheOpts::Prevent).then(|| {
let mut headers: Vec<(HeaderName, HeaderValue)> = vec![];
headers.push((
HeaderName::from(CACHE_CONTROL),
HeaderValue::from_static("no-store, no-cache, must-revalidate"),
));
headers.push((
HeaderName::from(PRAGMA),
HeaderValue::from_static("no-cache"),
));
headers.push((HeaderName::from(EXPIRES), HeaderValue::from_static("0")));
map_response_with_state(headers, set_resp_headers)
});

let optional_stack = ServiceBuilder::new()
.layer(option_layer(inject_layer))
.layer(option_layer(prevent_cache_headers_layer))
.layer(option_layer(set_response_headers_layer))
.layer(option_layer(cors_enabled_layer))
.layer(option_layer(delay_enabled_layer));
Expand Down Expand Up @@ -74,7 +91,7 @@ async fn delay_mw(
}
}

async fn set_resp_headers<B>(
async fn set_resp_headers_from_strs<B>(
State(header_map): State<BTreeMap<String, String>>,
mut response: Response<B>,
) -> Response<B> {
Expand Down Expand Up @@ -102,6 +119,17 @@ async fn set_resp_headers<B>(
response
}

async fn set_resp_headers<B>(
State(header_map): State<Vec<(HeaderName, HeaderValue)>>,
mut response: Response<B>,
) -> Response<B> {
let headers = response.headers_mut();
for (k, v) in header_map {
headers.insert(k, v);
}
response
}

fn comp_opts_to_layer(comp: &CompressionOpts) -> Option<CompressionLayer> {
match comp {
CompressionOpts::Bool(false) => None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Raw {
true,
),
headers: None,
cache: Prevent,
compression: None,
},
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ DirsProxy {
true,
),
headers: None,
cache: Prevent,
compression: None,
},
fallback_route: None,
Expand All @@ -38,6 +39,7 @@ DirsProxy {
true,
),
headers: None,
cache: Prevent,
compression: None,
},
fallback_route: None,
Expand All @@ -56,6 +58,7 @@ DirsProxy {
true,
),
headers: None,
cache: Prevent,
compression: None,
},
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Raw {
true,
),
headers: None,
cache: Prevent,
compression: None,
},
}
3 changes: 3 additions & 0 deletions crates/bsnext_core/tests/snapshots/delays__delays-2.snap
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ expression: "(parts2.headers, body2)"
{
"content-type": "text/html; charset=utf-8",
"content-length": "20",
"cache-control": "no-store, no-cache, must-revalidate",
"pragma": "no-cache",
"expires": "0",
},
"second - 500ms delay",
)
3 changes: 3 additions & 0 deletions crates/bsnext_core/tests/snapshots/delays__delays.snap
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ expression: "(parts1.headers, body1)"
{
"content-type": "text/html; charset=utf-8",
"content-length": "19",
"cache-control": "no-store, no-cache, must-revalidate",
"pragma": "no-cache",
"expires": "0",
},
"first - 200ms delay",
)
3 changes: 3 additions & 0 deletions crates/bsnext_core/tests/snapshots/headers__headers-2.snap
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ expression: "(parts2.headers, body2)"
"access-control-allow-origin": "localhost",
"access-control-expose-headers": "*",
"abc": "def",
"cache-control": "no-store, no-cache, must-revalidate",
"pragma": "no-cache",
"expires": "0",
},
"other route",
)
3 changes: 3 additions & 0 deletions crates/bsnext_core/tests/snapshots/headers__headers.snap
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ expression: "(parts1.headers, body1)"
{
"content-type": "application/json",
"content-length": "8",
"cache-control": "no-store, no-cache, must-revalidate",
"pragma": "no-cache",
"expires": "0",
},
"[ 1, 2 ]",
)
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
---
source: crates/bsnext_core/tests/tests.rs
expression: res.headers()
expression: parts.headers
---
{
"content-type": "text/html; charset=utf-8",
"content-length": "4",
"a": "b",
"cache-control": "no-store, no-cache, must-revalidate",
"pragma": "no-cache",
"expires": "0",
}
5 changes: 4 additions & 1 deletion crates/bsnext_core/tests/snapshots/tests__handlers.snap
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
---
source: crates/bsnext_core/tests/tests.rs
expression: res.headers()
expression: parts.headers
---
{
"content-type": "text/html; charset=utf-8",
"content-length": "4",
"a": "b",
"cache-control": "no-store, no-cache, must-revalidate",
"pragma": "no-cache",
"expires": "0",
}
39 changes: 39 additions & 0 deletions crates/bsnext_core/tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use bsnext_core::server::router::common::{from_yaml, uri_to_res_parts};
use http::header::{CACHE_CONTROL, CONTENT_TYPE};
use http::HeaderValue;

#[tokio::test]
Expand Down Expand Up @@ -94,3 +95,41 @@ async fn test_route_list() -> Result<(), anyhow::Error> {
assert_eq!(status, 200);
Ok(())
}

#[tokio::test]
async fn test_cache_prevent() -> Result<(), anyhow::Error> {
let input = r#"
servers:
- bind_address: 0.0.0.0:3000
routes:
- path: /
html: home
"#;
let state = from_yaml(input)?;
let (parts, ..) = uri_to_res_parts(state, "/").await;
assert_eq!(
parts.headers.get(CONTENT_TYPE).unwrap(),
"text/html; charset=utf-8"
);
assert_eq!(
parts.headers.get(CACHE_CONTROL).unwrap(),
"no-store, no-cache, must-revalidate"
);
Ok(())
}

#[tokio::test]
async fn test_cache_default() -> Result<(), anyhow::Error> {
let input = r#"
servers:
- bind_address: 0.0.0.0:3000
routes:
- path: /
html: home
cache: 'default'
"#;
let state = from_yaml(input)?;
let (parts, ..) = uri_to_res_parts(state, "/").await;
assert_eq!(parts.headers.get(CACHE_CONTROL), None);
Ok(())
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Config {
"a": "b",
},
),
cache: Prevent,
compression: None,
},
fallback: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Config {
true,
),
headers: None,
cache: Prevent,
compression: None,
},
fallback: None,
Expand Down
1 change: 1 addition & 0 deletions crates/bsnext_input/src/playground.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ impl Playground {
inject: playground_wrap(),
headers: None,
compression: None,
..Default::default()
},
fallback: Some(FallbackRoute {
kind: RouteKind::new_html(FALLBACK_HTML),
Expand Down
10 changes: 4 additions & 6 deletions crates/bsnext_input/src/route.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::path_def::PathDef;
use crate::watch_opts::WatchOpts;
use bsnext_resp::cache_opts::CacheOpts;
use bsnext_resp::inject_opts::InjectOpts;
use matchit::InsertError;
use std::collections::BTreeMap;
Expand Down Expand Up @@ -49,6 +50,8 @@ pub struct Opts {
#[serde(default)]
pub inject: InjectOpts,
pub headers: Option<BTreeMap<String, String>>,
#[serde(default)]
pub cache: CacheOpts,
pub compression: Option<CompressionOpts>,
}

Expand All @@ -58,12 +61,7 @@ impl Default for Route {
path: PathDef::from_str("/").unwrap(),
kind: RouteKind::new_html("default"),
opts: Opts {
headers: None,
cors: None,
delay: None,
watch: Default::default(),
inject: Default::default(),
compression: Default::default(),
..Default::default()
},
fallback: Default::default(),
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ expression: routes
],
),
headers: None,
cache: Prevent,
compression: None,
},
fallback: Some(
Expand All @@ -88,6 +89,7 @@ expression: routes
true,
),
headers: None,
cache: Prevent,
compression: None,
},
},
Expand All @@ -112,6 +114,7 @@ expression: routes
true,
),
headers: None,
cache: Prevent,
compression: None,
},
fallback: None,
Expand All @@ -135,6 +138,7 @@ expression: routes
true,
),
headers: None,
cache: Prevent,
compression: None,
},
fallback: None,
Expand All @@ -158,6 +162,7 @@ expression: routes
true,
),
headers: None,
cache: Prevent,
compression: None,
},
fallback: None,
Expand Down
10 changes: 10 additions & 0 deletions crates/bsnext_resp/src/cache_opts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#[derive(Debug, Default, PartialEq, Hash, Clone, serde::Deserialize, serde::Serialize)]
pub enum CacheOpts {
/// Try to prevent browsers from caching the responses. This is the default behaviour
#[serde(rename = "prevent")]
#[default]
Prevent,
/// Do not try to prevent browsers from caching the responses.
#[serde(rename = "default")]
Default,
}
1 change: 1 addition & 0 deletions crates/bsnext_resp/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod builtin_strings;
pub mod cache_opts;
pub mod connector;
pub mod debug;
pub mod inject_addition;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ servers:
watch: true
inject: true
headers: ~
cache: prevent
compression: ~
fallback: ~
watchers: []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Input {
true,
),
headers: None,
cache: Prevent,
compression: None,
},
fallback: None,
Expand Down
8 changes: 2 additions & 6 deletions crates/bsnext_system/tests/override_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ use tokio::sync::{mpsc, oneshot};
use tokio_stream::wrappers::ReceiverStream;
use tokio_stream::StreamExt;

async fn test() -> anyhow::Result<()> {
#[actix_rt::test]
pub async fn main() -> Result<(), anyhow::Error> {
let input = r#"
servers:
- name: api
Expand Down Expand Up @@ -83,8 +84,3 @@ servers:
};
Ok(())
}

#[actix_rt::test]
pub async fn main() -> Result<(), anyhow::Error> {
test().await
}

0 comments on commit d619274

Please sign in to comment.