use std::any::Any;
use glacier::access::Access;
use glacier::middleware::from_fn;
use glacier::prelude::*;
use glacier::testing::TestClient;
#[derive(Clone)]
struct UserAccess;
impl Access for UserAccess {
fn describe(&self) -> String {
"user:1".into()
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[tokio::test]
async fn responses_for_someone_are_private() {
let app = App::new()
.middleware(from_fn(|mut ctx: Context, next: Next| async move {
if ctx.header("authorization").is_some() {
ctx.set_access(UserAccess);
}
next.run(ctx).await
}))
.routes(|r| {
r.get("/page", |_ctx: Context| async { "page" });
r.get("/public", |_ctx: Context| async {
Response::text("public").with_header("cache-control", "public, max-age=60")
});
});
let client = TestClient::new(app);
let res = client.get("/page").await;
assert_eq!(res.header("cache-control"), None);
client.header("authorization", "Bearer x");
let res = client.get("/page").await;
assert_eq!(res.header("cache-control"), Some("private"));
assert_eq!(res.header("vary"), Some("Cookie"));
let res = client.get("/public").await;
assert_eq!(res.header("cache-control"), Some("public, max-age=60"));
}
struct Who(i64);
impl Access for Who {
fn describe(&self) -> String {
format!("user:{}", self.0)
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[tokio::test]
async fn cached_values_for_someone_are_theirs() {
glacier::cache::with_test_store(async {
let ada = Who(1);
let bob = Who(2);
assert_eq!(
glacier::cache::key_for(&ada, "dashboard"),
"user:1/dashboard"
);
let mine: i64 = glacier::cache::fetch_for(
&ada,
"dashboard",
std::time::Duration::from_secs(60),
|| async { Ok(1) },
)
.await
.unwrap();
let theirs: i64 = glacier::cache::fetch_for(
&bob,
"dashboard",
std::time::Duration::from_secs(60),
|| async { Ok(2) },
)
.await
.unwrap();
assert_eq!((mine, theirs), (1, 2));
let again: i64 = glacier::cache::fetch_for(
&ada,
"dashboard",
std::time::Duration::from_secs(60),
|| async { Ok(3) },
)
.await
.unwrap();
assert_eq!(again, 1, "still Ada's");
})
.await;
}