0.34.6_repo_cleanup

This commit is contained in:
Mateusz Gruszczyński committed 2026-10-22 09:31:15 +02:00
1 parent ce1a90397c
commit 133d2f0f91
273 files changed
+5969 -6926

No files matched your search

-19
View File
@@ -1,6 +1,3 @@
/// Transform an eligible response. The call is fail-open for unsupported media,
/// encodings and malformed minifiable content; transport/body collection errors
/// still propagate because the original stream can no longer be replayed safely.
pub async fn apply(
response: Response,
path: &str,
@@ -46,8 +43,6 @@ pub async fn apply(
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok())
else {
// Keep streaming semantics for unknown-size bodies instead of introducing
// unbounded buffering into the dataplane.
return Ok(skip(response, Some(kind), "unknown_length"));
};
if content_length > settings.max_body_bytes {
@@ -64,18 +59,10 @@ pub async fn apply(
let Some(_memory_reservation) =
try_reserve_transform_memory(required_memory, settings.memory_budget_bytes)
else {
// Transformations are an optimization. Under concurrent allocation
// pressure, preserve streaming/origin bytes instead of queueing more
// full-response buffers behind the memory budget.
return Ok(skip(response, Some(kind), "memory_pressure"));
};
let (mut parts, body) = response.into_parts();
// Do not trust Content-Length as a memory bound. A broken or malicious
// upstream can send more bytes than declared; Limited stops aggregation at
// the configured ceiling instead of letting BodyExt::collect grow without
// bound. Once aggregation starts an over-limit stream cannot be replayed
// safely, so it is treated like the other body/transport collection errors.
let raw = Limited::new(body, settings.max_body_bytes)
.collect()
.await
@@ -114,9 +101,6 @@ pub async fn apply(
}
};
if transformed.as_slice() == decoded.as_ref() && encoding.is_none() {
// The origin was explicitly requested without Accept-Encoding and the
// eligible response is already identity. The bytes/validator stay intact,
// but the cache no longer needs an Accept-Encoding variant dimension.
drop_vary_accept_encoding(&mut parts.headers);
parts.extensions.insert(CanonicalIdentity);
parts.extensions.insert(Skipped {
@@ -128,9 +112,6 @@ pub async fn apply(
let original_bytes = decoded.len();
let released_bytes = raw.len().saturating_add(decoded.len());
// The successful transformed response no longer needs the collected origin
// body or decoded temporary buffer. Drop both before building the response so
// large short-lived allocations do not overlap longer than necessary.
drop(decoded);
drop(raw);
trim_allocator_after_large_transform(released_bytes);
-4
View File
@@ -164,8 +164,6 @@ fn decode<'a>(body: &'a [u8], encoding: Option<&str>, limit: usize) -> Result<Co
body.len() <= limit,
"transform body exceeds configured limit"
);
// Identity bodies are already owned by `Bytes` after collection.
// Borrow them instead of creating a second full-size allocation.
Ok(Cow::Borrowed(body))
}
Some("gzip") => {
@@ -205,8 +203,6 @@ fn drop_vary_accept_encoding(headers: &mut HeaderMap) {
.filter(|token| !token.is_empty())
{
if token == "*" {
// `Vary: *` has special semantics and is rejected by the shared
// cache. Do not rewrite it into a different policy.
return;
}
if token.eq_ignore_ascii_case("accept-encoding") {
-3
View File
@@ -52,8 +52,6 @@ pub fn minify(body: &[u8]) -> Result<Vec<u8>> {
last_char = Some(' ');
}
pending_space = false;
// A space before ':' may be a descendant combinator before a pseudo-class.
// E.g. `.card :is(.child)` must not become `.card:is(.child)`.
if matches!(ch, '{' | '}' | ';' | ',' | '>') && last_char == Some(' ') {
out.pop();
}
@@ -73,6 +71,5 @@ fn needs_space(previous: Option<char>, next: Option<char>) -> bool {
return false;
};
!matches!(previous, '{' | '}' | ':' | ';' | ',' | '>')
// A ':' can introduce a pseudo-class after a descendant combinator.
&& !matches!(next, '{' | '}' | ';' | ',' | '>')
}
@@ -8,12 +8,6 @@ enum RawElement {
Pre,
}
/// Conservative HTML minification.
///
/// HTML whitespace can be semantically significant, especially between inline
/// elements, so this transformer deliberately preserves all whitespace. It only
/// removes ordinary comments outside raw-text elements. Conditional comments and
/// comment-looking bytes inside script/style/textarea/pre are preserved.
pub fn minify(body: &[u8]) -> Result<Vec<u8>> {
let input = std::str::from_utf8(body).context("HTML is not UTF-8")?;
let bytes = input.as_bytes();
@@ -130,4 +124,4 @@ fn raw_tag(tag: &str) -> Option<(RawElement, bool, bool)> {
}
#[cfg(test)]
include!("html/tests.rs");
include!("tests.rs");
@@ -1,13 +1,5 @@
use anyhow::{Context, Result};
/// Conservative JavaScript minification without token rewriting.
///
/// JavaScript `/` is context-sensitive (division vs. RegExp literal), so this
/// minifier never guesses. Outside strings/templates/comments it collapses
/// horizontal whitespace only until the first slash on a physical line; the
/// remainder of that line is copied verbatim. This still removes common
/// indentation/alignment whitespace while preserving RegExp bodies, ASI-sensitive
/// line terminators and comment text exactly.
pub fn minify(body: &[u8]) -> Result<Vec<u8>> {
let input = std::str::from_utf8(body).context("JavaScript is not UTF-8")?;
let mut out = String::with_capacity(input.len());
@@ -120,4 +112,4 @@ pub fn minify(body: &[u8]) -> Result<Vec<u8>> {
}
#[cfg(test)]
include!("js/tests.rs");
include!("tests.rs");
@@ -1,9 +1,6 @@
use anyhow::{Context, Result};
use serde::{de::IgnoredAny, Deserialize};
/// Validate JSON without materializing a full `serde_json::Value`, then remove
/// insignificant ASCII whitespace in one pass. This keeps peak memory close to
/// input + output instead of input + parsed tree + serialized output.
pub fn compact(body: &[u8]) -> Result<Vec<u8>> {
let mut deserializer = serde_json::Deserializer::from_slice(body);
IgnoredAny::deserialize(&mut deserializer).context("parse JSON")?;
@@ -35,4 +32,4 @@ pub fn compact(body: &[u8]) -> Result<Vec<u8>> {
}
#[cfg(test)]
include!("json/tests.rs");
include!("tests.rs");
-3
View File
@@ -1,6 +1,3 @@
//! Static-response transformation stage. Transformations run on the identity
//! representation before shared-cache storage and before downstream compression.
include!("model.rs");
include!("compile.rs");
include!("apply.rs");
-31
View File
@@ -37,11 +37,6 @@ pub enum Preset {
Uber,
}
/// Large transformable responses can temporarily own the collected origin body,
/// a decoded buffer and the transformed output at the same time. On glibc, freed
/// pages may remain in malloc arenas for a long time. The systemd unit also caps
/// arena proliferation with `MALLOC_ARENA_MAX=2`; this low-frequency trim handles
/// the large transient buffers without adding a trim syscall to every request.
fn trim_allocator_after_large_transform(released_bytes: usize) {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
{
@@ -78,27 +73,16 @@ fn trim_allocator_after_large_transform(released_bytes: usize) {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Settings {
/// Global kill switch. Per-vhost opt-in is still required.
pub enabled: bool,
/// Last resource profile explicitly selected in the administrator UI. The
/// numeric limits below are authoritative; this field only preserves UI
/// intent across reloads.
pub preset: Option<Preset>,
pub javascript: bool,
pub css: bool,
pub html: bool,
pub svg: bool,
pub json: bool,
/// Optional extension allow-list. Content-Type recognition remains available,
/// but an extension outside this list is never transformed by extension alone.
pub extensions: Vec<String>,
/// Hard aggregation/decode ceiling for transformable static responses.
pub max_body_bytes: usize,
/// Process-wide ceiling for estimated temporary response buffers owned by
/// active transformations. This is a limit, not a pre-allocation.
pub memory_budget_bytes: usize,
/// Process-wide number of transformation attempts allowed to own an active
/// transform slot at the same time. Excess work fails open unchanged.
pub max_inflight: usize,
}
impl Default for Settings {
@@ -156,8 +140,6 @@ impl Settings {
}
}
/// Per-vhost transformation policy. Unlike cache overrides, transformation is
/// deliberately opt-in per vhost even when the global engine is enabled.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Overrides {
@@ -231,8 +213,6 @@ impl Kind {
}
}
/// Origin validators are retained separately because transformed bytes receive
/// a RustProxy validator that must never be sent back to the origin.
#[derive(Debug, Clone)]
pub struct OriginValidators {
pub etag: Option<HeaderValue>,
@@ -246,18 +226,12 @@ pub struct Applied {
pub transformed_bytes: usize,
}
/// Internal observability marker for a response which was examined by the
/// transform stage but intentionally left unchanged. Reasons are fixed tokens
/// and never contain request or response data.
#[derive(Debug, Clone, Copy)]
pub struct Skipped {
pub kind: Option<Kind>,
pub reason: &'static str,
}
/// Marker restored on responses served from a cached transformed
/// representation. It lets diagnostics distinguish a transformed HIT from an
/// ordinary cached object without re-running the transformer.
#[derive(Debug, Clone, Copy)]
pub struct CachedTransformed;
@@ -338,7 +312,6 @@ pub struct MetricsView {
#[derive(Debug, Clone, Copy, Serialize)]
pub struct ResourceUsage {
/// Estimated temporary transform bytes currently reserved by active work.
pub memory_reserved_bytes: usize,
pub memory_budget_bytes: usize,
pub inflight: usize,
@@ -422,9 +395,5 @@ impl Metrics {
}
}
/// Marks a response whose upstream content-negotiation dimension has been
/// normalized to the identity representation. The shared cache can therefore
/// ignore origin `Vary: Accept-Encoding`; downstream compression recreates the
/// client-specific encoding after the cache lookup.
#[derive(Debug, Clone, Copy)]
pub struct CanonicalIdentity;
@@ -1,8 +1,5 @@
use anyhow::{Context, Result};
/// Conservative SVG optimization. Whitespace is preserved because it can be
/// visible inside text/tspan nodes. Only XML comments outside CDATA sections are
/// removed; malformed comment/CDATA markup is left unchanged.
pub fn optimize(body: &[u8]) -> Result<Vec<u8>> {
let input = std::str::from_utf8(body).context("SVG is not UTF-8")?;
let bytes = input.as_bytes();
@@ -51,4 +48,4 @@ fn find_bytes(haystack: &[u8], start: usize, needle: &[u8]) -> Option<usize> {
}
#[cfg(test)]
include!("svg/tests.rs");
include!("tests.rs");