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

-38
View File
@@ -216,8 +216,6 @@ pub enum SymlinkPolicy {
InsideRoot,
}
/// Opt-in kernel zero-copy for suitable Linux plain HTTP/1.1 static GETs.
/// Other requests continue through the original streaming implementation.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum SendfileMode {
@@ -231,14 +229,12 @@ pub enum SendfileMode {
pub struct RewriteRule {
pub pattern: String,
pub replacement: String,
/// `None` means an internal rewrite. Redirects are limited to 301/302/307/308.
pub status: Option<u16>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct CacheRule {
/// `ext:<extension>` or `mime:<prefix>`.
pub matcher: String,
pub cache_control: String,
}
@@ -267,12 +263,9 @@ impl Default for Precompressed {
#[serde(default, deny_unknown_fields)]
pub struct Php {
pub enabled: bool,
/// Safely split `/script.php/extra/path` into SCRIPT_FILENAME + PATH_INFO.
/// Disabled by default because it changes URL-to-script resolution semantics.
pub path_info: bool,
#[serde(default = "default_php_extensions")]
pub extensions: Vec<String>,
/// `unix:/run/php/php-fpm.sock` or `tcp:127.0.0.1:9000`.
pub endpoint: String,
#[serde(default = "default_php_connect_timeout_ms")]
pub connect_timeout_ms: u64,
@@ -280,20 +273,14 @@ pub struct Php {
pub request_timeout_ms: u64,
#[serde(default = "default_php_max_concurrent_requests")]
pub max_concurrent_requests: usize,
/// Forward the inbound Authorization header as HTTP_AUTHORIZATION.
#[serde(default = "default_php_pass_authorization")]
pub pass_authorization: bool,
/// Optional RustProxy-side request-body limit for PHP. 0 keeps the body unlimited here.
pub max_request_body_bytes: u64,
/// Maximum bytes accepted before the CGI response-header terminator.
#[serde(default = "default_php_max_response_header_bytes")]
pub max_response_header_bytes: usize,
/// Maximum PHP-FPM stderr bytes retained for one request diagnostic log entry.
#[serde(default = "default_php_stderr_log_bytes")]
pub stderr_log_bytes: usize,
/// Trusted operator-defined static FastCGI parameters. Core CGI/HTTP/PHP_* names are reserved.
pub custom_params: BTreeMap<String, String>,
/// Trusted operator-defined PHP INI overrides encoded through a single PHP_VALUE parameter.
pub php_values: BTreeMap<String, String>,
pub php_admin_values: BTreeMap<String, String>,
}
@@ -319,8 +306,6 @@ impl Default for Php {
}
}
/// Reusable PHP-FPM configuration. A Web Service can reference one profile or
/// keep its local `php` settings. Profiles are part of the revisioned Config.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct PhpFpmProfile {
@@ -332,57 +317,34 @@ pub struct PhpFpmProfile {
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct Hardening {
/// Reject high-confidence exploit probes and sensitive control/backup paths.
pub block_common_attacks: bool,
/// Remove implementation/fingerprint response headers from Web Server/PHP responses.
pub strip_unnecessary_headers: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Service {
/// Stable configuration identifier referenced by vhosts/locations.
pub id: String,
/// Human-readable service name shown in the administration UI.
pub name: String,
pub document_root: PathBuf,
pub index: Vec<String>,
pub directory_listing: bool,
/// Transport-only preference: it must not rotate cache identity.
pub sendfile: SendfileMode,
/// Optional per-extension MIME overrides. Keys are extensions without a leading dot.
pub mime_types: BTreeMap<String, String>,
/// Fallback MIME type used when neither an override nor a built-in mapping exists.
pub default_mime_type: String,
/// Browser/proxy cache policy emitted for static file responses. Location/vhost
/// response-header rules run later and can intentionally override this value.
pub cache_control: Option<String>,
/// More specific cache policy rules evaluated before `cache_control`.
pub cache_rules: Vec<CacheRule>,
/// Fixed response headers emitted by this Web Service. Vhost/location response
/// headers still run later and remain authoritative.
pub response_headers: BTreeMap<String, String>,
/// Nginx-style file candidates, e.g. `$uri`, `$uri/`, `/index.html`.
pub try_files: Vec<String>,
/// Regex rewrite/redirect rules evaluated before `try_files`.
pub rewrites: Vec<RewriteRule>,
/// Serve pre-generated `.br`/`.gz` sidecars when accepted by the client.
pub precompressed: Precompressed,
/// Optional downstream dynamic-compression override. Codecs remain global.
pub compression: crate::compression::Overrides,
/// Extensions that should be downloaded as attachments.
pub download_extensions: Vec<String>,
/// Symlink handling. The conservative default is `deny`.
pub symlink_policy: SymlinkPolicy,
/// Optional reference to a shared FPM profile; `php` stays the standalone
/// configuration and is preserved when attaching/detaching a profile.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub php_profile_id: Option<String>,
/// Optional FastCGI/PHP-FPM execution for configured script extensions.
pub php: Php,
/// Optional bounded Apache .htaccess compatibility layer compiled at Web Service apply time.
pub htaccess: HtaccessConfig,
/// Optional Web Service hardening. This is intentionally narrower than a generic WAF.
pub hardening: Hardening,
}
-7
View File
@@ -178,8 +178,6 @@ pub(super) fn fastcgi_params(
params.insert("CONTENT_LENGTH".into(), value.into());
}
for (name, value) in headers {
// HTTP_PROXY is a well-known CGI/FastCGI injection vector (httpoxy).
// This must never depend on the optional Web Service hardening switch.
if name.as_str() == "proxy" || (!php.pass_authorization && name.as_str() == "authorization")
{
continue;
@@ -201,10 +199,7 @@ pub(super) fn fastcgi_params(
})
.or_insert_with(|| value.to_owned());
}
// HTTP/2 and HTTP/3 use :authority and may not carry a literal Host
// header. WordPress and other CGI applications require HTTP_HOST.
params.entry("HTTP_HOST".into()).or_insert_with(|| context.server_name.clone());
// Trusted operator-defined parameters cannot override request-derived/core CGI names.
for (name, value) in &php.custom_params {
params.insert(name.clone(), value.clone());
}
@@ -224,8 +219,6 @@ pub(super) fn fastcgi_params(
let value = php.php_admin_values.iter().map(|(name, item)| format!("{name}={item}")).collect::<Vec<_>>().join("\n");
params.insert("PHP_ADMIN_VALUE".into(), value);
}
// Request headers cannot synthesize PHP_VALUE/PHP_ADMIN_VALUE because only HTTP_*
// names are derived above. PHP_VALUE comes exclusively from validated operator config.
let mut encoded = Vec::with_capacity(4096);
for (name, value) in params {
encode_fcgi_param(&mut encoded, &name, &value)?;
-3
View File
@@ -198,9 +198,6 @@ async fn php_response_inner(
response
}
// tower-http's compression encoder may poll a body again after observing EOF.
// An unfused `stream::unfold` panics on that second poll, aborting the response
// before the encoder can emit its final gzip/br/zstd bytes.
pub(super) fn fastcgi_body_stream(
rx: mpsc::Receiver<io::Result<Bytes>>,
) -> impl futures_util::Stream<Item = io::Result<Bytes>> {
-20
View File
@@ -7,9 +7,6 @@ use std::{
#[cfg(unix)]
use std::{ffi::CString, sync::Arc};
/// Only filesystem state crosses into the blocking pool. Cloning an entire
/// CompiledService here would also copy MIME, rewrite, PHP and security rules
/// for every file or candidate opened during a request.
pub(super) struct FilesystemRoot {
root: PathBuf,
symlink_policy: SymlinkPolicy,
@@ -83,11 +80,6 @@ pub(super) fn secure_open_sync(root: &FilesystemRoot, components: &[String]) ->
use std::os::unix::io::{AsRawFd, FromRawFd};
if components.is_empty() {
// `File::try_clone()` uses dup(2), which shares the directory offset with
// the persistent root descriptor. Passing such a clone to readdir(3)
// would leave the next root listing positioned at EOF. openat(".")
// creates a fresh open file description and therefore a fresh offset for
// every request while retaining the same O_NOFOLLOW confinement.
let dot = cstring_component(".")?;
let fd = unsafe {
libc::openat(
@@ -103,16 +95,10 @@ pub(super) fn secure_open_sync(root: &FilesystemRoot, components: &[String]) ->
let metadata = current.metadata()?;
return Ok(Opened { file: current, metadata });
}
// Borrow the already-owned root descriptor for the first openat. Opening a
// child does not change its directory offset, so a dup/close pair buys no
// isolation. Empty paths still open "." above for independent readdir state.
let mut current: Option<File> = None;
for (index, component) in components.iter().enumerate() {
let name = cstring_component(component)?;
let intermediate = index + 1 != components.len();
// The default remains O_NOFOLLOW on every component. `inside_root` is an
// explicit Linux-only opt-in: the opened descriptor is checked through
// /proc/self/fd after each resolution step before it can be used further.
let mut flags = libc::O_RDONLY | libc::O_CLOEXEC;
if root.symlink_policy == SymlinkPolicy::Deny {
flags |= libc::O_NOFOLLOW;
@@ -120,7 +106,6 @@ pub(super) fn secure_open_sync(root: &FilesystemRoot, components: &[String]) ->
if intermediate {
flags |= libc::O_DIRECTORY;
} else {
// Avoid blocking on special files. Only regular files/directories are served.
flags |= libc::O_NONBLOCK;
}
let parent = current.as_ref().unwrap_or(root.root_handle.as_ref());
@@ -227,15 +212,10 @@ pub(super) fn list_directory_sync(
continue;
}
let Ok(name) = std::str::from_utf8(name) else {
// Routing intentionally accepts only valid UTF-8, so do not emit an
// unusable or ambiguously decoded link for a non-UTF-8 file name.
continue;
};
let mut child = components.to_vec();
child.push(name.to_owned());
// Re-open through the root fd using the configured symlink policy. The
// default omits every symlink; Linux inside_root may include a target only
// after the opened descriptor has been proven to remain below the root.
let Ok(child_opened) = secure_open_sync(root, &child) else {
continue;
};
-2
View File
@@ -46,7 +46,6 @@ pub struct Config {
pub filename: String,
#[serde(default = "default_scan_subdirectories")]
pub scan_subdirectories: bool,
/// Unsupported directives are warnings by default. Strict mode rejects them.
pub strict: bool,
}
@@ -228,7 +227,6 @@ fn supported_response_header(name: &HeaderName) -> bool {
fn parse_duration(value: &str) -> Result<Duration> {
let value = value.trim().trim_matches('"').trim();
// The long form also starts with 'a'; only numeric suffixes use A<seconds>.
if let Some(seconds) = value.strip_prefix('A').or_else(|| value.strip_prefix('a'))
.filter(|seconds| !seconds.is_empty() && seconds.bytes().all(|byte| byte.is_ascii_digit()))
{
+1 -4
View File
@@ -23,8 +23,6 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
continue;
}
if state.in_files_block != 0 {
// RustProxy always blocks .htaccess/.htpasswd directly. More general Files/FilesMatch
// access semantics remain intentionally outside the compatibility subset.
continue;
}
let parts = tokens(line).with_context(|| format!("{}:{line_no}", path.display()))?;
@@ -37,7 +35,6 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
if !state.rewrite_engine { state.pending_conditions.clear(); state.skip_next_rule = false; }
}
"rewritebase" => {
// Per-directory substitutions are already resolved relative to the containing scope.
}
"rewritecond" if state.rewrite_engine => {
condition_count += 1;
@@ -79,7 +76,7 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
for option in &parts[1..] {
if option.eq_ignore_ascii_case("+Indexes") || option.eq_ignore_ascii_case("Indexes") { scope.directory_listing = Some(true); }
else if option.eq_ignore_ascii_case("-Indexes") { scope.directory_listing = Some(false); }
else if option.eq_ignore_ascii_case("-MultiViews") { /* RustProxy has no content negotiation; already effectively off. */ }
else if option.eq_ignore_ascii_case("-MultiViews") { }
else { unsupported(&mut state, config, path, line_no, format!("unsupported Options token {option}"))?; }
}
}
+4 -5
View File
@@ -1,4 +1,3 @@
//! Fixed-cardinality, per-compiled-Web-Service counters. No request-derived labels.
use http::{Method, StatusCode};
use serde_json::{json, Value};
use std::sync::atomic::{AtomicU64, Ordering};
@@ -29,15 +28,15 @@ pub(crate) struct PhpMetrics {
pub(crate) status_4xx: AtomicU64,
pub(crate) status_5xx: AtomicU64,
pub(crate) response_headers_us: AtomicU64,
pub(crate) response_bytes: AtomicU64, // observed uncompressed body frames, not wire bytes
pub(crate) response_bytes: AtomicU64,
pub(crate) in_flight_headers: AtomicU64,
pub(crate) static_requests: AtomicU64,
pub(crate) php_requests: AtomicU64,
pub(crate) other_requests: AtomicU64,
pub(crate) methods: [AtomicU64; 5], // GET POST PUT DELETE other
pub(crate) selected_status: [AtomicU64; 8], // 200 206 304 403 404 500 502 503
pub(crate) methods: [AtomicU64; 5],
pub(crate) selected_status: [AtomicU64; 8],
pub(crate) failures: [AtomicU64; 9],
pub(crate) compression: [AtomicU64; 4], // gzip Brotli zstd deflate (post-route encoder only)
pub(crate) compression: [AtomicU64; 4],
}
pub(crate) struct HeadersInFlight<'a>(&'a AtomicU64);
-6
View File
@@ -1,9 +1,3 @@
//! Static Web Server source integrated with the normal RustProxy vhost/location pipeline.
//! Web services are reusable configuration resources. Vhosts and locations only reference them.
//!
//! Keep this module as the stable public facade. Configuration, filesystem confinement,
//! HTTP responses, routing, FastCGI/PHP-FPM and request dispatch live in dedicated files.
mod config;
mod fastcgi;
mod filesystem;
-6
View File
@@ -1,6 +1,3 @@
// Tokio's file reads dispatch blocking work. Larger, bounded chunks avoid one
// dispatch/copy/body-accounting pass per 4 KiB for ordinary static responses.
// Size small files and ranges to their payload so they do not reserve 64 KiB.
const FILE_STREAM_CAPACITY: usize = 64 * 1024;
pub(super) fn file_stream_capacity(body_length: u64) -> usize {
@@ -162,9 +159,6 @@ async fn file_response_inner(
return response;
}
// Clone the already confined, validated file descriptor. Never reopen
// the user-controlled path for kernel sendfile (TOCTOU/symlink escape).
// When no HTTP/1 TCP bridge accepts it, the regular reader remains used.
#[cfg(target_os = "linux")]
let sendfile_candidate = if service.sendfile == super::SendfileMode::Auto
&& !multipart && single_range.is_none() && content_encoding.is_none()
@@ -1,11 +1,3 @@
//! Exact-length, data-only local file delivery.
//!
//! Hyper may stop polling after Content-Length bytes. ReaderStream alone only
//! learns EOF on the next read, leaving cache fills and body accounting open.
//! These streams come from a bounded local file read (or our multipart writer),
//! so their validated byte count is also a trustworthy end-of-stream boundary.
//! Never use this wrapper for arbitrary upstream HTTP bodies with trailers.
use bytes::Bytes;
use futures_util::Stream;
use http_body::{Body, Frame, SizeHint};
@@ -46,8 +38,6 @@ where
}
this.remaining -= data.len() as u64;
if this.remaining == 0 {
// Drop the file/duplex reader now. No additional EOF read
// or caller poll is needed to release it or finish a fill.
this.stream = None;
}
Poll::Ready(Some(Ok(Frame::data(data))))
@@ -90,7 +90,6 @@ async fn fully_delivered_file_fills_cache_before_consumer_drops_without_polling_
let plan = cache::plan(StatusCode::OK, response.headers(), &settings, Duration::ZERO).unwrap();
let mut body = cache.wrap(response, ticket.clone(), plan, &settings).into_body();
assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap(), "abcdef");
// Reproduce HTTP/1 Content-Length completion: do not ask for another frame.
drop(body);
assert_eq!(cache.view().entries, 1);
assert_eq!(cache.view().rejected_fills, 0);
-8
View File
@@ -21,8 +21,6 @@ use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio_util::io::ReaderStream;
pub(super) fn status_response(status: StatusCode, detail: &'static str) -> Response {
// Keep implementation diagnostics in logs; use the existing embedded
// application-style pages for every Web Server-generated error.
if status.is_server_error() {
tracing::warn!(
status = status.as_u16(),
@@ -30,16 +28,10 @@ pub(super) fn status_response(status: StatusCode, detail: &'static str) -> Respo
"Web Server error"
);
}
// The public serve() facade strips bodies from HEAD responses while
// retaining the same Content-Length as the corresponding GET.
builtin_error_response(status, &Method::GET)
}
pub(super) fn builtin_error_response(status: StatusCode, method: &Method) -> Response {
// Reuse the bundled pages wherever one exists. For statuses such as 405,
// use the shared styled application fallback instead of a plain-text or
// unstyled generic error. Do not mark these as PageServed so normal Vhost
// error-page policy can still replace them.
let (body, length) = match crate::pages::builtin_gateway_error(status) {
Some(html) => (
if *method == Method::HEAD {
-3
View File
@@ -126,9 +126,6 @@ pub(super) async fn select_precompressed(
if !service.precompressed.enabled || components.is_empty() {
return None;
}
// Multipart byte ranges mix MIME boundaries with representation bytes. Keep
// those responses on the identity representation so Content-Encoding never
// describes only the individual file fragments.
if headers
.get("range")
.and_then(|value| value.to_str().ok())
-17
View File
@@ -129,11 +129,6 @@ async fn serve_inner(
{
return builtin_error_response(StatusCode::FORBIDDEN, &method);
}
// An existing PHP script followed by PATH_INFO is a valid virtual PHP
// request, even though the full URL is not a filesystem path. Dispatch it
// before try_files can rewrite /static.php/skins/... to /index.php (as in
// Roundcube 1.7), while still applying the original path's rewrites and
// access controls above.
if let Ok(components) = path_components(&rewritten_path) {
if let Some((script_path, path_info)) = resolve_php_path_info(service, &components).await {
let script_components = path_components(&script_path).unwrap_or_default();
@@ -360,8 +355,6 @@ async fn serve_inner(
)
}
};
// Filtering in place avoids a second Vec allocation for large directories
// while retaining exactly the same visibility and hardening checks.
entries.retain(|entry| {
if htaccess::protected_component(service.htaccess.as_ref(), &entry.name) {
return false;
@@ -378,8 +371,6 @@ async fn serve_inner(
let mut response = Response::new(if method == Method::HEAD {
Body::empty()
} else {
// Move the generated listing into the response. Copying it doubles
// peak HTML allocation for large directory listings under load.
Body::from(listing)
});
response.headers_mut().insert(
@@ -399,10 +390,6 @@ async fn serve_inner(
response
}
/// Serve a decoded, validated routing path from a compiled Web Service.
/// The caller is responsible for normal vhost/location ACL/auth/routing selection;
/// this function performs filesystem handling plus optional Web Service routing,
/// precompressed delivery and bounded FastCGI/PHP-FPM execution.
pub async fn serve(
service: &CompiledService,
method: Method,
@@ -418,8 +405,6 @@ pub async fn serve(
crate::web_server::metrics::HeadersInFlight::new(&service.web_metrics.in_flight_headers);
let request_method = method.clone();
let mut response = serve_inner(service, method, headers, uri, path, body, context).await;
// HEAD carries the same metadata/status as GET, but no response body,
// including the generic filesystem and rewrite error paths.
if request_method == Method::HEAD {
*response.body_mut() = Body::empty();
}
@@ -436,8 +421,6 @@ pub async fn serve(
&request_method,
kind,
);
// Count bytes actually yielded by the Web Server body before downstream compression;
// never infer transferred bytes from Content-Length or count an unpolled response.
let web = service.web_metrics.clone();
let php = if matches!(kind, Some(crate::web_server::metrics::ResponseKind::Php)) {
service.php.as_ref().map(|p| p.metrics.clone())
+4 -21
View File
@@ -218,7 +218,6 @@ async fn internal_filesystem_diagnostics_never_appear_in_public_error_responses(
async fn web_server_validation_and_unmapped_error_statuses_are_styled() {
let tmp = TempDir::new().unwrap();
let service = service(tmp.path(), false);
// Path validation follows the same existing built-in page as other 400s.
let invalid = serve_request(&service, &request(Method::GET, "/"), "/../secret").await;
assert_eq!(invalid.status(), StatusCode::BAD_REQUEST);
assert_eq!(invalid.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
@@ -229,8 +228,6 @@ async fn web_server_validation_and_unmapped_error_statuses_are_styled() {
.as_bytes()
);
// 405 has no dedicated packaged HTML file: reuse the embedded styled
// fallback, while preserving Allow and the actual HTTP status.
let method = serve_request(&service, &request(Method::PUT, "/"), "/").await;
assert_eq!(method.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(method.headers()[ALLOW], "GET, HEAD");
@@ -240,8 +237,6 @@ async fn web_server_validation_and_unmapped_error_statuses_are_styled() {
.unwrap()
.contains("405 - Method Not Allowed"));
// An operator-configured status without a dedicated HTML template still
// uses the common styled fallback, including for HEAD requests.
let fallback_service = Service {
id: "teapot".into(),
name: "Teapot".into(),
@@ -673,7 +668,6 @@ async fn fastcgi_stream_can_be_polled_repeatedly_after_eof() {
Bytes::from_static(b"data")
);
assert!(body.next().await.is_none());
// Without `fuse` this panics inside futures-util::stream::unfold.
assert!(body.next().await.is_none());
}
@@ -1642,8 +1636,6 @@ fn fastcgi_http_host_keeps_explicit_host_and_port() {
.any(|w| w == b"example.test:8443"));
}
// Decode the actual FastCGI PARAMS records received by a mock PHP-FPM peer.
// This tests the Web Service dispatch and parameter generation together.
fn decode_fastcgi_params(mut bytes: &[u8]) -> BTreeMap<String, String> {
fn read_len(bytes: &mut &[u8]) -> usize {
let prefix = bytes[0];
@@ -1718,8 +1710,6 @@ async fn roundcube_static_php_path_info_runs_before_front_controller_try_files()
)
.unwrap();
std::fs::write(tmp.path().join("index.php"), b"<?php // front controller").unwrap();
// This is the Roundcube v1.7 URL layout; /static.php/skins/... is
// virtual PATH_INFO, not a readable directory on disk.
let uri = "/static.php/skins/elastic/images/favicon.ico?s=1783249197";
let (address, received) = fastcgi_fixture_record_params().await;
let mut configured = Service {
@@ -1815,7 +1805,6 @@ async fn web_metrics_count_handler_status_method_and_consumed_body_bytes() {
let service = service(tmp.path(), false);
let get = serve_request(&service, &request(Method::GET, "/asset.txt"), "/asset.txt").await;
assert_eq!(get.status(), StatusCode::OK);
// Bytes are accounted when the body is actually consumed, not when headers arrive.
assert_eq!(service.web_metrics.view()["response_bytes"], 0);
assert_eq!(get.into_body().collect().await.unwrap().to_bytes(), "12345");
let head = serve_request(&service, &request(Method::HEAD, "/asset.txt"), "/asset.txt").await;
@@ -1842,10 +1831,10 @@ async fn web_metrics_count_handler_status_method_and_consumed_body_bytes() {
assert_eq!(view["status_4xx"], 1);
assert_eq!(view["static_requests"], 2);
assert_eq!(view["other_requests"], 1);
assert_eq!(view["methods"][0], 2); // GET
assert_eq!(view["methods"][4], 1); // HEAD -> other
assert_eq!(view["selected_status"][0], 2); // 200
assert_eq!(view["selected_status"][4], 1); // 404
assert_eq!(view["methods"][0], 2);
assert_eq!(view["methods"][4], 1);
assert_eq!(view["selected_status"][0], 2);
assert_eq!(view["selected_status"][4], 1);
assert_eq!(view["response_bytes"], 5 + missing_bytes as u64);
assert_eq!(view["active_headers"], 0);
}
@@ -1933,8 +1922,6 @@ async fn static_streaming_keeps_large_payloads_intact_in_bounded_frames() {
}
assert_eq!(received, expected);
if length >= 64 * 1024 {
// A normal regular file must not regress to one dispatched read and
// body-accounting pass for every 4 KiB of its representation.
assert!(frames < length.div_ceil(4 * 1024));
}
accounted += length as u64;
@@ -2345,8 +2332,6 @@ async fn cancelled_static_and_multipart_bodies_release_files_and_count_only_emit
assert!(first.len() <= 64 * 1024);
accounted += first.len() as u64;
assert_eq!(service.web_metrics.view()["response_bytes"], accounted);
// The multipart writer may fill its bounded duplex buffer in the
// background. Neither it nor a pending file read counts unsent bytes.
tokio::task::yield_now().await;
assert_eq!(service.web_metrics.view()["response_bytes"], accounted);
drop(body);
@@ -2377,8 +2362,6 @@ async fn sendfile_auto_without_tcp_bridge_preserves_full_head_range_and_validato
get.headers()[CONTENT_LENGTH].to_str().unwrap(),
original.len().to_string()
);
// No transport adapter here. Even if a candidate extension was produced,
// its fallback Body must still stream the exact original representation.
let etag = get.headers()[ETAG].clone();
assert_eq!(
get.into_body().collect().await.unwrap().to_bytes().to_vec(),