Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache control #210

Merged
merged 11 commits into from
Aug 7, 2020
212 changes: 212 additions & 0 deletions src/cache/cache_control/cache_control.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
use crate::cache::CacheDirective;
use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, CACHE_CONTROL};

use std::fmt::{self, Debug, Write};
use std::iter::Iterator;
use std::option;
use std::slice;

/// A Cache-Control header.
///
/// # Examples
///
/// ```
/// # fn main() -> http_types::Result<()> {
/// #
/// use http_types::Response;
/// use http_types::cache::{CacheControl, CacheDirective};
/// let mut entries = CacheControl::new();
/// entries.push(CacheDirective::Immutable);
/// entries.push(CacheDirective::NoStore);
///
/// let mut res = Response::new(200);
/// entries.apply(&mut res);
///
/// let entries = CacheControl::from_headers(res)?.unwrap();
/// let mut entries = entries.iter();
/// assert_eq!(entries.next().unwrap(), &CacheDirective::Immutable);
/// assert_eq!(entries.next().unwrap(), &CacheDirective::NoStore);
/// #
/// # Ok(()) }
/// ```
pub struct CacheControl {
entries: Vec<CacheDirective>,
}

impl CacheControl {
/// Create a new instance of `CacheControl`.
pub fn new() -> Self {
Self { entries: vec![] }
}

/// Create a new instance from headers.
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought from_headers() was supposed to just be Option<Self>?

And this doesn't actually seem to make use of Result?

(Although I think that in many cases Result<Option<Header>> will probably make sense but is so far inconsistent...)

Copy link
Member Author

@yoshuawuyts yoshuawuyts Aug 4, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from_headers needs to be able to both detect whether a header was found, and whether parsing the header was successful. These are semantically different, and should be handled separately.

However in #99 an argument is made to use Option<Result<Self>> instead, which may actually be better. We should probably adjust all existing from_header methods to this shape, and update this one too (the only existing ones are currently behind an unstable flag, so we're okay).

Copy link
Member

@Fishrock123 Fishrock123 Aug 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On further thought I think that Result<Option<T>> should probably always be preferred, because it allows a seamless transition to e.g. ~ -> Option<T> throws Result if that ever becomes a thing.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The right signature would be -> Option<T> throws Error, but even then it'd be possible to write -> crate::Result<T> throws NoneError. I don't think the possibility of throws is something we should consider as a constraint for any design now. It's unclear if we'll ever have it, and even then the semantics are still undefined.

let mut entries = vec![];
let headers = match headers.as_ref().get(CACHE_CONTROL) {
Some(headers) => headers,
None => return Ok(None),
};

for value in headers {
for part in value.as_str().trim().split(',') {
// Try and parse a directive from a str. If the directive is
// unkown we skip it.
if let Some(entry) = CacheDirective::from_str(part)? {
entries.push(entry);
}
}
}

Ok(Some(Self { entries }))
}

/// Sets the `Server-Timing` header.
pub fn apply(&self, mut headers: impl AsMut<Headers>) {
headers.as_mut().insert(CACHE_CONTROL, self.value());
}

/// Get the `HeaderName`.
pub fn name(&self) -> HeaderName {
CACHE_CONTROL
}

/// Get the `HeaderValue`.
pub fn value(&self) -> HeaderValue {
let mut output = String::new();
for (n, directive) in self.entries.iter().enumerate() {
let directive: HeaderValue = directive.clone().into();
match n {
0 => write!(output, "{}", directive).unwrap(),
_ => write!(output, ", {}", directive).unwrap(),
};
}

// SAFETY: the internal string is validated to be ASCII.
unsafe { HeaderValue::from_bytes_unchecked(output.into()) }
}
/// Push a directive into the list of entries.
pub fn push(&mut self, directive: CacheDirective) {
self.entries.push(directive);
}

/// An iterator visiting all server entries.
pub fn iter(&self) -> Iter<'_> {
Iter {
inner: self.entries.iter(),
}
}

/// An iterator visiting all server entries.
pub fn iter_mut(&mut self) -> IterMut<'_> {
IterMut {
inner: self.entries.iter_mut(),
}
}
}

impl IntoIterator for CacheControl {
type Item = CacheDirective;
type IntoIter = IntoIter;

#[inline]
fn into_iter(self) -> Self::IntoIter {
IntoIter {
inner: self.entries.into_iter(),
}
}
}

impl<'a> IntoIterator for &'a CacheControl {
type Item = &'a CacheDirective;
type IntoIter = Iter<'a>;

#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}

impl<'a> IntoIterator for &'a mut CacheControl {
type Item = &'a mut CacheDirective;
type IntoIter = IterMut<'a>;

#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}

/// A borrowing iterator over entries in `CacheControl`.
#[derive(Debug)]
pub struct IntoIter {
inner: std::vec::IntoIter<CacheDirective>,
}

impl Iterator for IntoIter {
type Item = CacheDirective;

fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}

/// A lending iterator over entries in `CacheControl`.
#[derive(Debug)]
pub struct Iter<'a> {
inner: slice::Iter<'a, CacheDirective>,
}

impl<'a> Iterator for Iter<'a> {
type Item = &'a CacheDirective;

fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}

/// A mutable iterator over entries in `CacheControl`.
#[derive(Debug)]
pub struct IterMut<'a> {
inner: slice::IterMut<'a, CacheDirective>,
}

impl<'a> Iterator for IterMut<'a> {
type Item = &'a mut CacheDirective;

fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}

