use crate::{ config::{self, Snapshot, Update, ValidationPolicy}, db::Store, logging::Logs, metrics::Metrics, }; use arc_swap::ArcSwap; use axum::{ http::StatusCode, response::{IntoResponse, Response}, Json, }; use serde_json::json; use sha2::{Digest, Sha256}; use std::{ collections::HashMap, sync::Arc, time::{Duration, Instant}, }; use tokio::sync::{Mutex, Semaphore}; type DockerApplied = (std::sync::Weak, [u8; 32]); pub struct App { pub basic_workers: Arc, pub basic_limits: crate::basic_auth::Limits, pub active_prometheus: crate::prometheus::Settings, pub prometheus_token_hash: arc_swap::ArcSwapOption, pub active_administration: crate::settings::Administration, pub active_administration_tls_policy: crate::tls::ProtocolPolicy, pub active_administration_certificate_files: Option<(String, String)>, pub max_inflight: usize, pub config: ArcSwap, pub store: Store, pub policy: ValidationPolicy, pub active_listeners: Vec, pub active_streams: Vec, pub stream_metrics: HashMap>, pub startup_listeners: (std::net::SocketAddr, Option), pub startup_locks: crate::settings::StartupLocks, pub auth: Arc, pub viewer_slots: Arc, pub certificate_slots: Arc, pub cache_invalidation_slots: Arc, pub metrics: Arc, pub transform_metrics: Arc, pub traffic: Arc, pub cache: Arc, pub geoip: ArcSwap, pub rate_limiter: Arc, pub acme: Arc, pub diagnostics: Arc, pub docker: Arc, pub logs: Arc, pub software_update: Arc, pub shutdown: tokio_util::sync::CancellationToken, pub tunnels: tokio_util::task::TaskTracker, pub tunnel_registry: Arc, pub websocket_idle_timeout: Duration, pub inflight: Arc, pub started: Instant, pub header_timeout: Duration, pub body_idle_timeout: Duration, pub config_file: Mutex>, update_lock: Mutex<()>, docker_applied: std::sync::Mutex>, update_slots: Arc, } #[derive(Debug)] pub struct ApiError(pub StatusCode, pub String); impl IntoResponse for ApiError { fn into_response(self) -> Response { let mut response = (self.0, Json(json!({"error": self.1}))).into_response(); if self.0 == StatusCode::TOO_MANY_REQUESTS { response .headers_mut() .insert("retry-after", http::HeaderValue::from_static("60")); } response } } #[derive(Debug)] enum CacheInvalidation { None, All(u64), Scopes(Vec), } fn cache_revision(config: &config::Config) -> u64 { let mut cache = config.cache.clone(); cache.memory_preset = None; cache.cold_preset = None; cache.bypass_query = false; cache.bypass_prefixes.clear(); cache.http_invalidation_allowed_cidrs.clear(); cache.expose_status = false; cache.expose_hits = false; cache.expose_cache_status = false; cache.expose_resident_age = false; cache.expose_only_hits = false; cache.via_header = None; let mut transform = config.transform.clone(); transform.preset = None; transform.memory_budget_bytes = 0; transform.max_inflight = 0; let mut web_services = config.web_services.clone(); for service in &mut web_services { service.sendfile = crate::web_server::SendfileMode::Off; } cache_digest(&( &cache, &transform, &config.headers, &config.forwarding, &web_services, &config.php_fpm_profiles, )) } fn cache_digest(value: &T) -> u64 { let encoded = serde_json::to_vec(value).expect("serializable cache compatibility view"); let digest = Sha256::digest(encoded); u64::from_be_bytes(digest[..8].try_into().expect("sha256 prefix")) } fn vhost_cache_revision(vhost: &crate::vhost::Vhost) -> u64 { let mut view = vhost.clone(); view.websockets = false; view.websocket_legacy_support = false; view.websocket_rfc8441 = false; view.websocket_rfc9220 = false; view.http2_enabled = true; view.http3_enabled = true; view.enabled = true; view.force_ssl = false; view.www_redirect = false; view.www_redirect_target = None; view.timing_headers = false; view.backend_header = false; view.backend_timing_header = false; view.certificate_id = None; view.tls_policy = None; view.server_header = None; view.diagnostic_headers = None; view.rate_limit = Default::default(); view.method_policy = Default::default(); view.content_type_policy = Default::default(); view.basic_auth = Default::default(); view.tinyauth = Default::default(); view.authelia = Default::default(); view.authentik = Default::default(); view.acl = None; view.acl_profile_id = None; view.user_agent_blocking = Default::default(); view.proxy_timeouts = Default::default(); view.frontend.listener_ids.clear(); view.cache.expose_only_hits = None; view.load_balancing = Default::default(); for member in &mut view.backends { member.weight = 1; member.backup = false; member.drain = false; member.health_check_enabled = true; member.health_check = None; member.max_concurrent_requests = 0; member.queue_timeout_ms = 0; } cache_digest(&view) } fn vhost_cache_revisions(config: &config::Config) -> HashMap { config .vhosts .iter() .map(|vhost| (vhost.id.clone(), vhost_cache_revision(vhost))) .collect() } fn cache_invalidation(previous: &config::Config, next: &config::Config) -> CacheInvalidation { let before = cache_revision(previous); let after = cache_revision(next); if before != after { return CacheInvalidation::All(after); } let old = vhost_cache_revisions(previous); let new = vhost_cache_revisions(next); let mut changed: Vec<_> = old .iter() .filter(|(id, revision)| new.get(*id) != Some(*revision)) .map(|(id, _)| id.clone()) .collect(); changed.extend(new.keys().filter(|id| !old.contains_key(*id)).cloned()); changed.sort(); changed.dedup(); if changed.is_empty() { CacheInvalidation::None } else { CacheInvalidation::Scopes(changed) } }