use super::*;
impl Default for CompressConfig {
fn default() -> Self {
Self::new(DEFAULT_MIN_LENGTH)
}
}
impl CompressConfig {
pub fn new(min_length: usize) -> Self {
Self { min_length }
}
pub fn get_min_length(&self) -> usize {
self.min_length
}
pub fn set_min_length(&mut self, min_length: usize) -> &mut Self {
self.min_length = min_length;
self
}
pub fn with_min_length(mut self, min_length: usize) -> Self {
self.set_min_length(min_length);
self
}
}
impl CompressMiddleware {
pub fn init(config: CompressConfig) -> Result<(), String> {
CONFIG
.set(config)
.map_err(|_: CompressConfig| COMPRESS_CONFIG_ALREADY_SET.to_owned())
}
pub fn get() -> Option<&'static CompressConfig> {
CONFIG.get()
}
fn config() -> CompressConfig {
CONFIG.get().copied().unwrap_or_default()
}
fn negotiated_coding(request: &Request) -> Option<Compress> {
let mut total_values: usize = 0;
let mut total_len: usize = 0;
let mut single: Option<&str> = None;
for (key, values) in request.get_headers() {
if !key.eq_ignore_ascii_case(ACCEPT_ENCODING) {
continue;
}
for value in values {
total_values += 1;
total_len = total_len.saturating_add(value.len());
if total_values == 1 {
single = Some(value.as_str());
}
}
}
if total_values == 0 {
return None;
}
if total_values == 1 {
return single.and_then(Compress::from_accept_encoding);
}
let mut joined: String = String::with_capacity(total_len + total_values);
let mut first: bool = true;
for (key, values) in request.get_headers() {
if !key.eq_ignore_ascii_case(ACCEPT_ENCODING) {
continue;
}
for value in values {
if !first {
joined.push_str(COMMA);
}
joined.push_str(value);
first = false;
}
}
Compress::from_accept_encoding(joined)
}
}
impl ServerHook for CompressMiddleware {
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let Some(coding) = Self::negotiated_coding(ctx.get_request()) else {
return Status::Continue;
};
let response: &mut Response = ctx.get_mut_response();
if has_response_header_ci(response, CONTENT_ENCODING)
|| has_no_transform(response)
|| response.get_body().len() < Self::config().get_min_length()
|| has_no_body(response.get_status_code())
|| is_event_stream(response)
{
return Status::Continue;
}
response.set_header(CONTENT_ENCODING, coding.as_str());
vary_accept_encoding(response);
Status::Continue
}
}
impl EntityTag {
fn format_strong_bytes(digest: u64) -> [u8; 18] {
let mut buf: [u8; 18] = [b'"'; 18];
let mut idx: usize = 0;
while idx < 16 {
let shift: u32 = (15 - idx) as u32 * 4;
let nibble: usize = ((digest >> shift) & 0x0f) as usize;
buf[idx + 1] = HEX_LOWER[nibble];
idx += 1;
}
buf
}
pub fn strong(data: &[u8]) -> Self {
let mut hasher: XxHash3_64 = XxHash3_64::default();
hasher.write(data);
let buf: [u8; 18] = Self::format_strong_bytes(hasher.finish());
let tag: String = from_utf8(&buf).unwrap_or_default().to_owned();
Self(tag)
}
pub fn weak(data: &[u8]) -> Self {
let mut hasher: XxHash3_64 = XxHash3_64::default();
hasher.write(data);
let buf: [u8; 18] = Self::format_strong_bytes(hasher.finish());
let mut out: String = String::with_capacity(20);
out.push_str(WEAK_ETAG_PREFIX);
if let Ok(text) = from_utf8(&buf) {
out.push_str(text);
}
Self(out)
}
pub fn is_weak(&self) -> bool {
self.as_str().starts_with(WEAK_ETAG_PREFIX)
}
pub fn opaque_tag(&self) -> &str {
self.as_str()
.strip_prefix(WEAK_ETAG_PREFIX)
.unwrap_or(self.as_str())
}
pub fn weak_eq(&self, other: &Self) -> bool {
self.opaque_tag() == other.opaque_tag()
}
pub fn strong_eq(&self, other: &Self) -> bool {
!self.is_weak() && !other.is_weak() && self.opaque_tag() == other.opaque_tag()
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl ConditionalMiddleware {
fn existing_etag(response: &Response) -> Option<&str> {
response
.get_headers()
.iter()
.find(|(key, _): &(&String, &ResponseHeadersValue)| key.eq_ignore_ascii_case(ETAG))
.and_then(|(_, values): (&String, &ResponseHeadersValue)| {
values.back().map(String::as_str)
})
}
}
impl ServerHook for ConditionalMiddleware {
async fn new(_: &mut Stream, _: &mut Context) -> Self {
Self
}
async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
let method: &RequestMethod = ctx.get_request().get_method();
if !method.is_get() && !method.is_head() {
return Status::Continue;
}
let status_code: ResponseStatusCode = ctx.get_response().get_status_code();
if !(200..300).contains(&status_code) || has_no_body(status_code) {
return Status::Continue;
}
let matched: bool = if let Some(existing) = Self::existing_etag(ctx.get_response()) {
ctx.get_request().matches_if_none_match(existing)
} else {
let computed: EntityTag = EntityTag::strong(ctx.get_response().get_body());
let is_match: bool = ctx.get_request().matches_if_none_match(computed.as_str());
ctx.get_mut_response().set_header(ETAG, computed.as_str());
is_match
};
if matched {
ctx.get_mut_response()
.set_status_code(HttpStatus::NotModified.code())
.set_body(EMPTY_STR);
}
Status::Continue
}
}