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/main.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//! km-terrain — sert la pyramide de relief pré-générée.88//!89//! `GET /v1/dem/{z}/{x}/{y}.ktr` · `GET /v1/dem.json` · `GET /healthz` · `GET /metrics` (boucle locale seulement)90//!91//! Configuration (environnement) :92//! KM_TERRAIN_LISTEN adresses d'écoute séparées par des virgules (défaut 127.0.0.1:8903)93//! KM_TERRAIN_ROOT racine de la pyramide (défaut /var/lib/kamaps/dem)94//! KM_TERRAIN_MAXZOOM zoom maximal servi (défaut 12)95//! KM_GATEWAY_IP pair dont on croit X-Forwarded-For (défaut 10.67.0.1)96//! KM_TERRAIN_RATE / KM_TERRAIN_BURST limite par IP en requêtes/s (défauts 150 / 600)9798use axum::{99 extract::{ConnectInfo, Path, State},100 http::{header, HeaderMap, HeaderValue, Method, StatusCode},101 response::{IntoResponse, Response},102 routing::get,103 Router,104};105use km_terrain::httpx::{client_ip, fnv1a, Metrics, RateLimiter};106use km_terrain::store::tile_path;107use std::net::{IpAddr, SocketAddr};108use std::path::PathBuf;109use std::sync::Arc;110use std::time::Instant;111112const CACHE_OK: &str = "public, max-age=2592000, stale-while-revalidate=604800";113const CACHE_EMPTY: &str = "public, max-age=86400";114const EP: &[&str] = &["dem", "meta", "other"];115116struct App {117 root: PathBuf,118 max_zoom: u8,119 gateway: Option<IpAddr>,120 limiter: RateLimiter,121 metrics: Metrics,122 meta: String,123}124125fn env_or(k: &str, d: &str) -> String {126 std::env::var(k).unwrap_or_else(|_| d.to_string())127}128129#[tokio::main]130async fn main() {131 let root = PathBuf::from(env_or("KM_TERRAIN_ROOT", "/var/lib/kamaps/dem"));132 let max_zoom: u8 = env_or("KM_TERRAIN_MAXZOOM", "12").parse().expect("KM_TERRAIN_MAXZOOM");133 let gateway = match env_or("KM_GATEWAY_IP", "10.67.0.1").as_str() {134 "" | "none" => None,135 s => Some(s.parse().expect("KM_GATEWAY_IP")),136 };137 let rate: f64 = env_or("KM_TERRAIN_RATE", "150").parse().expect("KM_TERRAIN_RATE");138 let burst: f64 = env_or("KM_TERRAIN_BURST", "600").parse().expect("KM_TERRAIN_BURST");139 let meta = std::fs::read_to_string(root.join("meta/dem.json")).unwrap_or_else(|_| "{}".into());140 let app = Arc::new(App { root, max_zoom, gateway, limiter: RateLimiter::new(rate, burst), metrics: Metrics::new(EP), meta });141142 // Les adresses IP des seaux de limitation ne restent en mémoire que le temps d'un seau (purge chaque minute).143 {144 let app = app.clone();145 tokio::spawn(async move {146 loop {147 tokio::time::sleep(std::time::Duration::from_secs(60)).await;148 app.limiter.purge();149 }150 });151 }152153 let router = Router::new()154 .route("/v1/dem/{z}/{x}/{file}", get(tile))155 .route("/v1/dem.json", get(meta_json))156 .route("/healthz", get(healthz))157 .route("/metrics", get(metrics))158 .fallback(|| async { (StatusCode::NOT_FOUND, "introuvable\n") })159 .with_state(app);160161 let mut tasks = Vec::new();162 for addr in env_or("KM_TERRAIN_LISTEN", "127.0.0.1:8903").split(',') {163 let addr: SocketAddr = addr.trim().parse().expect("KM_TERRAIN_LISTEN");164 let listener = tokio::net::TcpListener::bind(addr).await.unwrap_or_else(|e| panic!("écoute {addr}: {e}"));165 eprintln!("km-terrain écoute sur {addr}");166 let r = router.clone();167 tasks.push(tokio::spawn(async move {168 axum::serve(listener, r.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();169 }));170 }171 for t in tasks {172 let _ = t.await;173 }174}175176fn base_headers(resp: &mut Response) {177 let h = resp.headers_mut();178 h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));179 h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));180}181182fn plain(status: StatusCode, msg: &'static str) -> Response {183 let mut r = (status, msg).into_response();184 base_headers(&mut r);185 r186}187188async fn tile(189 State(app): State<Arc<App>>,190 ConnectInfo(peer): ConnectInfo<SocketAddr>,191 method: Method,192 headers: HeaderMap,193 Path((z, x, file)): Path<(String, String, String)>,194) -> Response {195 let t0 = Instant::now();196 let resp = tile_inner(&app, peer, &method, &headers, &z, &x, &file).await;197 app.metrics.observe(0, resp.status().as_u16(), t0.elapsed().as_secs_f64());198 resp199}200201/// Entier décimal strict (pas de signe, pas de zéros de tête, longueur bornée).202fn parse_uint(s: &str) -> Option<u32> {203 if s.is_empty() || s.len() > 7 || !s.bytes().all(|b| b.is_ascii_digit()) || (s.len() > 1 && s.starts_with('0')) {204 return None;205 }206 s.parse().ok()207}208209async fn tile_inner(app: &App, peer: SocketAddr, _method: &Method, headers: &HeaderMap, z: &str, x: &str, file: &str) -> Response {210 let ip = client_ip(peer, headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()), app.gateway);211 if let Err(wait) = app.limiter.check(ip) {212 let mut r = plain(StatusCode::TOO_MANY_REQUESTS, "trop de requêtes\n");213 r.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from_str(&format!("{}", wait.ceil().max(1.0) as u64)).unwrap());214 return r;215 }216 let Some(y) = file.strip_suffix(".ktr") else {217 return plain(StatusCode::NOT_FOUND, "extension attendue : .ktr\n");218 };219 let (Some(z), Some(x), Some(y)) = (parse_uint(z), parse_uint(x), parse_uint(y)) else {220 return plain(StatusCode::BAD_REQUEST, "z, x, y : entiers attendus\n");221 };222 if z > app.max_zoom as u32 {223 return plain(StatusCode::NOT_FOUND, "zoom non servi\n");224 }225 let n = 1u32 << z;226 if x >= n || y >= n {227 return plain(StatusCode::BAD_REQUEST, "x ou y hors de la pyramide\n");228 }229 // Le chemin n'est construit qu'à partir d'entiers validés : aucune traversée possible.230 let path = tile_path(&app.root, z as u8, x, y);231 match tokio::fs::read(&path).await {232 Ok(body) => {233 let etag = format!("\"{:016x}\"", fnv1a(&body));234 let not_modified = headers235 .get(header::IF_NONE_MATCH)236 .and_then(|v| v.to_str().ok())237 .map(|v| v.split(',').any(|t| t.trim().trim_start_matches("W/") == etag || t.trim() == "*"))238 .unwrap_or(false);239 let mut r = if not_modified {240 StatusCode::NOT_MODIFIED.into_response()241 } else {242 let mut r = body.into_response();243 r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/vnd.kamaps.ktr"));244 r245 };246 r.headers_mut().insert(header::ETAG, HeaderValue::from_str(&etag).unwrap());247 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE_OK));248 base_headers(&mut r);249 r250 }251 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {252 // Hors couverture (ou tuile uniformément au niveau de la mer non écrite) : 204.253 let mut r = StatusCode::NO_CONTENT.into_response();254 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE_EMPTY));255 base_headers(&mut r);256 r257 }258 Err(_) => plain(StatusCode::INTERNAL_SERVER_ERROR, "erreur de lecture\n"),259 }260}261262async fn meta_json(State(app): State<Arc<App>>) -> Response {263 let mut r = app.meta.clone().into_response();264 r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json; charset=utf-8"));265 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=3600"));266 base_headers(&mut r);267 app.metrics.observe(1, 200, 0.0);268 r269}270271async fn healthz(State(app): State<Arc<App>>) -> Response {272 // La tuile z0 doit exister et se décoder.273 let ok = tokio::fs::read(tile_path(&app.root, 0, 0, 0)).await.ok().map(|b| km_terrain::ktr::decode(&b).is_ok()).unwrap_or(false);274 if ok {275 plain(StatusCode::OK, "ok\n")276 } else {277 plain(StatusCode::SERVICE_UNAVAILABLE, "pyramide absente ou illisible\n")278 }279}280281async fn metrics(State(app): State<Arc<App>>, ConnectInfo(peer): ConnectInfo<SocketAddr>) -> Response {282 if !peer.ip().is_loopback() {283 return plain(StatusCode::NOT_FOUND, "introuvable\n");284 }285 app.metrics.render("km_terrain").into_response()286}287