Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-terrain/src/httpx.rs10// Module : server11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687//! Briques HTTP communes à km-terrain et km-geo : IP réelle du client, limite de débit par IP,88//! compteurs agrégés (aucune requête ni coordonnée n'est conservée).8990use std::collections::HashMap;91use std::net::{IpAddr, SocketAddr};92use std::sync::atomic::{AtomicU64, Ordering};93use std::sync::Mutex;94use std::time::Instant;9596/// IP du client. `X-Forwarded-For` n'est cru que si le pair TCP est la passerelle ; on prend alors97/// la dernière adresse de l'en-tête (celle que la passerelle a elle-même ajoutée).98pub fn client_ip(peer: SocketAddr, xff: Option<&str>, gateway: Option<IpAddr>) -> IpAddr {99 let peer_ip = canonical(peer.ip());100 if Some(peer_ip) == gateway {101 if let Some(ip) = xff102 .and_then(|h| h.rsplit(',').next())103 .and_then(|s| s.trim().parse::<IpAddr>().ok())104 {105 return canonical(ip);106 }107 }108 peer_ip109}110111fn canonical(ip: IpAddr) -> IpAddr {112 match ip {113 IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(IpAddr::V6(v6)),114 v4 => v4,115 }116}117118/// Clé de limitation : l'IPv4 entière, ou le préfixe /64 d'une IPv6.119fn bucket_key(ip: IpAddr) -> u128 {120 match ip {121 IpAddr::V4(v4) => u32::from(v4) as u128,122 IpAddr::V6(v6) => (u128::from(v6) >> 64) | (1u128 << 100),123 }124}125126/// Seau à jetons par IP. Mémoire bornée : au-delà de `max_keys`, les seaux pleins (inactifs) sont purgés.127pub struct RateLimiter {128 rate: f64,129 burst: f64,130 max_keys: usize,131 start: Instant,132 buckets: Mutex<HashMap<u128, (f64, f64)>>,133}134135impl RateLimiter {136 pub fn new(rate_per_sec: f64, burst: f64) -> Self {137 Self { rate: rate_per_sec, burst, max_keys: 100_000, start: Instant::now(), buckets: Mutex::new(HashMap::new()) }138 }139140 /// `Ok(())` si la requête passe, sinon `Err(secondes avant le prochain jeton)`.141 pub fn check(&self, ip: IpAddr) -> Result<(), f64> {142 self.check_at(ip, self.start.elapsed().as_secs_f64())143 }144145 /// Oublie les IP dont le seau est de nouveau plein (inactives) ; à appeler périodiquement.146 pub fn purge(&self) -> usize {147 let now = self.start.elapsed().as_secs_f64();148 let (rate, burst) = (self.rate, self.burst);149 let mut b = self.buckets.lock().unwrap();150 b.retain(|_, (tokens, t)| *tokens + (now - *t) * rate < burst);151 b.len()152 }153154 pub fn check_at(&self, ip: IpAddr, now: f64) -> Result<(), f64> {155 let mut b = self.buckets.lock().unwrap();156 if b.len() >= self.max_keys {157 let (rate, burst) = (self.rate, self.burst);158 b.retain(|_, (tokens, t)| *tokens + (now - *t) * rate < burst);159 if b.len() >= self.max_keys {160 b.clear();161 }162 }163 let e = b.entry(bucket_key(ip)).or_insert((self.burst, now));164 e.0 = (e.0 + (now - e.1) * self.rate).min(self.burst);165 e.1 = now;166 if e.0 >= 1.0 {167 e.0 -= 1.0;168 Ok(())169 } else {170 Err((1.0 - e.0) / self.rate)171 }172 }173}174175const BUCKETS_MS: [f64; 10] = [1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 1000.0, 5000.0];176177/// Compteurs par point d'accès : nombre de réponses par classe de statut et histogramme de durée.178pub struct Metrics {179 names: &'static [&'static str],180 status: Vec<[AtomicU64; 6]>,181 hist: Vec<[AtomicU64; 11]>,182 sum_us: Vec<AtomicU64>,183 started: Instant,184}185186impl Metrics {187 pub fn new(names: &'static [&'static str]) -> Self {188 Self {189 names,190 status: names.iter().map(|_| Default::default()).collect(),191 hist: names.iter().map(|_| Default::default()).collect(),192 sum_us: names.iter().map(|_| AtomicU64::new(0)).collect(),193 started: Instant::now(),194 }195 }196197 pub fn observe(&self, endpoint: usize, status: u16, seconds: f64) {198 let class = ((status / 100) as usize).min(5);199 self.status[endpoint][class].fetch_add(1, Ordering::Relaxed);200 let ms = seconds * 1000.0;201 let i = BUCKETS_MS.iter().position(|b| ms <= *b).unwrap_or(10);202 self.hist[endpoint][i].fetch_add(1, Ordering::Relaxed);203 self.sum_us[endpoint].fetch_add((seconds * 1e6) as u64, Ordering::Relaxed);204 }205206 pub fn render(&self, prefix: &str) -> String {207 let mut s = String::new();208 s.push_str(&format!("{prefix}_uptime_seconds {}\n", self.started.elapsed().as_secs()));209 for (e, name) in self.names.iter().enumerate() {210 for class in 1..6 {211 let v = self.status[e][class].load(Ordering::Relaxed);212 if v > 0 {213 s.push_str(&format!("{prefix}_requests_total{{endpoint=\"{name}\",status=\"{class}xx\"}} {v}\n"));214 }215 }216 let mut cum = 0;217 for (i, b) in BUCKETS_MS.iter().enumerate() {218 cum += self.hist[e][i].load(Ordering::Relaxed);219 s.push_str(&format!("{prefix}_duration_ms_bucket{{endpoint=\"{name}\",le=\"{b}\"}} {cum}\n"));220 }221 cum += self.hist[e][10].load(Ordering::Relaxed);222 s.push_str(&format!("{prefix}_duration_ms_bucket{{endpoint=\"{name}\",le=\"+Inf\"}} {cum}\n"));223 s.push_str(&format!(224 "{prefix}_duration_ms_sum{{endpoint=\"{name}\"}} {:.3}\n",225 self.sum_us[e].load(Ordering::Relaxed) as f64 / 1000.0226 ));227 }228 s229 }230}231232/// FNV-1a 64 bits (ETag de contenu).233pub fn fnv1a(data: &[u8]) -> u64 {234 let mut h: u64 = 0xcbf29ce484222325;235 for b in data {236 h ^= *b as u64;237 h = h.wrapping_mul(0x100000001b3);238 }239 h240}241242#[cfg(test)]243mod tests {244 use super::*;245246 fn sa(s: &str) -> SocketAddr {247 s.parse().unwrap()248 }249250 #[test]251 fn xff_only_from_gateway() {252 let gw: Option<IpAddr> = Some("10.67.0.1".parse().unwrap());253 // pair = passerelle : dernière adresse de l'en-tête254 assert_eq!(client_ip(sa("10.67.0.1:5000"), Some("6.6.6.6, 203.0.113.9"), gw).to_string(), "203.0.113.9");255 // pair quelconque : l'en-tête est ignoré256 assert_eq!(client_ip(sa("198.51.100.7:5000"), Some("203.0.113.9"), gw).to_string(), "198.51.100.7");257 // en-tête absent ou illisible : IP du pair258 assert_eq!(client_ip(sa("10.67.0.1:5000"), None, gw).to_string(), "10.67.0.1");259 assert_eq!(client_ip(sa("10.67.0.1:5000"), Some("n'importe quoi"), gw).to_string(), "10.67.0.1");260 // aucune passerelle configurée261 assert_eq!(client_ip(sa("10.67.0.1:5000"), Some("203.0.113.9"), None).to_string(), "10.67.0.1");262 // IPv4 mappée263 assert_eq!(client_ip(sa("[::ffff:10.67.0.1]:5000"), Some("203.0.113.9"), gw).to_string(), "203.0.113.9");264 }265266 #[test]267 fn token_bucket() {268 let rl = RateLimiter::new(2.0, 3.0);269 let a: IpAddr = "203.0.113.1".parse().unwrap();270 let b: IpAddr = "203.0.113.2".parse().unwrap();271 for _ in 0..3 {272 assert!(rl.check_at(a, 0.0).is_ok());273 }274 let wait = rl.check_at(a, 0.0).unwrap_err();275 assert!((wait - 0.5).abs() < 1e-9);276 assert!(rl.check_at(b, 0.0).is_ok(), "les IP sont indépendantes");277 assert!(rl.check_at(a, 0.5).is_ok(), "un jeton revient après 0,5 s");278 assert!(rl.check_at(a, 0.5).is_err());279 // même /64 en IPv6 = même seau280 let v6a: IpAddr = "2001:db8::1".parse().unwrap();281 let v6b: IpAddr = "2001:db8::ffff".parse().unwrap();282 for _ in 0..3 {283 assert!(rl.check_at(v6a, 0.0).is_ok());284 }285 assert!(rl.check_at(v6b, 0.0).is_err());286 // Purge : rien n'est gardé une fois les seaux de nouveau pleins287 let rl = RateLimiter::new(1000.0, 2.0);288 assert!(rl.check(a).is_ok());289 std::thread::sleep(std::time::Duration::from_millis(20));290 assert_eq!(rl.purge(), 0);291 }292293 #[test]294 fn metrics_render() {295 let m = Metrics::new(&["a", "b"]);296 m.observe(0, 200, 0.004);297 m.observe(0, 429, 0.0001);298 let out = m.render("t");299 assert!(out.contains("t_requests_total{endpoint=\"a\",status=\"2xx\"} 1"));300 assert!(out.contains("t_requests_total{endpoint=\"a\",status=\"4xx\"} 1"));301 assert!(out.contains("t_duration_ms_bucket{endpoint=\"a\",le=\"5\"} 2"));302 }303}304