impl ToHeaderValues for CacheControl {
type Iter = option::IntoIter<HeaderValue>;
fn to_header_values(&self) -> crate::Result<Self::Iter> {
// A HeaderValue will always convert into itself.
Ok(self.value().to_header_values().unwrap())
}
}

impl Debug for CacheControl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut list = f.debug_list();
for directive in &self.entries {
list.entry(directive);
}
list.finish()
}
}
153 changes: 153 additions & 0 deletions src/cache/cache_control/cache_directive.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
use crate::headers::HeaderValue;
use crate::Status;

use std::time::Duration;

/// An HTTP `Cache-Control` directive.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CacheDirective {
/// The response body will not change over time.
Immutable,
/// The maximum amount of time a resource is considered fresh.
MaxAge(Duration),
/// Indicates the client will accept a stale response.
MaxStale(Option<Duration>),
/// A response that will still be fresh for at least the specified duration.
MinFresh(Duration),
/// Once a response is stale, a fresh response must be retrieved.
MustRevalidate,
/// The response may be cached, but must always be revalidated before being used.
NoCache,
/// The response may not be cached.
NoStore,
/// An intermediate cache or proxy should not edit the response body,
/// Content-Encoding, Content-Range, or Content-Type.
NoTransform,
/// Do not use the network for a response.
OnlyIfCached,
/// The response may be stored only by a browser's cache, even if the
/// response is normally non-cacheable.
Private,
/// Like must-revalidate, but only for shared caches (e.g., proxies).
ProxyRevalidate,
/// The response may be stored by any cache, even if the response is normally
/// non-cacheable.
Public,
/// Overrides max-age or the Expires header, but only for shared caches.
SMaxAge(Duration),
/// The client will accept a stale response if retrieving a fresh one fails.
StaleIfError(Duration),
/// Indicates the client will accept a stale response, while asynchronously
/// checking in the background for a fresh one.
StaleWhileRevalidate(Duration),
}

impl CacheDirective {
/// Check whether this directive is valid in an HTTP request.
pub fn valid_in_req(&self) -> bool {
use CacheDirective::*;
matches!(self,
MaxAge(_) | MaxStale(_) | MinFresh(_) | NoCache | NoStore | NoTransform
| OnlyIfCached)
}

/// Check whether this directive is valid in an HTTP response.
pub fn valid_in_res(&self) -> bool {
use CacheDirective::*;
matches!(self,
MustRevalidate
| NoCache
| NoStore
| NoTransform
| Public
| Private
| ProxyRevalidate
| MaxAge(_)
| SMaxAge(_)
| StaleIfError(_)
| StaleWhileRevalidate(_))
}

/// Create an instance from a string slice.
//
// This is a private method rather than a trait because we assume the
// input string is a single-value only. This is upheld by the calling
// function, but we cannot guarantee this to be true in the general
// sense.
pub(crate) fn from_str(s: &str) -> crate::Result<Option<Self>> {
use CacheDirective::*;

let s = s.trim();

// We're dealing with an empty string.
if s.is_empty() {
return Ok(None);
}

s.to_lowercase();
let mut parts = s.split('=');
let next = parts.next().unwrap();

let mut get_dur = || -> crate::Result<Duration> {
let dur = parts.next().status(400)?;
let dur: u64 = dur.parse().status(400)?;
Ok(Duration::new(dur, 0))
};

// This won't panic because each input string has at least one part.
let res = match next {
"immutable" => Some(Immutable),
"no-cache" => Some(NoCache),
"no-store" => Some(NoStore),
"no-transform" => Some(NoTransform),
"only-if-cached" => Some(OnlyIfCached),
"must-revalidate" => Some(MustRevalidate),
"public" => Some(Public),
"private" => Some(Private),
"proxy-revalidate" => Some(ProxyRevalidate),
"max-age" => Some(MaxAge(get_dur()?)),
"max-stale" => match parts.next() {
Some(secs) => {
let dur: u64 = secs.parse().status(400)?;
Some(MaxStale(Some(Duration::new(dur, 0))))
}
None => Some(MaxStale(None)),
},
"min-fresh" => Some(MinFresh(get_dur()?)),
"s-maxage" => Some(SMaxAge(get_dur()?)),
"stale-if-error" => Some(StaleIfError(get_dur()?)),
"stale-while-revalidate" => Some(StaleWhileRevalidate(get_dur()?)),
_ => None,
};
Ok(res)
}
}

impl From<CacheDirective> for HeaderValue {
fn from(directive: CacheDirective) -> Self {
use CacheDirective::*;
let h = |s: String| unsafe { HeaderValue::from_bytes_unchecked(s.into_bytes()) };

match directive {
Immutable => h("immutable".to_string()),
MaxAge(dur) => h(format!("max-age={}", dur.as_secs())),
MaxStale(dur) => match dur {
Some(dur) => h(format!("max-stale={}", dur.as_secs())),
None => h("max-stale".to_string()),
},
MinFresh(dur) => h(format!("min-fresh={}", dur.as_secs())),
MustRevalidate => h("must-revalidate".to_string()),
NoCache => h("no-cache".to_string()),
NoStore => h("no-store".to_string()),
NoTransform => h("no-transform".to_string()),
OnlyIfCached => h("only-if-cached".to_string()),
Private => h("private".to_string()),
ProxyRevalidate => h("proxy-revalidate".to_string()),
Public => h("public".to_string()),
SMaxAge(dur) => h(format!("s-max-age={}", dur.as_secs())),
StaleIfError(dur) => h(format!("stale-if-error={}", dur.as_secs())),
StaleWhileRevalidate(dur) => h(format!("stale-while-revalidate={}", dur.as_secs())),
}
}
}
Loading