Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-tiler/src/loadtest.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//! Essai de charge : N clients simulent des cartes — chaque client charge une vue (grille de tuiles autour d'un88//! point, à un zoom donné) sur quelques connexions persistantes, attend, se déplace, change de zoom.89//! Une part des vues vise des zones rurales à z13–z14, hors pré-génération (générations à froid).90//! Client HTTP/1.1 minimal écrit ici (connexions persistantes), pour ne dépendre d'aucun outil externe.9192use crate::tilemath::lonlat_to_tile;93use anyhow::Result;94use std::sync::atomic::{AtomicU64, Ordering};95use std::sync::{Arc, Mutex};96use std::time::{Duration, Instant};97use tokio::io::{AsyncReadExt, AsyncWriteExt};98use tokio::net::TcpStream;99100pub struct LoadOptions {101 pub addr: String,102 /// Adresse locale d'où partent les connexions (pour éprouver le limiteur depuis une adresse non exemptée).103 pub bind: Option<std::net::IpAddr>,104 pub clients: usize,105 pub seconds: u64,106 pub cold_share: f64,107 pub conns_per_client: usize,108 pub think_ms: (u64, u64),109}110111#[derive(Default)]112struct Stats {113 ok200: AtomicU64,114 ok204: AtomicU64,115 s429: AtomicU64,116 s503: AtomicU64,117 other: AtomicU64,118 errors: AtomicU64,119 bytes: AtomicU64,120 views: AtomicU64,121}122123/// Générateur pseudo-aléatoire (xorshift) : pas de dépendance, reproductible par client.124struct Rng(u64);125impl Rng {126 fn next(&mut self) -> u64 {127 self.0 ^= self.0 << 13;128 self.0 ^= self.0 >> 7;129 self.0 ^= self.0 << 17;130 self.0131 }132 fn f(&mut self) -> f64 {133 (self.next() >> 11) as f64 / (1u64 << 53) as f64134 }135 fn range(&mut self, a: f64, b: f64) -> f64 {136 a + (b - a) * self.f()137 }138}139140/// Centres urbains (lon, lat, poids) : là où regardent les utilisateurs des quatre produits.141const CITIES: [(f64, f64, f64); 9] = [142 (-73.5674, 45.5019, 0.40), (-71.2080, 46.8139, 0.15), (-73.7500, 45.5700, 0.10), (-73.5000, 45.5300, 0.08),143 (-75.7000, 45.4500, 0.08), (-71.9000, 45.4000, 0.06), (-72.5500, 46.3500, 0.05), (-71.0700, 48.4300, 0.04),144 (-73.4500, 45.3000, 0.04),145];146147async fn fetch(stream: &mut Option<TcpStream>, opt: &LoadOptions, path: &str, buf: &mut Vec<u8>) -> Result<(u16, usize)> {148 if stream.is_none() {149 let s = match opt.bind {150 Some(ip) => {151 let sock = if ip.is_ipv4() { tokio::net::TcpSocket::new_v4()? } else { tokio::net::TcpSocket::new_v6()? };152 sock.bind(std::net::SocketAddr::new(ip, 0))?;153 sock.connect(opt.addr.parse()?).await?154 }155 None => TcpStream::connect(&opt.addr).await?,156 };157 s.set_nodelay(true)?;158 *stream = Some(s);159 }160 let s = stream.as_mut().unwrap();161 let req = format!("GET {path} HTTP/1.1\r\nHost: loadtest\r\nAccept-Encoding: gzip\r\nConnection: keep-alive\r\n\r\n");162 s.write_all(req.as_bytes()).await?;163 buf.clear();164 let mut tmp = [0u8; 16384];165 let head_end;166 loop {167 let n = s.read(&mut tmp).await?;168 if n == 0 {169 anyhow::bail!("connexion fermée");170 }171 buf.extend_from_slice(&tmp[..n]);172 if let Some(p) = buf.windows(4).position(|w| w == b"\r\n\r\n") {173 head_end = p + 4;174 break;175 }176 if buf.len() > 65536 {177 anyhow::bail!("en-têtes trop longs");178 }179 }180 let head = String::from_utf8_lossy(&buf[..head_end]).to_ascii_lowercase();181 let status: u16 = head.split(' ').nth(1).and_then(|v| v.parse().ok()).unwrap_or(0);182 let len: usize = head183 .lines()184 .find_map(|l| l.strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0)))185 .unwrap_or(0);186 let mut got = buf.len() - head_end;187 while got < len {188 let n = s.read(&mut tmp).await?;189 if n == 0 {190 anyhow::bail!("corps tronqué");191 }192 got += n;193 }194 if head.contains("connection: close") {195 *stream = None;196 }197 Ok((status, len))198}199200pub async fn run(opt: LoadOptions) -> Result<serde_json::Value> {201 let opt = Arc::new(opt);202 let stats = Arc::new(Stats::default());203 let lat_ms: Arc<Mutex<Vec<f32>>> = Arc::new(Mutex::new(Vec::with_capacity(1 << 20)));204 let cold_ms: Arc<Mutex<Vec<f32>>> = Arc::new(Mutex::new(Vec::new()));205 let start = Instant::now();206 let deadline = start + Duration::from_secs(opt.seconds);207 let mut handles = Vec::new();208 for c in 0..opt.clients {209 let (opt, stats, lat_ms, cold_ms) = (opt.clone(), stats.clone(), lat_ms.clone(), cold_ms.clone());210 handles.push(tokio::spawn(async move {211 let mut rng = Rng(0x9E3779B97F4A7C15 ^ ((c as u64 + 1) * 0x2545F4914F6CDD1D));212 // montée en charge étalée sur 5 s213 tokio::time::sleep(Duration::from_millis((rng.f() * 5000.0) as u64)).await;214 let (mut lon, mut lat, mut z, mut cold) = (0.0f64, 0.0f64, 12u8, false);215 let mut conns: Vec<Option<TcpStream>> = (0..opt.conns_per_client).map(|_| None).collect();216 let mut steps_left = 0u32;217 while Instant::now() < deadline {218 if steps_left == 0 {219 // nouvelle session : une ville (vue chaude) ou un point rural à fort zoom (vue froide)220 cold = rng.f() < opt.cold_share;221 if cold {222 lon = rng.range(-79.0, -64.5);223 lat = rng.range(45.2, 50.5);224 z = if rng.f() < 0.5 { 13 } else { 14 };225 } else {226 let mut r = rng.f();227 let mut pick = CITIES[0];228 for cty in CITIES {229 if r < cty.2 {230 pick = cty;231 break;232 }233 r -= cty.2;234 }235 lon = pick.0 + rng.range(-0.08, 0.08);236 lat = pick.1 + rng.range(-0.05, 0.05);237 z = 9 + (rng.f() * 6.0) as u8; // z9–z14238 }239 steps_left = 4 + (rng.f() * 8.0) as u32;240 } else {241 // déplacement d'environ une demi-vue, ou changement de zoom242 let span = 360.0 / (1u64 << z) as f64;243 if rng.f() < 0.25 {244 z = (z as i8 + if rng.f() < 0.5 { 1 } else { -1 }).clamp(if cold { 12 } else { 5 }, 14) as u8;245 } else {246 lon += rng.range(-1.5, 1.5) * span;247 lat += rng.range(-1.0, 1.0) * span * 0.7;248 }249 }250 steps_left -= 1;251 // vue : grille de 4 × 3 tuiles autour du point252 let t = lonlat_to_tile(lon, lat, z);253 let n = 1u32 << z;254 let mut paths: Vec<String> = Vec::with_capacity(12);255 for dx in -1i64..=2 {256 for dy in -1i64..=1 {257 let (x, y) = (t.x as i64 + dx, t.y as i64 + dy);258 if x >= 0 && y >= 0 && (x as u32) < n && (y as u32) < n {259 paths.push(format!("/v1/base/{z}/{x}/{y}.mvt"));260 }261 }262 }263 stats.views.fetch_add(1, Ordering::Relaxed);264 // la rafale part sur les connexions du client, en parallèle265 let chunks: Vec<Vec<String>> = (0..conns.len()).map(|i| paths.iter().skip(i).step_by(conns.len()).cloned().collect()).collect();266 let mut futs = Vec::new();267 for (conn, chunk) in conns.iter_mut().zip(chunks) {268 let (opt, stats) = (opt.clone(), stats.clone());269 futs.push(async move {270 let mut buf = Vec::with_capacity(32768);271 let mut out: Vec<f32> = Vec::with_capacity(chunk.len());272 for p in chunk {273 let t0 = Instant::now();274 match tokio::time::timeout(Duration::from_secs(60), fetch(conn, &opt, &p, &mut buf)).await {275 Ok(Ok((status, len))) => {276 match status {277 200 => stats.ok200.fetch_add(1, Ordering::Relaxed),278 204 => stats.ok204.fetch_add(1, Ordering::Relaxed),279 429 => stats.s429.fetch_add(1, Ordering::Relaxed),280 503 => stats.s503.fetch_add(1, Ordering::Relaxed),281 _ => stats.other.fetch_add(1, Ordering::Relaxed),282 };283 stats.bytes.fetch_add(len as u64, Ordering::Relaxed);284 out.push(t0.elapsed().as_secs_f32() * 1000.0);285 }286 _ => {287 stats.errors.fetch_add(1, Ordering::Relaxed);288 *conn = None;289 }290 }291 }292 out293 });294 }295 let res = futures::future::join_all(futs).await;296 {297 let mut l = if cold { cold_ms.lock().unwrap() } else { lat_ms.lock().unwrap() };298 for r in res {299 l.extend(r);300 }301 }302 let think = opt.think_ms.0 + (rng.f() * (opt.think_ms.1 - opt.think_ms.0) as f64) as u64;303 tokio::time::sleep(Duration::from_millis(think)).await;304 }305 }));306 }307 for h in handles {308 let _ = h.await;309 }310 let secs = start.elapsed().as_secs_f64();311 let pct = |v: &mut Vec<f32>| -> serde_json::Value {312 if v.is_empty() {313 return serde_json::json!(null);314 }315 v.sort_by(|a, b| a.partial_cmp(b).unwrap());316 let p = |q: f64| (v[((v.len() as f64 * q) as usize).min(v.len() - 1)] as f64 * 100.0).round() / 100.0;317 serde_json::json!({"n": v.len(), "p50_ms": p(0.5), "p95_ms": p(0.95), "p99_ms": p(0.99), "max_ms": p(1.0)})318 };319 let g = |a: &AtomicU64| a.load(Ordering::Relaxed);320 let total = g(&stats.ok200) + g(&stats.ok204) + g(&stats.s429) + g(&stats.s503) + g(&stats.other);321 let warm = pct(&mut lat_ms.lock().unwrap());322 let cold = pct(&mut cold_ms.lock().unwrap());323 Ok(serde_json::json!({324 "clients": opt.clients, "seconds": (secs * 10.0).round() / 10.0, "cold_share": opt.cold_share,325 "connections_per_client": opt.conns_per_client, "views": g(&stats.views), "requests": total,326 "requests_per_s": (total as f64 / secs).round(), "megabits_per_s": ((g(&stats.bytes) as f64 * 8.0 / secs / 1e6) * 10.0).round() / 10.0,327 "status_200": g(&stats.ok200), "status_204": g(&stats.ok204), "status_429": g(&stats.s429), "status_503": g(&stats.s503),328 "status_other": g(&stats.other), "transport_errors": g(&stats.errors), "bytes": g(&stats.bytes),329 "latency_city_views": warm, "latency_rural_high_zoom_views": cold,330 }))331}332