⚡ ETag conditional GET so polled reads become cheap 304s
Browse files at this commita9627787e16bebc66200c3781eb9fb5467bb8335Parent: f1a8cf3- feat
- ⚡ ETag conditional GET so polled reads become cheap 304s
4 changed files +275 -0
- src/lib.rs +4 -0
- src/web/etag.rs +121 -0
- src/web/mod.rs +1 -0
- tests/etag.rs +149 -0
src/lib.rsmodified+4 -0
| @@ -132,6 +132,10 @@ pub fn build_router(state: AppState) -> Router { | |||
| 132 | router | 132 | router |
| 133 | .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) | 133 | .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) |
| 134 | .with_state(state) | 134 | .with_state(state) |
| 135 | + // Conditional-GET: revalidatable `ETag` on 200 JSON GETs, `304` on a | ||
| 136 | + // matching `If-None-Match`. Innermost, so it sees the handler's own | ||
| 137 | + // response (mutations and errors pass straight through untouched). | ||
| 138 | + .layer(middleware::from_fn(web::etag::etag)) | ||
| 135 | .layer(middleware::from_fn(move |req: Request, next: Next| { | 139 | .layer(middleware::from_fn(move |req: Request, next: Next| { |
| 136 | let health = db_up.clone(); | 140 | let health = db_up.clone(); |
| 137 | async move { db_guard(health, req, next).await } | 141 | async move { db_guard(health, req, next).await } |
src/web/etag.rsadded+121 -0
| @@ -0,0 +1,121 @@ | |||
| 1 | +//! Conditional-GET (`ETag` / `If-None-Match` → `304 Not Modified`) middleware. | ||
| 2 | +//! | ||
| 3 | +//! The frontend polls its list endpoints often; this makes an unchanged poll a | ||
| 4 | +//! cheap header-only `304` instead of a full JSON re-send (the browser HTTP | ||
| 5 | +//! cache revalidates on its own once we emit the headers — no client change). | ||
| 6 | +//! | ||
| 7 | +//! Scoped tightly on purpose. Only a `GET` whose handler returned a | ||
| 8 | +//! `200 application/json` response is touched; everything else passes through | ||
| 9 | +//! untouched: | ||
| 10 | +//! * mutations (`POST`/`PATCH`/`DELETE`) and their non-`200` results, | ||
| 11 | +//! * errors, redirects, `204`s, | ||
| 12 | +//! * `text/event-stream` (SSE) and any streamed body — they carry no | ||
| 13 | +//! `Content-Length`, so they are never buffered (buffering one would hang), | ||
| 14 | +//! * file blobs (`image/*`, downloads) — non-JSON, so their own `no-store` | ||
| 15 | +//! survives untouched. | ||
| 16 | +//! | ||
| 17 | +//! The validator is a strong `ETag` — a `DefaultHasher` (SipHash) digest of the | ||
| 18 | +//! body bytes. This is cache validation, not security, so a fast dependency-free | ||
| 19 | +//! hasher is the right tool; no crypto dep is pulled in for it. | ||
| 20 | + | ||
| 21 | +use std::collections::hash_map::DefaultHasher; | ||
| 22 | +use std::hash::{Hash, Hasher}; | ||
| 23 | + | ||
| 24 | +use axum::body::{Body, HttpBody}; | ||
| 25 | +use axum::extract::Request; | ||
| 26 | +use axum::http::header::{CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE, ETAG, IF_NONE_MATCH}; | ||
| 27 | +use axum::http::{HeaderValue, Method, StatusCode}; | ||
| 28 | +use axum::middleware::Next; | ||
| 29 | +use axum::response::Response; | ||
| 30 | + | ||
| 31 | +/// Bodies larger than this are streamed through without buffering — JSON pages | ||
| 32 | +/// sit far below it, so the cap only bounds worst-case memory. A response whose | ||
| 33 | +/// `Content-Length` exceeds it (or is absent, i.e. a stream) skips the feature. | ||
| 34 | +const MAX_BODY: u64 = 1 << 20; // 1 MiB | ||
| 35 | + | ||
| 36 | +/// Add an `ETag` + revalidation headers to `200` JSON `GET`s, and short-circuit | ||
| 37 | +/// a matching `If-None-Match` to a bodyless `304`. | ||
| 38 | +pub async fn etag(request: Request, next: Next) -> Response { | ||
| 39 | + // `next.run` consumes the request, so capture the precondition up front. | ||
| 40 | + let is_get = request.method() == Method::GET; | ||
| 41 | + let if_none_match = request.headers().get(IF_NONE_MATCH).cloned(); | ||
| 42 | + | ||
| 43 | + let response = next.run(request).await; | ||
| 44 | + | ||
| 45 | + if !is_get || response.status() != StatusCode::OK || !is_json(&response) { | ||
| 46 | + return response; | ||
| 47 | + } | ||
| 48 | + // A handler that set its own `ETag` owns its validation — its validator | ||
| 49 | + // scheme need not be a body hash, so we neither overwrite it nor run our | ||
| 50 | + // hash/304 logic against it. Pass it straight through. (No JSON GET handler | ||
| 51 | + // does this today; this is preemptive.) | ||
| 52 | + if response.headers().contains_key(ETAG) { | ||
| 53 | + return response; | ||
| 54 | + } | ||
| 55 | + // Buffer only an already-measured, bounded body. A body with no known upper | ||
| 56 | + // size is a stream (SSE) — never buffer that; over the cap, leave it alone. | ||
| 57 | + // (`Content-Length` isn't a header yet here — hyper writes it downstream — | ||
| 58 | + // so the size hint is the pre-buffer measurement.) | ||
| 59 | + match response.body().size_hint().upper() { | ||
| 60 | + Some(len) if len <= MAX_BODY => {} | ||
| 61 | + _ => return response, | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + let (mut parts, body) = response.into_parts(); | ||
| 65 | + let Ok(bytes) = axum::body::to_bytes(body, MAX_BODY as usize).await else { | ||
| 66 | + // Unreachable given the Content-Length check above; a truncated body is | ||
| 67 | + // worse than a missed cache, so fail closed on the empty-parts path. | ||
| 68 | + return Response::from_parts(parts, Body::empty()); | ||
| 69 | + }; | ||
| 70 | + | ||
| 71 | + let tag = compute_etag(&bytes); | ||
| 72 | + let tag_value = HeaderValue::from_str(&tag).expect("hex etag is a valid header value"); | ||
| 73 | + parts.headers.insert(ETAG, tag_value); | ||
| 74 | + // `no-cache` = store but revalidate every time — this is what makes the | ||
| 75 | + // browser resend `If-None-Match` on the next poll. Without it the ETag is | ||
| 76 | + // inert. `private`: these are per-user authenticated responses. But if the | ||
| 77 | + // handler set its own directive, it knows best — leave it untouched. | ||
| 78 | + if !parts.headers.contains_key(CACHE_CONTROL) { | ||
| 79 | + parts.headers.insert( | ||
| 80 | + CACHE_CONTROL, | ||
| 81 | + HeaderValue::from_static("private, no-cache"), | ||
| 82 | + ); | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + if matches(if_none_match.as_ref(), &tag) { | ||
| 86 | + parts.status = StatusCode::NOT_MODIFIED; | ||
| 87 | + parts.headers.remove(CONTENT_LENGTH); | ||
| 88 | + parts.headers.remove(CONTENT_TYPE); | ||
| 89 | + return Response::from_parts(parts, Body::empty()); | ||
| 90 | + } | ||
| 91 | + | ||
| 92 | + Response::from_parts(parts, Body::from(bytes)) | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// A JSON response — the only shape worth revalidating. Excludes SSE, blobs, | ||
| 96 | +/// and Swagger HTML. | ||
| 97 | +fn is_json(response: &Response) -> bool { | ||
| 98 | + response | ||
| 99 | + .headers() | ||
| 100 | + .get(CONTENT_TYPE) | ||
| 101 | + .and_then(|v| v.to_str().ok()) | ||
| 102 | + .is_some_and(|ct| ct.starts_with("application/json")) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// Strong `ETag` for `bytes`, formatted as a quoted hex string. | ||
| 106 | +fn compute_etag(bytes: &[u8]) -> String { | ||
| 107 | + let mut hasher = DefaultHasher::new(); | ||
| 108 | + bytes.hash(&mut hasher); | ||
| 109 | + format!("\"{:016x}\"", hasher.finish()) | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// Strong `If-None-Match` compare: `*` matches anything, otherwise the (comma- | ||
| 113 | +/// separated) candidate list must contain our exact quoted tag. A weak | ||
| 114 | +/// validator `W/"…"` never equals our strong tag, so it correctly misses. | ||
| 115 | +fn matches(if_none_match: Option<&HeaderValue>, tag: &str) -> bool { | ||
| 116 | + let Some(value) = if_none_match.and_then(|v| v.to_str().ok()) else { | ||
| 117 | + return false; | ||
| 118 | + }; | ||
| 119 | + let value = value.trim(); | ||
| 120 | + value == "*" || value.split(',').map(str::trim).any(|candidate| candidate == tag) | ||
| 121 | +} | ||
src/web/mod.rsmodified+1 -0
| @@ -10,6 +10,7 @@ pub mod auth; | |||
| 10 | pub mod bank_questions; | 10 | pub mod bank_questions; |
| 11 | pub mod chatbot; | 11 | pub mod chatbot; |
| 12 | pub mod courses; | 12 | pub mod courses; |
| 13 | +pub mod etag; | ||
| 13 | pub mod events; | 14 | pub mod events; |
| 14 | pub mod exam_ws; | 15 | pub mod exam_ws; |
| 15 | pub mod exams; | 16 | pub mod exams; |
tests/etag.rsadded+149 -0
| @@ -0,0 +1,149 @@ | |||
| 1 | +//! Conditional-GET: the ETag middleware emits a revalidatable `ETag` + | ||
| 2 | +//! `Cache-Control` on `200` JSON GETs, answers a matching `If-None-Match` with | ||
| 3 | +//! a bodyless `304`, and never touches a mutation. | ||
| 4 | + | ||
| 5 | +mod common; | ||
| 6 | + | ||
| 7 | +use axum::Router; | ||
| 8 | +use axum::body::Body; | ||
| 9 | +use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG}; | ||
| 10 | +use axum::http::{HeaderMap, Request, StatusCode}; | ||
| 11 | +use axum::middleware; | ||
| 12 | +use axum::response::IntoResponse; | ||
| 13 | +use axum::routing::get as route_get; | ||
| 14 | +use common::mem_app; | ||
| 15 | +use tower::ServiceExt; | ||
| 16 | + | ||
| 17 | +/// Wrap a one-route router in the real ETag middleware — lets a test stand up a | ||
| 18 | +/// JSON GET whose handler pre-sets its own cache headers (no such endpoint | ||
| 19 | +/// exists in the app, so it can't be exercised in-tree). | ||
| 20 | +fn behind_etag(router: Router) -> Router { | ||
| 21 | + router.layer(middleware::from_fn(hezarfen_backend::web::etag::etag)) | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +/// `GET uri`, optionally carrying an `If-None-Match`. Returns status, headers, | ||
| 25 | +/// and the (possibly empty) body bytes. | ||
| 26 | +async fn get( | ||
| 27 | + app: &axum::Router, | ||
| 28 | + uri: &str, | ||
| 29 | + if_none_match: Option<&str>, | ||
| 30 | +) -> (StatusCode, HeaderMap, Vec<u8>) { | ||
| 31 | + let mut builder = Request::builder().method("GET").uri(uri); | ||
| 32 | + if let Some(v) = if_none_match { | ||
| 33 | + builder = builder.header("if-none-match", v); | ||
| 34 | + } | ||
| 35 | + let res = app | ||
| 36 | + .clone() | ||
| 37 | + .oneshot(builder.body(Body::empty()).unwrap()) | ||
| 38 | + .await | ||
| 39 | + .unwrap(); | ||
| 40 | + let status = res.status(); | ||
| 41 | + let headers = res.headers().clone(); | ||
| 42 | + let bytes = axum::body::to_bytes(res.into_body(), usize::MAX) | ||
| 43 | + .await | ||
| 44 | + .unwrap() | ||
| 45 | + .to_vec(); | ||
| 46 | + (status, headers, bytes) | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +#[tokio::test] | ||
| 50 | +async fn get_carries_etag_and_revalidation() { | ||
| 51 | + let app = mem_app().await; | ||
| 52 | + let (status, headers, body) = get(&app, "/health", None).await; | ||
| 53 | + assert_eq!(status, StatusCode::OK); | ||
| 54 | + assert!(headers.get("etag").is_some(), "a 200 GET carries an ETag"); | ||
| 55 | + assert_eq!( | ||
| 56 | + headers.get("cache-control").unwrap(), | ||
| 57 | + "private, no-cache", | ||
| 58 | + "no-cache is what makes the browser revalidate" | ||
| 59 | + ); | ||
| 60 | + assert!(!body.is_empty(), "the first fetch returns the body"); | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +#[tokio::test] | ||
| 64 | +async fn matching_if_none_match_gets_304_empty() { | ||
| 65 | + let app = mem_app().await; | ||
| 66 | + let (_, headers, _) = get(&app, "/health", None).await; | ||
| 67 | + let etag = headers.get("etag").unwrap().to_str().unwrap().to_string(); | ||
| 68 | + | ||
| 69 | + // The same fetch with that validator revalidates to a bodyless 304. | ||
| 70 | + let (status, headers, body) = get(&app, "/health", Some(&etag)).await; | ||
| 71 | + assert_eq!(status, StatusCode::NOT_MODIFIED); | ||
| 72 | + assert!(body.is_empty(), "a 304 carries no body"); | ||
| 73 | + assert_eq!(headers.get("etag").unwrap().to_str().unwrap(), etag); | ||
| 74 | + | ||
| 75 | + // A stale validator still gets the full 200 payload. | ||
| 76 | + let (status, _, body) = get(&app, "/health", Some("\"deadbeef\"")).await; | ||
| 77 | + assert_eq!(status, StatusCode::OK); | ||
| 78 | + assert!(!body.is_empty()); | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +#[tokio::test] | ||
| 82 | +async fn handler_cache_control_is_not_overwritten() { | ||
| 83 | + async fn handler() -> impl IntoResponse { | ||
| 84 | + ( | ||
| 85 | + [ | ||
| 86 | + (CONTENT_TYPE, "application/json"), | ||
| 87 | + (CACHE_CONTROL, "public, max-age=60"), | ||
| 88 | + ], | ||
| 89 | + "{\"a\":1}", | ||
| 90 | + ) | ||
| 91 | + } | ||
| 92 | + let app = behind_etag(Router::new().route("/x", route_get(handler))); | ||
| 93 | + let (status, headers, _) = get(&app, "/x", None).await; | ||
| 94 | + assert_eq!(status, StatusCode::OK); | ||
| 95 | + // We still add our validator... | ||
| 96 | + assert!(headers.get("etag").is_some(), "no handler ETag, so we set one"); | ||
| 97 | + // ...but the handler's own directive wins. | ||
| 98 | + assert_eq!(headers.get("cache-control").unwrap(), "public, max-age=60"); | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +#[tokio::test] | ||
| 102 | +async fn handler_owned_etag_passes_through_and_never_304s() { | ||
| 103 | + async fn handler() -> impl IntoResponse { | ||
| 104 | + ( | ||
| 105 | + [ | ||
| 106 | + (CONTENT_TYPE, "application/json"), | ||
| 107 | + (ETAG, "\"handler-owned\""), | ||
| 108 | + ], | ||
| 109 | + "{\"a\":1}", | ||
| 110 | + ) | ||
| 111 | + } | ||
| 112 | + let app = behind_etag(Router::new().route("/x", route_get(handler))); | ||
| 113 | + | ||
| 114 | + // The handler's ETag is left exactly as-is; no Cache-Control is imposed. | ||
| 115 | + let (status, headers, body) = get(&app, "/x", None).await; | ||
| 116 | + assert_eq!(status, StatusCode::OK); | ||
| 117 | + assert_eq!(headers.get("etag").unwrap(), "\"handler-owned\""); | ||
| 118 | + assert!(headers.get("cache-control").is_none()); | ||
| 119 | + assert!(!body.is_empty()); | ||
| 120 | + | ||
| 121 | + // Even If-None-Match matching that ETag stays a full 200 — our body-hash | ||
| 122 | + // 304 logic never runs against a handler's own validator. | ||
| 123 | + let (status, _, body) = get(&app, "/x", Some("\"handler-owned\"")).await; | ||
| 124 | + assert_eq!(status, StatusCode::OK); | ||
| 125 | + assert!(!body.is_empty()); | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +#[tokio::test] | ||
| 129 | +async fn mutations_are_never_etagged() { | ||
| 130 | + let app = mem_app().await; | ||
| 131 | + let creds = serde_json::json!({ "username": "ann", "password": "secret1" }); | ||
| 132 | + let res = app | ||
| 133 | + .clone() | ||
| 134 | + .oneshot( | ||
| 135 | + Request::builder() | ||
| 136 | + .method("POST") | ||
| 137 | + .uri("/auth/register") | ||
| 138 | + .header("content-type", "application/json") | ||
| 139 | + .body(Body::from(creds.to_string())) | ||
| 140 | + .unwrap(), | ||
| 141 | + ) | ||
| 142 | + .await | ||
| 143 | + .unwrap(); | ||
| 144 | + assert_eq!(res.status(), StatusCode::CREATED); | ||
| 145 | + assert!( | ||
| 146 | + res.headers().get("etag").is_none(), | ||
| 147 | + "a mutation is never given an ETag" | ||
| 148 | + ); | ||
| 149 | +} | ||