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
}
}
impl CompressMiddleware {
pub fn init(config: CompressConfig) -> Result<(), String> {
CONFIG
.set(config)
.map_err(|_: CompressConfig| COMPRESS_CONFIG_ALREADY_SET.to_owned())
}
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 {
pub fn strong(data: &[u8]) -> Self {
let mut hasher: XxHash3_64 = XxHash3_64::default();
hasher.write(data);
Self(format!(
"{ENTITY_TAG_QUOTE}{:016x}{ENTITY_TAG_QUOTE}",
hasher.finish()
))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl ConditionalMiddleware {
fn entity_tag(response: &mut Response) -> EntityTag {
let existing: Option<String> = response
.get_headers()
.iter()
.find(|(key, _): &(&String, &ResponseHeadersValue)| key.eq_ignore_ascii_case(ETAG))
.and_then(|(_, values): (&String, &ResponseHeadersValue)| values.back().cloned());
match existing {
Some(etag) => EntityTag(etag),
None => {
let etag: EntityTag = EntityTag::strong(response.get_body());
response.set_header(ETAG, etag.as_str());
etag
}
}
}
}
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 etag: EntityTag = Self::entity_tag(ctx.get_mut_response());
if ctx.get_request().matches_if_none_match(etag.as_str()) {
ctx.get_mut_response()
.set_status_code(HttpStatus::NotModified.code())
.set_body(EMPTY_STR);
}
Status::Continue
}
}