use crate::prelude::{chrono::*, *};
use std::{
borrow::Borrow,
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
pub static HTTP_DATE: &[time::format_description::FormatItem] = time::macros::format_description!("[weekday repr:short case_sensitive:true], [day padding:zero] [month repr:short case_sensitive:true] [year padding:zero repr:full base:calendar sign:automatic] [hour repr:24 padding:zero]:[minute padding:zero]:[second padding:zero] GMT");
pub type FileCache = RwLock<Cache<PathBuf, Bytes>>;
pub type ResponseCache = RwLock<Cache<UriKey, VariedResponse>>;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[must_use]
pub struct PathQuery {
string: String,
query_start: usize,
}
impl PathQuery {
#[inline]
#[must_use]
pub fn path(&self) -> &str {
&self.string[..self.query_start]
}
#[inline]
#[must_use]
pub fn query(&self) -> Option<&str> {
if self.query_start == self.string.len() {
None
} else {
Some(&self.string[self.query_start..])
}
}
pub fn truncate_query(&mut self) {
self.string.truncate(self.query_start);
}
#[inline]
#[must_use]
pub fn into_path(mut self) -> String {
self.truncate_query();
self.string
}
}
impl From<&Uri> for PathQuery {
fn from(uri: &Uri) -> Self {
match uri.query() {
Some(query) => {
let mut string = String::with_capacity(uri.path().len() + query.len());
string.push_str(uri.path());
string.push_str(query);
Self {
string,
query_start: uri.path().len(),
}
}
None => Self {
string: uri.path().to_string(),
query_start: uri.path().len(),
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum UriKey {
Path(String),
PathQuery(PathQuery),
}
impl UriKey {
#[inline]
pub fn path_and_query(uri: &Uri) -> Self {
Self::PathQuery(PathQuery::from(uri))
}
#[inline]
pub fn call_all<T>(
mut self,
mut callback: impl FnMut(&Self) -> Option<T>,
) -> (Self, Option<T>) {
match callback(&self) {
Some(t) => (self, Some(t)),
None => match self {
Self::Path(_) => (self, None),
Self::PathQuery(path_query) => {
self = Self::Path(path_query.into_path());
let result = callback(&self);
(self, result)
}
},
}
}
}
pub fn do_compress(mime: &Mime, check_utf8: impl Fn() -> bool) -> bool {
mime.type_() != mime::IMAGE
&& mime.type_() != mime::FONT
&& mime.type_() != mime::VIDEO
&& mime.type_() != mime::AUDIO
&& mime.type_() != mime::STAR
&& mime != &mime::APPLICATION_PDF
&& mime.subtype() != "zip"
&& mime.subtype() != "zstd"
&& (mime.type_() != mime::APPLICATION
|| (mime.subtype() == mime::JAVASCRIPT
|| mime.subtype() == "graphql"
|| mime.subtype() == mime::JSON
|| mime.subtype() == mime::XML
|| mime.subtype() == "wasm"
|| mime.subtype() == "octet-stream"
|| check_utf8()))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PreferredCompression {
#[cfg(feature = "br")]
Brotli,
#[cfg(feature = "gzip")]
Gzip,
None,
}
impl PreferredCompression {
#[must_use]
pub fn as_str(&self) -> &'static str {
match self {
#[cfg(feature = "br")]
Self::Brotli => "br",
#[cfg(feature = "gzip")]
Self::Gzip => "gzip",
Self::None => "identity",
}
}
}
impl Default for PreferredCompression {
fn default() -> Self {
#[cfg(feature = "br")]
{
PreferredCompression::Brotli
}
#[cfg(all(not(feature = "br"), feature = "gzip"))]
{
PreferredCompression::Gzip
}
#[cfg(all(not(feature = "br"), not(feature = "gzip")))]
{
PreferredCompression::None
}
}
}
#[derive(Debug, Clone)]
pub struct CompressionOptions {
pub preferred: PreferredCompression,
#[cfg(feature = "br")]
pub brotli_level: u32,
#[cfg(feature = "gzip")]
pub gzip_level: u32,
}
#[allow(clippy::derivable_impls)] impl Default for CompressionOptions {
fn default() -> Self {
Self {
preferred: PreferredCompression::default(),
#[cfg(feature = "br")]
brotli_level: 3,
#[cfg(feature = "gzip")]
gzip_level: 1,
}
}
}
#[derive(Debug)]
#[must_use]
pub struct CompressedResponse {
identity: Response<Bytes>,
#[cfg(feature = "gzip")]
gzip: Option<Bytes>,
#[cfg(feature = "br")]
br: Option<Bytes>,
compress: CompressPreference,
}
impl CompressedResponse {
pub(crate) fn new(
mut identity: Response<Bytes>,
compress: CompressPreference,
client_cache: ClientCachePreference,
extension: &str,
disable_client_cache: bool,
) -> Self {
let headers = identity.headers_mut();
Self::set_client_cache(headers, client_cache, disable_client_cache);
Self::add_server_header(headers);
Self::check_content_type(&mut identity, extension);
Self {
identity,
#[cfg(feature = "gzip")]
gzip: None,
#[cfg(feature = "br")]
br: None,
compress,
}
}
#[inline]
pub fn get_identity(&self) -> &Response<Bytes> {
&self.identity
}
pub fn clone_preferred<T>(
&self,
request: &Request<T>,
options: &CompressionOptions,
) -> Result<Response<Bytes>, &'static str> {
let values = match request
.headers()
.get("accept-encoding")
.map(HeaderValue::to_str)
.and_then(Result::ok)
{
Some(header) => utils::list_header(header),
None => Vec::new(),
};
let disable_identity = values
.iter()
.any(|v| v.value == "identity" && v.quality == 0.0);
let only_identity = values.len() == 1
&& values[0]
== utils::ValueQualitySet {
value: "identity",
quality: 1.0,
};
if only_identity {
return Ok(self.clone_identity_set_compression(
Bytes::clone(self.get_identity().body()),
HeaderValue::from_static("identity"),
));
}
#[cfg(any(feature = "gzip", feature = "br"))]
let contains = |name| values.iter().any(|v| v.value == name && v.quality != 0.0);
let mime = self
.get_identity()
.headers()
.get("content-type")
.and_then(|header| header.to_str().ok())
.and_then(|header| header.parse().ok());
debug!("Recognised mime {:?}", &mime);
let (bytes, compression) = match &mime {
Some(mime) => {
if do_compress(mime, || str::from_utf8(self.get_identity().body()).is_ok()) {
match self.compress {
CompressPreference::None => (self.get_identity().body(), "identity"),
CompressPreference::Full => {
#[cfg(feature = "br")]
let contains_br = contains("br");
#[cfg(feature = "gzip")]
let contains_gzip = contains("gzip");
#[allow(unused_mut)]
let mut preferred = match options.preferred.as_str() {
#[cfg(feature = "br")]
"br" if contains_br => {
Some((self.get_br(options.brotli_level), "br"))
}
#[cfg(feature = "gzip")]
"gzip" if contains_gzip => {
Some((self.get_gzip(options.gzip_level), "gzip"))
}
_ => None,
};
#[cfg(feature = "br")]
if preferred.is_none() && contains_br {
preferred = Some((self.get_br(options.brotli_level), "br"));
}
#[cfg(feature = "gzip")]
if preferred.is_none() && contains_gzip {
preferred = Some((self.get_gzip(options.gzip_level), "gzip"));
}
preferred.unwrap_or_else(|| (self.get_identity().body(), "identity"))
}
}
} else {
debug!("Not compressing; filtered out.");
(self.get_identity().body(), "identity")
}
}
None => (self.get_identity().body(), "identity"),
};
if disable_identity && compression == "identity" {
return Err(
"identity compression is the only option, but the client refused to accept it",
);
}
Ok(self.clone_identity_set_compression(
Bytes::clone(bytes),
HeaderValue::from_static(compression),
))
}
#[inline]
fn add_server_header(headers: &mut HeaderMap) {
headers.insert("server", HeaderValue::from_static(SERVER));
}
#[inline]
fn set_client_cache(
headers: &mut HeaderMap,
preference: ClientCachePreference,
disable_client_cache: bool,
) {
let header = if disable_client_cache {
Some(HeaderValue::from_static("no-store"))
} else {
preference.as_header()
};
if let Some(h) = header {
headers.entry("cache-control").or_insert(h);
}
}
fn check_content_type(response: &mut Response<Bytes>, extension: &str) {
fn add_utf_8(headers: &mut HeaderMap, mime: &Mime) {
let charset = if mime.get_param(mime::CHARSET) == Some(mime::UTF_8) {
""
} else {
"; charset=utf-8"
};
let mut header = mime.to_string();
header.push_str(charset);
let content_type =
HeaderValue::from_maybe_shared::<Bytes>(header.into_bytes().into()).unwrap();
headers.insert("content-type", content_type);
}
let utf_8 = response.body().len() < 16 * 1024 && str::from_utf8(response.body()).is_ok();
match response.headers().get("content-type") {
Some(content_type) => {
if let Some(mime_type) = content_type
.to_str()
.ok()
.and_then(|s| s.parse::<Mime>().ok())
{
#[allow(clippy::match_same_arms)] match mime_type.get_param("charset") {
None if utf_8 => {
add_utf_8(response.headers_mut(), &mime_type);
}
Some(_) | None => {}
}
}
}
None if !response.body().is_empty() => {
let mime = if utf_8 {
mime::TEXT_HTML_UTF_8
} else {
mime::APPLICATION_OCTET_STREAM
};
let mime_type = mime_guess::from_ext(extension).first_or(mime);
if utf_8 {
add_utf_8(response.headers_mut(), &mime_type);
} else {
let content_type = HeaderValue::from_maybe_shared::<Bytes>(
mime_type.to_string().into_bytes().into(),
)
.unwrap();
response.headers_mut().insert("content-type", content_type);
}
}
None => {}
}
}
fn clone_identity_set_compression(
&self,
new_data: Bytes,
compression: HeaderValue,
) -> Response<Bytes> {
let response = &self.identity;
let mut builder = Response::builder()
.version(response.version())
.status(response.status());
let mut map = response.headers().clone();
if !new_data.is_empty() {
let headers = &mut map;
debug!(
"Changing content-encoding from {:?}. Has content-type {:?}",
headers.get("content-encoding"),
headers.get("content-type"),
);
headers.insert("content-encoding", compression);
}
*builder.headers_mut().unwrap() = map;
builder.body(new_data).unwrap()
}
#[cfg(feature = "gzip")]
pub fn get_gzip(&self, level: u32) -> &Bytes {
if self.gzip.is_none() {
let bytes = self.identity.body().as_ref();
let mut buffer = utils::WriteableBytes::with_capacity(bytes.len() / 3 + 64);
let mut c = flate2::write::GzEncoder::new(&mut buffer, flate2::Compression::new(level));
c.write_all(bytes).expect("Failed to compress using gzip!");
c.finish().expect("Failed to compress using gzip!");
let buffer = buffer.into_inner();
let buffer = buffer.freeze();
if self.gzip.is_none() {
unsafe { (&mut *{ utils::ref_to_mut(&self.gzip) }).replace(buffer) };
}
}
self.gzip.as_ref().unwrap()
}
#[cfg(feature = "br")]
pub fn get_br(&self, level: u32) -> &Bytes {
if self.br.is_none() {
let bytes = self.identity.body().as_ref();
let mut buffer = utils::WriteableBytes::with_capacity(bytes.len() / 3 + 64);
let mut c = brotli::CompressorWriter::new(&mut buffer, 4096, level, 21);
c.write_all(bytes)
.expect("Failed to compress using Brotli!");
c.flush().expect("Failed to compress using Brotli!");
c.into_inner();
let buffer = buffer.into_inner();
let buffer = buffer.freeze();
if self.br.is_none() {
unsafe { (&mut *{ utils::ref_to_mut(&self.br) }).replace(buffer) };
}
}
self.br.as_ref().unwrap()
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum CompressPreference {
None,
Full,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum CachePreferenceError {
Empty,
Invalid,
ZeroDuration,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum ServerCachePreference {
None,
QueryMatters,
Full,
MaxAge(Duration),
}
impl ServerCachePreference {
#[inline]
#[must_use]
#[allow(clippy::unused_self)]
pub fn cache(self, cache_action: host::CacheAction, method: &Method) -> bool {
let of_self = match self {
Self::None => false,
Self::QueryMatters | Self::Full | Self::MaxAge(_) => true,
};
#[allow(clippy::unnested_or_patterns)] let of_response =
cache_action.into_cache() && matches!(method, &Method::GET | &Method::HEAD);
of_self && of_response
}
#[inline]
#[must_use]
pub fn query_matters(self) -> bool {
match self {
Self::None | Self::Full | Self::MaxAge(_) => false,
Self::QueryMatters => true,
}
}
}
impl str::FromStr for ServerCachePreference {
type Err = CachePreferenceError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"full" => ServerCachePreference::Full,
"query_matters" | "query-matters" | "QueryMatters" | "queryMatters" => {
ServerCachePreference::QueryMatters
}
"none" => ServerCachePreference::None,
"" => return Err(CachePreferenceError::Empty),
_ => {
if let Some(integer) = s.strip_suffix('s') {
if let Ok(integer) = integer.parse::<u64>() {
if integer == 0 {
return Err(CachePreferenceError::ZeroDuration);
}
return Ok(Self::MaxAge(integer.std_seconds()));
}
}
return Err(CachePreferenceError::Invalid);
}
})
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum ClientCachePreference {
Ignore,
None,
Changing,
Full,
MaxAge(Duration),
}
impl ClientCachePreference {
#[inline]
#[must_use]
pub fn as_header(self) -> Option<HeaderValue> {
Some(match self {
Self::Ignore => return None,
Self::None => HeaderValue::from_static("no-store"),
Self::Changing => HeaderValue::from_static("max-age=2"),
Self::Full => HeaderValue::from_static("public, max-age=604800, immutable"),
Self::MaxAge(duration) => {
let bytes = build_bytes!(
b"public, max-age=",
(duration.as_secs() + u64::from(duration.subsec_nanos() > 0))
.to_string()
.as_bytes(),
b", immutable"
);
HeaderValue::from_maybe_shared(bytes).unwrap()
}
})
}
}
impl str::FromStr for ClientCachePreference {
type Err = CachePreferenceError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some(integer) = s.strip_suffix('s') {
if let Ok(integer) = integer.parse::<u64>() {
if integer == 0 {
return Err(CachePreferenceError::ZeroDuration);
}
return Ok(Self::MaxAge(integer.std_seconds()));
}
}
Ok(match s {
"ignore" => ClientCachePreference::Ignore,
"full" => ClientCachePreference::Full,
"changing" => ClientCachePreference::Changing,
"none" => ClientCachePreference::None,
"" => return Err(CachePreferenceError::Empty),
_ => return Err(CachePreferenceError::Invalid),
})
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum CacheOut<V> {
None,
Present(V),
NotInserted(V),
}
impl<V> CacheOut<V> {
#[inline]
pub fn into_option(self) -> Option<V> {
match self {
Self::None => None,
Self::Present(v) | Self::NotInserted(v) => Some(v),
}
}
pub fn map<K>(self, f: impl FnOnce(V) -> K) -> CacheOut<K> {
match self {
Self::None => CacheOut::None,
Self::NotInserted(v) => CacheOut::NotInserted(f(v)),
Self::Present(v) => CacheOut::Present(f(v)),
}
}
}
pub type CacheItem<T> = (T, (OffsetDateTime, Option<Duration>));
#[derive(Debug)]
#[must_use]
pub struct Cache<K, V, H = DefaultHasher> {
map: HashMap<K, CacheItem<V>>,
max_items: usize,
size_limit: usize,
inserts: usize,
hasher: H,
}
impl<K, V> Cache<K, V, DefaultHasher> {
#[inline]
pub fn new(max_items: usize, size_limit: usize) -> Self {
Self {
map: HashMap::new(),
max_items,
size_limit,
inserts: 0,
hasher: DefaultHasher::new(),
}
}
#[inline]
pub fn with_size_limit(size_limit: usize) -> Self {
Self::new(1024, size_limit)
}
#[inline]
pub fn clear(&mut self) {
self.map.clear();
}
}
impl<K, V> Default for Cache<K, V> {
fn default() -> Self {
Self::new(1024, 4 * 1024 * 1024) }
}
impl<K: Eq + Hash, V, H> Cache<K, V, H> {
#[inline]
pub fn get<Q: ?Sized + Hash + Eq>(&self, key: &Q) -> CacheOut<&V>
where
K: Borrow<Q>,
{
self.get_with_lifetime(key).map(|v| &v.0)
}
pub fn get_with_lifetime<Q: ?Sized + Hash + Eq>(&self, key: &Q) -> CacheOut<&CacheItem<V>>
where
K: Borrow<Q>,
{
match self.map.get(key) {
Some(value_and_lifetime)
if value_and_lifetime.1 .1.map_or(true, |lifetime| {
OffsetDateTime::now_utc() - value_and_lifetime.1 .0 <= lifetime
}) =>
{
CacheOut::Present(value_and_lifetime)
}
Some(_) | None => CacheOut::None,
}
}
#[inline]
pub fn get_mut<Q: ?Sized + Hash + Eq>(&mut self, key: &Q) -> CacheOut<&V>
where
K: Borrow<Q>,
{
self.get_mut_with_lifetime(key).map(|v| &v.0)
}
pub fn get_mut_with_lifetime<Q: ?Sized + Hash + Eq>(
&mut self,
key: &Q,
) -> CacheOut<&mut CacheItem<V>>
where
K: Borrow<Q>,
{
match self.map.get_mut(key) {
Some(value_and_lifetime)
if value_and_lifetime.1 .1.map_or(true, |lifetime| {
OffsetDateTime::now_utc() - value_and_lifetime.1 .0 <= lifetime
}) =>
{
CacheOut::Present(value_and_lifetime)
}
Some(_) => {
CacheOut::None
}
None => CacheOut::None,
}
}
#[inline]
pub fn contains<Q: ?Sized + Hash + Eq>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
{
self.map.contains_key(key)
}
#[inline]
pub fn remove<Q: ?Sized + Hash + Eq>(&mut self, key: &Q) -> CacheOut<V>
where
K: Borrow<Q>,
{
match self.map.remove(key) {
Some((item, _expiry)) => CacheOut::Present(item),
None => CacheOut::None,
}
}
pub fn insert(
&mut self,
value_length: usize,
key: K,
value: V,
lifetime: Option<Duration>,
) -> CacheOut<V>
where
H: Hasher,
{
if value_length >= self.size_limit {
return CacheOut::NotInserted(value);
}
self.inserts += 1;
if self.map.len() >= self.max_items {
self.discard_one();
}
match self
.map
.insert(key, (value, (OffsetDateTime::now_utc(), lifetime)))
{
Some((v, _expiry)) => CacheOut::Present(v),
None => CacheOut::None,
}
}
}
impl<K, V, H: Hasher> Cache<K, V, H> {
pub fn feed_hasher(&mut self, data: &[u8]) {
self.hasher.write(data);
}
}
impl<K: Eq + Hash, V, H: Hasher> Cache<K, V, H> {
pub fn discard_one(&mut self) {
let pseudo_random = {
self.feed_hasher(&self.inserts.to_le_bytes());
self.hasher.finish()
};
#[allow(clippy::cast_possible_truncation)]
let position = (pseudo_random % self.map.len() as u64) as usize;
let mut current_position = 0;
self.map.retain(|_, _| {
let result = current_position != position;
current_position += 1;
result
});
}
}
impl<K: Eq + Hash, H: Hasher> Cache<K, VariedResponse, H> {
pub fn cache(&mut self, key: K, response: VariedResponse) -> CacheOut<VariedResponse> {
let lifetime =
parse::CacheControl::from_headers(response.first().0.get_identity().headers())
.ok()
.as_ref()
.and_then(parse::CacheControl::as_freshness)
.map(|s| u64::from(s).std_seconds());
let identity = response.first().0.get_identity().body();
let identity_fragment = &identity[identity.len().saturating_sub(512)..];
self.feed_hasher(identity_fragment);
debug!("Inserted item to cache with lifetime {:?}", lifetime);
self.insert(
response.first().0.get_identity().body().len(),
key,
response,
lifetime,
)
}
}
impl<K: Eq + Hash> Cache<K, Bytes> {
pub fn cache(&mut self, key: K, contents: Bytes) -> CacheOut<Bytes> {
let fragment = &contents[contents.len().saturating_sub(512)..];
self.feed_hasher(fragment);
self.insert(contents.len(), key, contents, None)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn path_query_empty_query_1() {
let uri: Uri = "https://kvarn.org/index.html?".parse().unwrap();
let path_query = PathQuery::from(&uri);
assert_eq!(path_query.query(), None);
}
#[test]
fn path_query_empty_query_2() {
let uri: Uri = "https://kvarn.org/index.html?hi".parse().unwrap();
let path_query = PathQuery::from(&uri);
assert_eq!(path_query.query(), Some("hi"));
}
#[test]
fn path_query_empty_query_3() {
let uri: Uri = "https://kvarn.org/index.html??".parse().unwrap();
let path_query = PathQuery::from(&uri);
assert_eq!(path_query.query(), Some("?"));
}
#[test]
fn path_query_empty_query_4() {
let uri: Uri = "https://kvarn.org/".parse().unwrap();
let path_query = PathQuery::from(&uri);
assert_eq!(path_query.query(), None);
}
}