SPB Git

Repository Public

main.rs 31.4 KB 734 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : server/km-geo/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-geo — API géographique de KA Maps (Québec).88//!89//!   km-geo serve      lance le service (défaut)90//!   km-geo norm       pipeline : normalise des noms lus sur l'entrée standard91//!92//! Configuration (environnement) :93//!   KM_GEO_DB_URL      postgres://… (rôle en lecture seule)94//!   KM_GEO_LISTEN      adresses d'écoute, séparées par des virgules (défaut 127.0.0.1:8902)95//!   KM_GEO_DEM_ROOT    pyramide .ktr pour /v1/elevation (défaut /var/lib/kamaps/dem)96//!   KM_GATEWAY_IP      pair dont on croit X-Forwarded-For (défaut 10.67.0.1)97//!   KM_GEO_RATE / KM_GEO_BURST   limite par IP, requêtes/s (défauts 20 / 60)98//!   KM_GEO_POOL        connexions PostgreSQL (défaut 16)99//!100//! Vie privée : aucune requête, aucune coordonnée, aucune adresse IP n'est écrite sur disque ni journalisée.101//! Seuls des compteurs agrégés par point d'accès existent en mémoire (/metrics, boucle locale).102103mod err;104mod geom;105mod graph;106mod graph_build;107mod iso;108mod measure;109mod norm;110mod parse;111mod places;112mod routing;113mod search;114115use axum::{116    body::Bytes,117    extract::{ConnectInfo, DefaultBodyLimit, Path, Query, Request, State},118    http::{header, HeaderValue, Method, StatusCode},119    middleware::{self, Next},120    response::{IntoResponse, Response},121    routing::get,122    Json, Router,123};124use err::ApiError;125use km_terrain::httpx::{client_ip, Metrics, RateLimiter};126use km_terrain::store::DemStore;127use serde_json::{json, Value};128use std::collections::HashMap;129use std::io::{BufRead, Write};130use std::net::{IpAddr, SocketAddr};131use std::sync::{Arc, RwLock};132use std::time::{Duration, Instant};133134pub const ATTRIBUTION: &str = "© Gouvernement du Québec (Adresses Québec, découpages administratifs, ISQ) ; Statistique Canada (Registre national d'adresses) ; villes de Montréal, Québec, Gatineau, Sherbrooke, Saguenay, Lévis, Longueuil, Trois-Rivières ; © les contributeurs d'OpenStreetMap";135136const EP: &[&str] = &["search", "reverse", "boundaries", "nearby", "measure", "elevation", "other", "isochrone", "route"];137138pub struct AppState {139    pub pool: deadpool_postgres::Pool,140    pub dem: DemStore,141    pub dem_maxzoom: u8,142    pub gateway: Option<IpAddr>,143    pub limiter: RateLimiter,144    pub metrics: Metrics,145    pub aliases: RwLock<Arc<parse::Aliases>>,146    /// Réseau routier (isochrones, trajets) ; absent si le fichier de graphe n'existe pas.147    pub routing: RwLock<Option<Arc<routing::Routing>>>,148    /// Limite propre aux calculs de réseau, plus coûteux (par IP).149    pub heavy_limiter: RateLimiter,150}151152fn env_or(k: &str, d: &str) -> String {153    std::env::var(k).unwrap_or_else(|_| d.to_string())154}155156fn main() {157    let args: Vec<String> = std::env::args().collect();158    match args.get(1).map(|s| s.as_str()) {159        Some("norm") => cmd_norm(),160        Some("graph-build") => {161            let (Some(pbf), Some(out)) = (args.get(2), args.get(3)) else {162                eprintln!("usage : km-geo graph-build <extrait.osm.pbf> <graphe.bin>");163                std::process::exit(2);164            };165            if let Err(e) = graph_build::build(pbf, out) {166                eprintln!("échec : {e}");167                std::process::exit(1);168            }169        }170        Some("serve") | None => {171            tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap().block_on(serve());172        }173        _ => {174            eprintln!("usage : km-geo [serve] | km-geo norm < noms.txt");175            std::process::exit(2);176        }177    }178}179180/// Pipeline : lit un nom par ligne, écrit `nom \t forme normalisée \t forme sans générique`.181fn cmd_norm() {182    let stdin = std::io::stdin();183    let mut out = std::io::BufWriter::new(std::io::stdout().lock());184    for line in stdin.lock().lines() {185        let line = line.expect("entrée UTF-8");186        let name = line.trim_end_matches(['\r', '\n']);187        if name.is_empty() || name.contains('\t') {188            continue;189        }190        let toks = norm::tokens(name);191        writeln!(out, "{}\t{}\t{}", name, toks.join(" "), norm::core_of(&toks)).unwrap();192    }193}194195fn make_pool() -> deadpool_postgres::Pool {196    let url = std::env::var("KM_GEO_DB_URL").expect("KM_GEO_DB_URL manquant");197    let mut cfg: tokio_postgres::Config = url.parse().expect("KM_GEO_DB_URL invalide");198    // Garde-fous par connexion : délai par requête, lecture seule, plans adaptés aux paramètres,199    // seuil de similarité des trigrammes.200    // Les requêtes nomment les tables sans schéma : `search_path` choisit le jeu de données (`geo` en service,201    // `geo_next,geo` pour l'instance de validation d'une reconstruction).202    let sp = env_or("KM_GEO_SEARCH_PATH", "geo,public");203    assert!(!sp.is_empty() && sp.bytes().all(|b| b.is_ascii_lowercase() || b == b'_' || b == b','), "KM_GEO_SEARCH_PATH invalide");204    cfg.options(&format!(205        "-c search_path={sp} -c statement_timeout=1500 -c lock_timeout=500 -c idle_in_transaction_session_timeout=5000 \206         -c default_transaction_read_only=on -c plan_cache_mode=force_custom_plan \207         -c pg_trgm.word_similarity_threshold=0.65 -c jit=off -c max_parallel_workers_per_gather=0"208    ));209    cfg.application_name("km-geo");210    cfg.connect_timeout(Duration::from_secs(3));211    let mgr = deadpool_postgres::Manager::from_config(212        cfg,213        tokio_postgres::NoTls,214        deadpool_postgres::ManagerConfig { recycling_method: deadpool_postgres::RecyclingMethod::Fast },215    );216    let size: usize = env_or("KM_GEO_POOL", "16").parse().expect("KM_GEO_POOL");217    deadpool_postgres::Pool::builder(mgr)218        .max_size(size)219        .wait_timeout(Some(Duration::from_secs(2)))220        .create_timeout(Some(Duration::from_secs(3)))221        .runtime(deadpool_postgres::Runtime::Tokio1)222        .build()223        .expect("pool PostgreSQL")224}225226async fn load_aliases(pool: &deadpool_postgres::Pool) -> Result<parse::Aliases, err::DbError> {227    let c = pool.get().await?;228    let rows = c229        .query(230            "SELECT norm, kind, mun_id, ST_X(pt), ST_Y(pt) FROM place231             WHERE kind IN ('municipality', 'borough', 'neighbourhood', 'locality') AND norm IS NOT NULL AND length(norm) >= 3",232            &[],233        )234        .await?;235    let mut m: parse::Aliases = HashMap::new();236    for r in rows {237        m.entry(r.get(0)).or_default().push(parse::Alias { kind: r.get(1), mun_id: r.get(2), x: r.get(3), y: r.get(4) });238    }239    Ok(m)240}241242async fn serve() {243    let pool = make_pool();244    let gateway = match env_or("KM_GATEWAY_IP", "10.67.0.1").as_str() {245        "" | "none" => None,246        s => Some(s.parse().expect("KM_GATEWAY_IP")),247    };248    let rate: f64 = env_or("KM_GEO_RATE", "20").parse().expect("KM_GEO_RATE");249    let burst: f64 = env_or("KM_GEO_BURST", "60").parse().expect("KM_GEO_BURST");250    let aliases = match load_aliases(&pool).await {251        Ok(a) => a,252        Err(_) => {253            eprintln!("km-geo: table des lieux indisponible au démarrage (nouvel essai périodique)");254            HashMap::new()255        }256    };257    eprintln!("km-geo: {} noms de lieux en mémoire", aliases.len());258    let app = Arc::new(AppState {259        pool,260        dem: DemStore::new(env_or("KM_GEO_DEM_ROOT", "/var/lib/kamaps/dem"), 256),261        dem_maxzoom: env_or("KM_GEO_DEM_MAXZOOM", "12").parse().expect("KM_GEO_DEM_MAXZOOM"),262        gateway,263        limiter: RateLimiter::new(rate, burst),264        metrics: Metrics::new(EP),265        aliases: RwLock::new(Arc::new(aliases)),266        routing: RwLock::new(None),267        heavy_limiter: RateLimiter::new(268            env_or("KM_GEO_HEAVY_RATE", "3").parse().expect("KM_GEO_HEAVY_RATE"),269            env_or("KM_GEO_HEAVY_BURST", "12").parse().expect("KM_GEO_HEAVY_BURST"),270        ),271    });272273    // Réseau routier : chargé au démarrage, puis rechargé à chaud quand le fichier change (échange de pointeur ;274    // les calculs en cours finissent sur l'ancien graphe).275    {276        let app = app.clone();277        let path = env_or("KM_GEO_GRAPH", "/var/lib/kamaps/graph/quebec.kmgraph");278        let workers: usize = env_or("KM_GEO_ROUTE_WORKERS", "4").parse().expect("KM_GEO_ROUTE_WORKERS");279        let stamp = |p: &str| std::fs::metadata(p).ok().and_then(|m| Some((m.modified().ok()?, m.len())));280        let load = move |path: String| {281            let t0 = Instant::now();282            match graph::Graph::load(&path) {283                Ok(g) if g.n() > 0 => {284                    eprintln!("km-geo: réseau chargé ({} sommets, {} arêtes, {:.1} s)", g.n(), g.m(), t0.elapsed().as_secs_f64());285                    Some(Arc::new(routing::Routing::new(g, workers)))286                }287                _ => {288                    eprintln!("km-geo: réseau routier illisible ou absent ({path})");289                    None290                }291            }292        };293        let mut seen = stamp(&path);294        if seen.is_some() {295            *app.routing.write().unwrap() = load(path.clone());296        } else {297            eprintln!("km-geo: pas de réseau routier ({path}) — /v1/isochrone et /v1/route répondront 503");298        }299        tokio::spawn(async move {300            loop {301                tokio::time::sleep(Duration::from_secs(30)).await;302                let now = stamp(&path);303                if now.is_some() && now != seen {304                    // Le fichier est remplacé par renommage atomique : s'il a changé, il est complet.305                    let p = path.clone();306                    if let Ok(Some(r)) = tokio::task::spawn_blocking(move || load(p)).await {307                        *app.routing.write().unwrap() = Some(r);308                        seen = now;309                    }310                }311            }312        });313    }314315    // Les adresses IP des seaux de limitation ne restent en mémoire que le temps d'un seau (purge chaque minute).316    {317        let app = app.clone();318        tokio::spawn(async move {319            loop {320                tokio::time::sleep(Duration::from_secs(60)).await;321                app.limiter.purge();322                app.heavy_limiter.purge();323            }324        });325    }326327    // Rafraîchit la table des lieux chaque minute (une reconstruction bascule les tables sans redémarrage).328    {329        let app = app.clone();330        tokio::spawn(async move {331            loop {332                tokio::time::sleep(Duration::from_secs(60)).await;333                if let Ok(a) = load_aliases(&app.pool).await {334                    if !a.is_empty() {335                        *app.aliases.write().unwrap() = Arc::new(a);336                    }337                }338            }339        });340    }341342    let router = Router::new()343        .route("/v1/search", get(h_search))344        .route("/v1/reverse", get(h_reverse))345        .route("/v1/boundaries", get(h_boundaries_at))346        .route("/v1/boundaries/search", get(h_boundary_search))347        .route("/v1/boundaries/{level}/{id}", get(h_boundary))348        .route("/v1/nearby", get(h_nearby))349        .route("/v1/nearby/kinds", get(h_kinds))350        .route("/v1/measure", get(h_measure_get).post(h_measure_post))351        .route("/v1/elevation", get(h_elevation))352        .route("/v1/isochrone", get(h_isochrone))353        .route("/v1/route", get(h_route))354        .route("/healthz", get(h_healthz))355        .route("/metrics", get(h_metrics))356        .fallback(|| async { ApiError::not_found("Point d'accès inconnu.") })357        .layer(DefaultBodyLimit::max(512 * 1024))358        .layer(middleware::from_fn_with_state(app.clone(), guard))359        .with_state(app);360361    let mut tasks = Vec::new();362    for addr in env_or("KM_GEO_LISTEN", "127.0.0.1:8902").split(',') {363        let addr: SocketAddr = addr.trim().parse().expect("KM_GEO_LISTEN");364        let listener = tokio::net::TcpListener::bind(addr).await.unwrap_or_else(|e| panic!("écoute {addr}: {e}"));365        eprintln!("km-geo écoute sur {addr}");366        let r = router.clone();367        tasks.push(tokio::spawn(async move {368            axum::serve(listener, r.into_make_service_with_connect_info::<SocketAddr>()).await.unwrap();369        }));370    }371    for t in tasks {372        let _ = t.await;373    }374}375376fn endpoint_index(path: &str) -> usize {377    if path.starts_with("/v1/search") {378        0379    } else if path.starts_with("/v1/reverse") {380        1381    } else if path.starts_with("/v1/boundaries") {382        2383    } else if path.starts_with("/v1/nearby") {384        3385    } else if path.starts_with("/v1/measure") {386        4387    } else if path.starts_with("/v1/elevation") {388        5389    } else if path.starts_with("/v1/isochrone") {390        7391    } else if path.starts_with("/v1/route") {392        8393    } else {394        6395    }396}397398/// Limite de débit par IP, en-têtes communs (CORS, sécurité), compteurs agrégés.399async fn guard(State(app): State<Arc<AppState>>, ConnectInfo(peer): ConnectInfo<SocketAddr>, req: Request, next: Next) -> Response {400    let t0 = Instant::now();401    let path = req.uri().path().to_string();402    let ep = endpoint_index(&path);403    let internal = path == "/healthz" || path == "/metrics";404    let mut resp = if req.uri().path_and_query().map(|p| p.as_str().len()).unwrap_or(0) > 2048 {405        ApiError { status: StatusCode::URI_TOO_LONG, code: "requete_invalide", message: "URL trop longue.".into() }.into_response()406    } else if req.method() == Method::OPTIONS {407        let mut r = StatusCode::NO_CONTENT.into_response();408        r.headers_mut().insert(header::ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("GET, POST, OPTIONS"));409        r.headers_mut().insert(header::ACCESS_CONTROL_ALLOW_HEADERS, HeaderValue::from_static("content-type"));410        r.headers_mut().insert(header::ACCESS_CONTROL_MAX_AGE, HeaderValue::from_static("86400"));411        r412    } else if !matches!(*req.method(), Method::GET | Method::HEAD | Method::POST) {413        ApiError { status: StatusCode::METHOD_NOT_ALLOWED, code: "methode_refusee", message: "Méthode non admise.".into() }.into_response()414    } else {415        // La boucle locale (tests, validation d'une reconstruction, supervision) n'est pas limitée : les clients416        // arrivent tous par la passerelle, sur l'interface WireGuard.417        let limited = if internal || peer.ip().is_loopback() {418            None419        } else {420            let ip = client_ip(peer, req.headers().get("x-forwarded-for").and_then(|v| v.to_str().ok()), app.gateway);421            app.limiter.check(ip).err()422        };423        match limited {424            Some(wait) => ApiError::too_many(wait),425            None => next.run(req).await,426        }427    };428    let h = resp.headers_mut();429    h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));430    h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));431    h.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));432    if !h.contains_key(header::CACHE_CONTROL) {433        // Recherches et positions : données personnelles, jamais en cache partagé.434        h.insert(header::CACHE_CONTROL, HeaderValue::from_static("private, max-age=60"));435    }436    if !internal {437        app.metrics.observe(ep, resp.status().as_u16(), t0.elapsed().as_secs_f64());438    }439    resp440}441442type Params = Query<HashMap<String, String>>;443444fn num(params: &HashMap<String, String>, key: &str) -> Result<Option<f64>, ApiError> {445    match params.get(key) {446        None => Ok(None),447        Some(s) if s.len() <= 24 => s.trim().parse::<f64>().ok().filter(|v| v.is_finite()).map(Some).ok_or_else(|| ApiError::bad(format!("{key} : nombre attendu"))),448        Some(_) => Err(ApiError::bad(format!("{key} : nombre attendu"))),449    }450}451452fn lonlat(params: &HashMap<String, String>) -> Result<(f64, f64), ApiError> {453    match (num(params, "lon")?, num(params, "lat")?) {454        (Some(lon), Some(lat)) if geom::in_area(lon, lat) => Ok((lon, lat)),455        (Some(_), Some(_)) => Err(ApiError::bad("position hors de la zone couverte (Québec : lon −80,5 à −56,5 ; lat 44,5 à 63)")),456        _ => Err(ApiError::bad("lon et lat sont requis")),457    }458}459460fn public_cache(v: Value, seconds: u32) -> Response {461    let mut r = Json(v).into_response();462    r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_str(&format!("public, max-age={seconds}")).unwrap());463    r464}465466async fn h_search(State(app): State<Arc<AppState>>, Query(params): Params) -> Result<Json<Value>, ApiError> {467    let q = params.get("q").map(|s| s.trim()).unwrap_or("");468    if q.is_empty() {469        return Err(ApiError::bad("q est requis"));470    }471    if q.chars().count() > 120 {472        return Err(ApiError::bad("q : 120 caractères au plus"));473    }474    let near = match params.get("near") {475        None => None,476        Some(s) => {477            let (a, b) = s.split_once(',').ok_or_else(|| ApiError::bad("near : lon,lat attendu"))?;478            match (a.trim().parse::<f64>(), b.trim().parse::<f64>()) {479                (Ok(lon), Ok(lat)) if geom::in_area(lon, lat) => Some((lon, lat)),480                (Ok(_), Ok(_)) => return Err(ApiError::bad("near : position hors de la zone couverte")),481                _ => return Err(ApiError::bad("near : lon,lat attendu")),482            }483        }484    };485    let limit = match num(&params, "limit")? {486        None => 8,487        Some(v) if (1.0..=25.0).contains(&v) && v.fract() == 0.0 => v as usize,488        Some(_) => return Err(ApiError::bad("limit : entier de 1 à 25")),489    };490    let types = match params.get("types") {491        Some(s) if s.len() <= 80 => search::Types::parse(s)?,492        Some(_) => return Err(ApiError::bad("types : valeur trop longue")),493        None => search::Types::all(),494    };495    search::run(&app, search::SearchParams { q: q.to_string(), near, limit, types }).await.map(Json)496}497498async fn h_reverse(State(app): State<Arc<AppState>>, Query(params): Params) -> Result<Json<Value>, ApiError> {499    let (lon, lat) = lonlat(&params)?;500    places::reverse(&app, lon, lat).await.map(Json)501}502503async fn h_boundaries_at(State(app): State<Arc<AppState>>, Query(params): Params) -> Result<Json<Value>, ApiError> {504    let (lon, lat) = lonlat(&params)?;505    places::boundaries_at(&app, lon, lat).await.map(Json)506}507508const LEVELS: &[&str] = &["region", "mrc", "municipalite", "arrondissement", "quartier"];509510async fn h_boundary(State(app): State<Arc<AppState>>, Path((level, id)): Path<(String, String)>, Query(params): Params) -> Result<Response, ApiError> {511    if !LEVELS.contains(&level.as_str()) {512        return Err(ApiError::bad("niveau : region, mrc, municipalite, arrondissement ou quartier"));513    }514    if id.is_empty() || id.len() > 24 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {515        return Err(ApiError::bad("identifiant invalide"));516    }517    // tolerance (mètres) ou zoom (0 à 20) : choisit la plus fine des géométries pré-simplifiées qui suffit.518    let tol = match (num(&params, "tolerance")?, num(&params, "zoom")?) {519        (Some(t), _) if (0.0..=100_000.0).contains(&t) => t,520        (Some(_), _) => return Err(ApiError::bad("tolerance : 0 à 100000 (mètres)")),521        (None, Some(z)) if (0.0..=20.0).contains(&z) => 40_075_016.686 * 0.68 / (256.0 * 2f64.powf(z)),522        (None, Some(_)) => return Err(ApiError::bad("zoom : 0 à 20")),523        (None, None) => 10.0,524    };525    let detail = if tol < 10.0 { 0 } else if tol < 100.0 { 1 } else if tol < 1000.0 { 2 } else { 3 };526    let v = places::boundary(&app, &format!("{level}/{id}"), detail).await?;527    let mut r = public_cache(v, 86_400);528    r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/geo+json"));529    Ok(r)530}531532async fn h_boundary_search(State(app): State<Arc<AppState>>, Query(params): Params) -> Result<Response, ApiError> {533    let q = params.get("q").map(|s| s.trim()).unwrap_or("");534    if q.is_empty() || q.chars().count() > 80 {535        return Err(ApiError::bad("q : 1 à 80 caractères"));536    }537    let level = match params.get("level").map(|s| s.as_str()) {538        None => None,539        Some(l) if LEVELS.contains(&l) => Some(l),540        Some(_) => return Err(ApiError::bad("level : region, mrc, municipalite, arrondissement ou quartier")),541    };542    let limit = match num(&params, "limit")? {543        None => 10,544        Some(v) if (1.0..=50.0).contains(&v) && v.fract() == 0.0 => v as i64,545        Some(_) => return Err(ApiError::bad("limit : entier de 1 à 50")),546    };547    Ok(public_cache(places::boundary_search(&app, q, level, limit).await?, 3600))548}549550async fn h_nearby(State(app): State<Arc<AppState>>, Query(params): Params) -> Result<Json<Value>, ApiError> {551    let (lon, lat) = lonlat(&params)?;552    let radius = match num(&params, "radius")? {553        None => 1000.0,554        Some(r) if (50.0..=5000.0).contains(&r) => r,555        Some(_) => return Err(ApiError::bad("radius : 50 à 5000 (mètres)")),556    };557    let kinds: Vec<&str> = match params.get("kinds") {558        Some(s) if s.len() <= 300 => places::expand_kinds(s)?,559        Some(_) => return Err(ApiError::bad("kinds : valeur trop longue")),560        None => places::KINDS.iter().map(|(k, _)| *k).filter(|k| *k != "bus_stop" && *k != "airport").collect(),561    };562    if kinds.is_empty() {563        return Err(ApiError::bad("kinds : au moins une catégorie"));564    }565    let per_kind = match num(&params, "limit")? {566        None => 5,567        Some(v) if (1.0..=20.0).contains(&v) && v.fract() == 0.0 => v as i64,568        Some(_) => return Err(ApiError::bad("limit : entier de 1 à 20 (par catégorie)")),569    };570    places::nearby(&app, lon, lat, radius, &kinds, per_kind).await.map(Json)571}572573async fn h_kinds() -> Response {574    let v: Vec<Value> = places::KINDS.iter().map(|(k, l)| json!({ "kind": k, "label": l })).collect();575    public_cache(json!({ "kinds": v, "groups": ["transit", "education", "commerces", "sante", "loisirs"] }), 86_400)576}577578async fn h_measure_get(Query(params): Params) -> Result<Json<Value>, ApiError> {579    let pts = params.get("points").ok_or_else(|| ApiError::bad("points est requis (lon,lat;lon,lat;…) — ou POST d'un GeoJSON"))?;580    let close = matches!(params.get("close").map(|s| s.as_str()), Some("1") | Some("true"));581    Ok(Json(measure::to_json(&measure::measure_points(pts, close)?)))582}583584async fn h_measure_post(body: Bytes) -> Result<Json<Value>, ApiError> {585    let v: Value = serde_json::from_slice(&body).map_err(|_| ApiError::bad("corps : GeoJSON (JSON) attendu"))?;586    Ok(Json(measure::to_json(&measure::measure_geojson(&v)?)))587}588589async fn h_elevation(State(app): State<Arc<AppState>>, Query(params): Params) -> Result<Json<Value>, ApiError> {590    let (lon, lat) = lonlat(&params)?;591    places::elevation(&app, lon, lat).await.map(Json)592}593594fn pair(s: &str, name: &str) -> Result<(f64, f64), ApiError> {595    if s.len() > 48 {596        return Err(ApiError::bad(format!("{name} : lon,lat attendu")));597    }598    let (a, b) = s.split_once(',').ok_or_else(|| ApiError::bad(format!("{name} : lon,lat attendu")))?;599    match (a.trim().parse::<f64>(), b.trim().parse::<f64>()) {600        (Ok(lon), Ok(lat)) if geom::in_area(lon, lat) => Ok((lon, lat)),601        (Ok(_), Ok(_)) => Err(ApiError::bad(format!("{name} : position hors de la zone couverte"))),602        _ => Err(ApiError::bad(format!("{name} : lon,lat attendu"))),603    }604}605606fn profile_param(params: &HashMap<String, String>) -> Result<graph::Profile, ApiError> {607    match params.get("profile") {608        None => Ok(graph::Profile::Walking),609        Some(s) => graph::Profile::parse(s).ok_or_else(|| ApiError::bad("profile : walking, cycling ou driving")),610    }611}612613/// Garde commune aux calculs de réseau : service chargé, limite par IP propre, file d'attente bornée.614async fn heavy_guard(615    app: &Arc<AppState>,616    peer: SocketAddr,617    headers: &axum::http::HeaderMap,618) -> Result<(Arc<routing::Routing>, tokio::sync::OwnedSemaphorePermit), Response> {619    let Some(r) = app.routing.read().unwrap().clone() else {620        return Err(ApiError::unavailable().into_response());621    };622    if !peer.ip().is_loopback() {623        let ip = client_ip(peer, headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()), app.gateway);624        if let Err(wait) = app.heavy_limiter.check(ip) {625            return Err(ApiError::too_many(wait));626        }627    }628    match tokio::time::timeout(Duration::from_secs(4), r.sem.clone().acquire_owned()).await {629        Ok(Ok(permit)) => Ok((r, permit)),630        _ => Err(ApiError::unavailable().into_response()),631    }632}633634async fn h_isochrone(635    State(app): State<Arc<AppState>>,636    ConnectInfo(peer): ConnectInfo<SocketAddr>,637    headers: axum::http::HeaderMap,638    Query(params): Params,639) -> Response {640    let parsed = (|| -> Result<routing::IsoParams, ApiError> {641        let (lon, lat) = lonlat(&params)?;642        let profile = profile_param(&params)?;643        let minutes = match params.get("minutes") {644            Some(s) if s.len() <= 40 => routing::parse_minutes(s)?,645            Some(_) => return Err(ApiError::bad("minutes : valeur trop longue")),646            None => vec![15.0],647        };648        let max_vertices = match num(&params, "max_vertices")? {649            None => 400,650            Some(v) if (16.0..=2000.0).contains(&v) && v.fract() == 0.0 => v as usize,651            Some(_) => return Err(ApiError::bad("max_vertices : entier de 16 à 2000")),652        };653        Ok(routing::IsoParams { lon, lat, profile, minutes, max_vertices })654    })();655    let p = match parsed {656        Ok(p) => p,657        Err(e) => return e.into_response(),658    };659    let (r, permit) = match heavy_guard(&app, peer, &headers).await {660        Ok(x) => x,661        Err(resp) => return resp,662    };663    let out = tokio::task::spawn_blocking(move || routing::isochrone(&r, &p)).await;664    drop(permit);665    match out {666        Ok(Ok(v)) => {667            let mut resp = Json(&*v).into_response();668            resp.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/geo+json"));669            resp.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("private, max-age=600"));670            resp671        }672        Ok(Err(e)) => e.into_response(),673        Err(_) => ApiError::unavailable().into_response(),674    }675}676677async fn h_route(678    State(app): State<Arc<AppState>>,679    ConnectInfo(peer): ConnectInfo<SocketAddr>,680    headers: axum::http::HeaderMap,681    Query(params): Params,682) -> Response {683    let parsed = (|| -> Result<((f64, f64), (f64, f64), graph::Profile), ApiError> {684        let from = pair(params.get("from").ok_or_else(|| ApiError::bad("from est requis (lon,lat)"))?, "from")?;685        let to = pair(params.get("to").ok_or_else(|| ApiError::bad("to est requis (lon,lat)"))?, "to")?;686        Ok((from, to, profile_param(&params)?))687    })();688    let (from, to, profile) = match parsed {689        Ok(p) => p,690        Err(e) => return e.into_response(),691    };692    let (r, permit) = match heavy_guard(&app, peer, &headers).await {693        Ok(x) => x,694        Err(resp) => return resp,695    };696    let out = tokio::task::spawn_blocking(move || routing::route(&r, from, to, profile)).await;697    drop(permit);698    match out {699        Ok(Ok(v)) => Json(v).into_response(),700        Ok(Err(e)) => e.into_response(),701        Err(_) => ApiError::unavailable().into_response(),702    }703}704705async fn h_healthz(State(app): State<Arc<AppState>>) -> Response {706    let ok = match tokio::time::timeout(Duration::from_secs(2), async {707        let c = app.pool.get().await.ok()?;708        c.query_one("SELECT 1 FROM street LIMIT 1", &[]).await.ok()709    })710    .await711    {712        Ok(Some(_)) => true,713        _ => false,714    };715    let mut r = if ok { (StatusCode::OK, "ok\n").into_response() } else { (StatusCode::SERVICE_UNAVAILABLE, "base indisponible\n").into_response() };716    r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));717    r718}719720async fn h_metrics(State(app): State<Arc<AppState>>, ConnectInfo(peer): ConnectInfo<SocketAddr>) -> Response {721    if !peer.ip().is_loopback() {722        return ApiError::not_found("Point d'accès inconnu.").into_response();723    }724    let st = app.pool.status();725    let mut s = app.metrics.render("km_geo");726    s.push_str(&format!("km_geo_db_pool_size {}\nkm_geo_db_pool_available {}\n", st.size, st.available));727    if let Some(r) = app.routing.read().unwrap().clone() {728        s.push_str(&format!("km_geo_graph_vertices {}\nkm_geo_isochrone_cache_entries {}\n", r.graph.n(), r.cache_len()));729    }730    let mut r = s.into_response();731    r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));732    r733}734
Files main
Menu

Theme