Skip to main content

Conditional

Struct Conditional 

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

Extractor for the request’s If-None-Match, to answer 304 Not Modified without rendering.

Like Rails’ fresh_when. Only GET and HEAD requests are considered; for other methods (and when the header is absent or not ASCII) the client is never fresh. Extraction never fails. Comparison is weak (RFC 9110): W/"x" matches "x", and * matches any tag. Default is a request without the header.

The handler still runs its database queries to build the ETag; a 304 skips only rendering and the body, saving CPU and bandwidth.

§Examples

use axum::response::Response;
use ocre::{Result, cache::{CacheControl, Conditional, ETag}};

async fn show(conditional: Conditional) -> Result<Response> {
    let post = ("Hello", 1767225600); // e.g. post::find(&ctx, id).await?.or_404()?
    let etag = ETag::of(&post)?; // everything the page shows
    conditional.fresh_when(etag, CacheControl::no_cache(), || Ok(format!("<h1>{}</h1>", post.0)))
}

let response = pollster::block_on(show(Conditional::default()))?;
assert_eq!(response.status(), 200);

Implementations§

Source§

impl Conditional

Source

pub fn is_fresh(&self, etag: &ETag) -> bool

Whether the client already has the version etag.

Always false for requests other than GET and HEAD, and when the request had no If-None-Match.

§Examples
use axum::{extract::FromRequestParts, http::Request};
use ocre::cache::{Conditional, ETag};

let etag = ETag::new("v1");
let (mut parts, ()) = Request::get("/").header("If-None-Match", etag.as_str()).body(()).unwrap().into_parts();
let conditional = pollster::block_on(Conditional::from_request_parts(&mut parts, &())).unwrap();
assert!(conditional.is_fresh(&etag));
assert!(!conditional.is_fresh(&ETag::new("v2")));
Source

pub fn fresh_when<R: IntoResponse>( &self, etag: ETag, cache_control: CacheControl, render: impl FnOnce() -> Result<R>, ) -> Result<Response>

Answers 304 Not Modified when the client’s copy is current, or else renders the page.

When is_fresh, the response is a 304 with the ETag and Cache-Control headers and no body, and render is not called. Otherwise render runs and its response gets both headers.

§Errors

Whatever render returns; a 304 never fails.

§Examples
use axum::{extract::FromRequestParts, http::Request};
use ocre::cache::{CacheControl, Conditional, ETag};

let response = Conditional::default().fresh_when(ETag::new("v1"), CacheControl::no_cache(), || Ok("page"))?;
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["cache-control"], "private, no-cache");

let etag = ETag::new("v1");
let (mut parts, ()) = Request::get("/").header("If-None-Match", etag.as_str()).body(()).unwrap().into_parts();
let conditional = pollster::block_on(Conditional::from_request_parts(&mut parts, &())).unwrap();
let response = conditional.fresh_when(etag, CacheControl::no_cache(), || -> ocre::Result<&str> {
    unreachable!("not rendered")
})?;
assert_eq!(response.status(), 304);

Trait Implementations§

Source§

impl Clone for Conditional

Source§

fn clone(&self) -> Conditional

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Conditional

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Conditional

Source§

fn default() -> Conditional

Returns the “default value” for a type. Read more
Source§

impl<S: Send + Sync> FromRequestParts<S> for Conditional

Source§

type Rejection = Infallible

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

async fn from_request_parts( parts: &mut Parts, _state: &S, ) -> Result<Self, Self::Rejection>

Perform the extraction.

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
§

fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

Perform the extraction.
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.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V