This commit is contained in:
Mateusz Gruszczyński committed 2026-10-04 11:15:58 +02:00
1 parent 87e571c170
commit fa7abc9e53
308 files changed
+49746 -50237

No files matched your search

+245
View File
@@ -0,0 +1,245 @@
use anyhow::{ensure, Result};
use axum::{body::Body, response::Response};
use bytes::Bytes;
use http::{HeaderMap, HeaderValue, Method, StatusCode};
use http_body::{Body as HttpBody, Frame, SizeHint};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, BinaryHeap, HashMap, HashSet},
path::{Component, Path, PathBuf},
pin::Pin,
sync::{
atomic::{AtomicU64, Ordering},
Arc, Mutex,
},
task::{Context, Poll},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::sync::{mpsc, OwnedSemaphorePermit, Semaphore};
use tokio_util::sync::CancellationToken;
const MAX_HEADER_BYTES: usize = 32 * 1024;
const FILL_SLOTS: usize = 8;
const COLD_DELETE_FALLBACKS: usize = 2;
const COLD_CLEANUP_SLOTS: usize = 1;
const BACKGROUND_REVALIDATION_LIMIT: usize = 8;
// Cold writes can contain complete response bodies. Keep the queue deliberately
// small so demotion cannot become a second, hidden RAM cache while disk is slow.
const COLD_QUEUE: usize = 16;
const COLD_FORMAT_VERSION: u8 = 3;
type Key = [u8; 32];
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
enum CleanupPriority {
Automatic(u64, SystemTime, SystemTime),
Manual(SystemTime, SystemTime, u64),
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
struct CleanupCandidate {
priority: CleanupPriority,
sequence: u64,
key: Key,
}
/// `Bytes` releases its allocation when the last reference is dropped, but
/// glibc can keep large freed arenas mapped. After bulk cache demotions/purges,
/// return releasable pages to the OS instead of letting RSS stay artificially
/// high. This is intentionally a no-op on other allocators/platforms.
fn release_allocator_memory() {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
unsafe {
libc::malloc_trim(0);
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CollapseTimeoutFallback {
Origin,
StaleIfAvailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaleErrorClass {
Timeout,
Connection,
Dns,
Tls,
}
impl Default for CollapseTimeoutFallback {
fn default() -> Self {
Self::Origin
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MemoryPreset {
Conservative,
Recommended,
Performance,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ColdPreset {
Recommended,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Settings {
pub enabled: bool,
/// UI sizing profile last explicitly selected by the administrator. The
/// actual numeric limits remain authoritative; this only preserves intent
/// across reloads so the dashboard can show which preset was applied.
pub memory_preset: Option<MemoryPreset>,
/// Hard RAM budget for published HOT entries, charged by backing allocation
/// plus directly owned metadata rather than only logical body length.
pub max_bytes: usize,
/// Maximum logical size of a single cacheable object body.
pub max_object_bytes: usize,
/// Hot tier object count.
pub max_entries: usize,
/// Bounded Varnish-style transient RAM used by in-progress fills and full
/// bodies moving between HOT and COLD. This is independent of `max_bytes`.
pub transient_max_bytes: usize,
/// Byte ceiling for demoted objects waiting in the COLD writer queue.
pub cold_queue_max_bytes: usize,
/// Maximum number of LRU objects removed during one admission attempt.
/// Reaching the limit makes the new object pass through uncached.
pub hot_eviction_max_objects: usize,
/// Automatically release idle HOT objects once the tier is above the target waterline.
pub hot_auto_trim_enabled: bool,
/// Minimum idle age before automatic HOT trimming can evict an object.
pub hot_auto_trim_after_seconds: u64,
/// Target HOT usage percentage reached by each automatic trim pass.
pub hot_auto_trim_target_percent: u8,
/// Persistent cold tier. Disabled by default to avoid implicit disk writes.
pub cold_enabled: bool,
/// Last explicitly selected COLD policy profile, persisted with the cache
/// configuration for the same reason as `memory_preset`.
pub cold_preset: Option<ColdPreset>,
/// Relative to the RustProxy data directory.
pub cold_path: String,
pub cold_max_bytes: u64,
pub cold_max_entries: usize,
/// Interval between asynchronous cold-cache GC checks.
pub cold_gc_interval_seconds: u64,
/// Maximum number of objects removed by one GC pass.
pub cold_gc_max_delete: usize,
/// Hot objects not touched for this long are demoted to disk.
pub cold_after_seconds: u64,
/// Demote objects which have been idle for `cold_after_seconds`.
pub cold_on_idle: bool,
/// Demote objects after this much continuous residency in the hot tier
/// when `cold_on_age` is enabled, even when they are still being read.
pub cold_max_hot_seconds: u64,
/// Apply `cold_max_hot_seconds` as a separate hot-tier age policy.
pub cold_on_age: bool,
/// Preserve objects evicted from the hot LRU in the cold tier.
pub cold_on_lru: bool,
/// Best-effort flush of hot objects to cold storage on graceful shutdown.
pub cold_on_shutdown: bool,
/// Only used for responses explicitly marked public and without origin TTL.
pub default_ttl_seconds: u64,
pub max_ttl_seconds: u64,
pub bypass_query: bool,
pub bypass_prefixes: Vec<String>,
/// For explicitly selected static extensions, ignore request Cookie when
/// deciding cache eligibility and when building the shared cache key.
pub static_ignore_cookies: bool,
pub static_extensions: Vec<String>,
/// Collapse concurrent foreground cache MISS/revalidation fills for the same public cache key.
pub collapse_enabled: bool,
/// Maximum time a follower waits for the current fill before applying the configured fallback.
pub collapse_wait_timeout_ms: u64,
pub collapse_timeout_fallback: CollapseTimeoutFallback,
/// Fine-grained stale-if-error classes. Defaults preserve the 0.21 behavior.
pub stale_if_error_timeout: bool,
pub stale_if_error_connection: bool,
pub stale_if_error_dns: bool,
pub stale_if_error_tls: bool,
pub stale_if_error_statuses: Vec<u16>,
/// Schedule bounded validator refresh before normal freshness expires.
pub proactive_refresh_enabled: bool,
pub proactive_refresh_before_expiry_seconds: u64,
pub proactive_refresh_percent: u8,
pub proactive_refresh_max_inflight: usize,
pub expose_status: bool,
pub expose_hits: bool,
pub expose_cache_status: bool,
pub expose_resident_age: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
enabled: true,
memory_preset: None,
max_bytes: 256 * 1024 * 1024,
max_object_bytes: 16 * 1024 * 1024,
max_entries: 4096,
transient_max_bytes: 64 * 1024 * 1024,
cold_queue_max_bytes: 32 * 1024 * 1024,
hot_eviction_max_objects: 64,
hot_auto_trim_enabled: true,
hot_auto_trim_after_seconds: 300,
hot_auto_trim_target_percent: 80,
cold_enabled: false,
cold_preset: None,
cold_path: "cache/cold".into(),
cold_max_bytes: 4 * 1024 * 1024 * 1024,
cold_max_entries: 50_000,
cold_gc_interval_seconds: 60,
cold_gc_max_delete: 256,
cold_after_seconds: 300,
cold_on_idle: true,
cold_max_hot_seconds: 3600,
cold_on_age: false,
cold_on_lru: true,
cold_on_shutdown: true,
default_ttl_seconds: 0,
max_ttl_seconds: 86_400,
bypass_query: false,
bypass_prefixes: Vec::new(),
// Static assets are normally representation-identical for logged-in and
// anonymous visitors. Keep this enabled by default once the shared cache
// itself is enabled; response-side privacy guards still reject Set-Cookie,
// private/no-store and Vary: Cookie before anything is stored.
static_ignore_cookies: true,
static_extensions: vec![
// styles / scripts
"css", "js", "mjs", "cjs", "wasm", // images
"png", "jpg", "jpeg", "jfif", "jxl", "gif", "webp", "avif", "apng", "svg", "ico",
"cur", "bmp", "tif", "tiff", "heic", "heif", // fonts
"woff", "woff2", "ttf", "otf", "eot", // video
"mp4", "webm", "ogv", "mov", "m4v", // audio
"mp3", "ogg", "oga", "wav", "m4a", "aac", "flac", "opus",
// common static downloads
"pdf", "txt", "zip", "gz", "tgz", "bz2", "xz", "7z", "rar", "tar",
]
.into_iter()
.map(str::to_owned)
.collect(),
collapse_enabled: true,
collapse_wait_timeout_ms: 1500,
collapse_timeout_fallback: CollapseTimeoutFallback::Origin,
stale_if_error_timeout: true,
stale_if_error_connection: true,
stale_if_error_dns: true,
stale_if_error_tls: true,
stale_if_error_statuses: vec![500, 502, 503, 504],
proactive_refresh_enabled: false,
proactive_refresh_before_expiry_seconds: 15,
proactive_refresh_percent: 10,
proactive_refresh_max_inflight: 4,
expose_status: false,
expose_hits: false,
expose_cache_status: false,
expose_resident_age: false,
}
}
}