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; const COLD_QUEUE: usize = 16; const COLD_FORMAT_VERSION: u8 = 3; type Key = [u8; 32]; #[derive(Default, Clone, Copy)] struct DigestKeyHasher(u64); impl std::hash::Hasher for DigestKeyHasher { fn finish(&self) -> u64 { self.0 } fn write(&mut self, bytes: &[u8]) { if bytes.len() == 32 { let mut word = [0u8; 8]; word.copy_from_slice(&bytes[..8]); self.0 ^= u64::from_le_bytes(word); return; } for chunk in bytes.chunks(8) { let mut word = [0u8; 8]; word[..chunk.len()].copy_from_slice(chunk); self.0 = (self.0.rotate_left(5) ^ u64::from_le_bytes(word)) .wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); } } fn write_usize(&mut self, _length: usize) { } } type KeyMap = HashMap>; #[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, } const ALLOCATOR_RELEASE_INTERVAL_MS: u64 = 250; static ALLOCATOR_RELEASE_LAST_MS: AtomicU64 = AtomicU64::new(0); static ALLOCATOR_RELEASE_PENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); fn allocator_clock_ms() -> u64 { static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); (EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64) .saturating_add(ALLOCATOR_RELEASE_INTERVAL_MS + 1) } fn release_allocator_memory() { let now = allocator_clock_ms(); let last = ALLOCATOR_RELEASE_LAST_MS.load(Ordering::Relaxed); if now.saturating_sub(last) < ALLOCATOR_RELEASE_INTERVAL_MS || ALLOCATOR_RELEASE_LAST_MS .compare_exchange(last, now, Ordering::AcqRel, Ordering::Relaxed) .is_err() { ALLOCATOR_RELEASE_PENDING.store(true, Ordering::Relaxed); return; } ALLOCATOR_RELEASE_PENDING.store(false, Ordering::Relaxed); cache_trim_allocator(); } fn flush_pending_allocator_release() { if ALLOCATOR_RELEASE_PENDING.load(Ordering::Relaxed) { release_allocator_memory(); } } fn cache_trim_allocator() { #[cfg(all(target_os = "linux", target_env = "gnu"))] unsafe { libc::malloc_trim(0); } } #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum CollapseTimeoutFallback { #[default] Origin, StaleIfAvailable, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum StaleErrorClass { Timeout, Connection, Dns, Tls, } #[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, pub varnish_compatible: bool, pub varnish_grace_seconds: u64, pub memory_preset: Option, pub max_bytes: usize, pub max_object_bytes: usize, pub max_entries: usize, pub transient_max_bytes: usize, pub cold_queue_max_bytes: usize, pub hot_eviction_max_objects: usize, pub hot_auto_trim_enabled: bool, pub hot_auto_trim_after_seconds: u64, pub hot_auto_trim_target_percent: u8, pub cold_enabled: bool, pub cold_preset: Option, pub cold_path: String, pub cold_max_bytes: u64, pub cold_max_entries: usize, pub cold_gc_interval_seconds: u64, pub cold_gc_max_delete: usize, pub cold_after_seconds: u64, pub cold_on_idle: bool, pub cold_max_hot_seconds: u64, pub cold_on_age: bool, pub cold_on_lru: bool, pub cold_on_shutdown: bool, pub default_ttl_seconds: u64, pub max_ttl_seconds: u64, pub bypass_query: bool, pub bypass_prefixes: Vec, pub http_invalidation_allowed_cidrs: Vec, pub static_ignore_cookies: bool, pub static_extensions: Vec, pub collapse_enabled: bool, pub collapse_wait_timeout_ms: u64, pub collapse_timeout_fallback: CollapseTimeoutFallback, 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, 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, pub expose_only_hits: bool, pub via_header: Option, #[serde(skip_serializing_if = "Vec::is_empty")] pub rules: Vec, #[serde(skip)] pub compiled_rules: Option>, } impl Default for Settings { fn default() -> Self { Self { enabled: true, varnish_compatible: true, varnish_grace_seconds: 60, 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(), http_invalidation_allowed_cidrs: Vec::new(), static_ignore_cookies: true, static_extensions: vec![ "css", "js", "mjs", "cjs", "wasm", "png", "jpg", "jpeg", "jfif", "jxl", "gif", "webp", "avif", "apng", "svg", "ico", "cur", "bmp", "tif", "tiff", "heic", "heif", "woff", "woff2", "ttf", "otf", "eot", "mp4", "webm", "ogv", "mov", "m4v", "mp3", "ogg", "oga", "wav", "m4a", "aac", "flac", "opus", "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, expose_only_hits: false, via_header: Some("RustProxy".into()), rules: Vec::new(), compiled_rules: None, } } }