SPB Git

Repository Public

engine.rs 16.2 KB 397 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : KA Maps Engine9// File             : server/km-tiler/src/engine.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//! Cœur du moteur : connexion PostGIS, génération d'une tuile (requêtes par couche → MVT → gzip),88//! cache disque versionné, suivi de la version de données active.8990use crate::layers::{self, Options};91use crate::mvt::{self, LayerBuilder, Value};92use crate::tilemath::{Tile, EXTENT};93use anyhow::{anyhow, Context, Result};94use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod};95use flate2::write::GzEncoder;96use flate2::Compression;97use std::io::Write;98use std::path::{Path, PathBuf};99use std::str::FromStr;100use std::sync::atomic::{AtomicU64, Ordering};101use std::sync::{Arc, RwLock};102use std::time::Instant;103use tokio_postgres::types::Type;104use tokio_postgres::NoTls;105106pub struct Generated {107    /// Tuile gzip ; vide si aucune entité.108    pub gz: Vec<u8>,109    pub raw_len: usize,110    pub features: u32,111    /// Contient des routes carrossables ou des bâtiments (critère de descente de la pré-génération).112    pub populated: bool,113    pub millis: f64,114    /// (couche, entités, octets non compressés)115    pub layer_counts: Vec<(&'static str, u32, u32)>,116}117118pub struct Engine {119    pub pool: Pool,120    pub cache_root: PathBuf,121    pub opts: Options,122    version: RwLock<Arc<str>>,123    pub generated_total: AtomicU64,124    /// Requêtes de fusion retombées sur leur variante sans fusion.125    pub fallback_total: AtomicU64,126}127128pub fn make_pool(db_url: &str, schema: &str, size: usize) -> Result<Pool> {129    if !schema.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {130        return Err(anyhow!("nom de schéma invalide"));131    }132    let mut cfg = tokio_postgres::Config::from_str(db_url).context("KM_DB_URL invalide")?;133    cfg.options(&format!("-c search_path={schema},ext,public -c statement_timeout=120000 -c jit=off"));134    cfg.application_name("km-tiler");135    let mgr = Manager::from_config(cfg, NoTls, ManagerConfig { recycling_method: RecyclingMethod::Fast });136    Ok(Pool::builder(mgr).max_size(size).build()?)137}138139impl Engine {140    pub async fn new(db_url: &str, schema: &str, pool_size: usize, cache_root: PathBuf, version: Option<String>, base_parcel: bool) -> Result<Engine> {141        let pool = make_pool(db_url, schema, pool_size)?;142        let client = pool.get().await.context("connexion PostgreSQL")?;143        let has_parcel: bool = client144            .query_one("SELECT to_regclass('parcel') IS NOT NULL", &[])145            .await?146            .get(0);147        let version = match version {148            Some(v) => v,149            None => fetch_active_version(&client).await.unwrap_or_else(|| "dev".to_string()),150        };151        check_version_name(&version)?;152        Ok(Engine {153            pool,154            cache_root,155            opts: Options { has_parcel, base_parcel },156            version: RwLock::new(Arc::from(version.as_str())),157            generated_total: AtomicU64::new(0),158            fallback_total: AtomicU64::new(0),159        })160    }161162    pub fn version(&self) -> Arc<str> {163        self.version.read().unwrap().clone()164    }165166    /// Relit la version active dans `meta.version`. Renvoie `true` si elle a changé.167    pub async fn refresh_version(&self) -> Result<bool> {168        let client = self.pool.get().await?;169        if let Some(v) = fetch_active_version(&client).await {170            if check_version_name(&v).is_ok() && *v != *self.version() {171                *self.version.write().unwrap() = Arc::from(v.as_str());172                return Ok(true);173            }174        }175        Ok(false)176    }177178    pub fn cache_path(&self, version: &str, t: Tile) -> PathBuf {179        cache_path(&self.cache_root, version, t)180    }181182    /// Cache du jeu `parcel` : {racine}/{version}/parcel/{z}/{x}/{y}.mvt183    pub fn parcel_cache_path(&self, version: &str, t: Tile) -> PathBuf {184        self.cache_root.join(version).join("parcel").join(t.z.to_string()).join(t.x.to_string()).join(format!("{}.mvt", t.y))185    }186187    pub async fn put_file(path: &Path, gz: &[u8]) -> Result<()> {188        let dir = path.parent().unwrap();189        tokio::fs::create_dir_all(dir).await?;190        let tmp = dir.join(format!(".{}.{}.tmp", path.file_name().unwrap().to_string_lossy(), std::process::id()));191        tokio::fs::write(&tmp, gz).await?;192        tokio::fs::rename(&tmp, path).await?;193        Ok(())194    }195196    /// Lit une tuile du cache. `Some(vec![])` = tuile vide connue.197    pub async fn cache_get(&self, version: &str, t: Tile) -> Option<Vec<u8>> {198        tokio::fs::read(self.cache_path(version, t)).await.ok()199    }200201    pub async fn cache_put(&self, version: &str, t: Tile, gz: &[u8]) -> Result<()> {202        let path = self.cache_path(version, t);203        let dir = path.parent().unwrap();204        tokio::fs::create_dir_all(dir).await?;205        let tmp = dir.join(format!(".{}.{}.tmp", t.y, std::process::id()));206        tokio::fs::write(&tmp, gz).await?;207        tokio::fs::rename(&tmp, &path).await?;208        Ok(())209    }210211    /// Génère la tuile du jeu `base` depuis PostGIS (sans toucher au cache).212    pub async fn generate(&self, t: Tile) -> Result<Generated> {213        self.generate_set(t, false).await214    }215216    /// Génère une tuile : jeu `base`, ou jeu `parcel` (couche parcel seule) si `parcel_set`.217    pub async fn generate_set(&self, t: Tile, parcel_set: bool) -> Result<Generated> {218        let start = Instant::now();219        let (x0, y0, x1, y1) = t.bounds_3857();220        let unit = t.unit();221        let qs = if parcel_set { layers::parcel_queries(t.z, &self.opts) } else { layers::queries(t.z, &self.opts) };222        let client = self.pool.get().await.context("pool PostgreSQL")?;223        let types = [Type::FLOAT8, Type::FLOAT8, Type::FLOAT8, Type::FLOAT8, Type::FLOAT8, Type::FLOAT8];224225        // Les requêtes partent en rafale sur la même connexion (pipeline) ; les résultats sont assemblés226        // dans l'ordre des couches.227        let futs = qs.iter().map(|q| {228            let client = &client;229            let types = &types;230            async move {231                let stmt = client.prepare_typed_cached(&q.sql, types).await.with_context(|| format!("préparation {}", q.layer))?;232                let margin = q.buffer as f64 * unit;233                let rows = match client.query(&stmt, &[&x0, &y0, &x1, &y1, &margin, &unit]).await {234                    Ok(rows) => rows,235                    Err(e) => match &q.fallback {236                        // Repli sans fusion : la tuile reste servie (voir layers::Query::fallback).237                        Some(fb) => {238                            self.fallback_total.fetch_add(1, Ordering::Relaxed);239                            tracing::debug!(z = t.z, x = t.x, y = t.y, layer = q.layer, error = %e, "repli sans fusion");240                            let stmt = client.prepare_typed_cached(fb, types).await.with_context(|| format!("préparation du repli {}", q.layer))?;241                            client242                                .query(&stmt, &[&x0, &y0, &x1, &y1, &margin, &unit])243                                .await244                                .with_context(|| format!("requête de repli {}", q.layer))?245                        }246                        None => return Err(e).with_context(|| format!("requête {}", q.layer)),247                    },248                };249                Ok::<_, anyhow::Error>((q.layer, rows))250            }251        });252        let results = futures::future::try_join_all(futs).await?;253        drop(client);254255        let mut builders: Vec<LayerBuilder> = Vec::new();256        for (layer, rows) in results {257            if rows.is_empty() {258                continue;259            }260            if builders.last().map(|b| b_name(b) != layer).unwrap_or(true) {261                builders.push(LayerBuilder::new(layer, EXTENT));262            }263            let b = builders.last_mut().unwrap();264            let cols = rows[0].columns();265            let mut attrs: Vec<(&str, Value)> = Vec::with_capacity(cols.len());266            for row in &rows {267                let Some(wkb) = row.try_get::<_, Option<&[u8]>>(0).ok().flatten() else { continue };268                let Some(geom) = mvt::geom_from_wkb(wkb) else { continue };269                attrs.clear();270                for (i, c) in cols.iter().enumerate().skip(1) {271                    let ty = c.type_();272                    let val = if *ty == Type::TEXT || *ty == Type::VARCHAR || *ty == Type::BPCHAR || *ty == Type::NAME {273                        row.try_get::<_, Option<&str>>(i).ok().flatten().filter(|s| !s.is_empty()).map(|s| Value::Str(s.to_string()))274                    } else if *ty == Type::INT4 {275                        row.try_get::<_, Option<i32>>(i).ok().flatten().map(|v| Value::Int(v as i64))276                    } else if *ty == Type::INT2 {277                        row.try_get::<_, Option<i16>>(i).ok().flatten().map(|v| Value::Int(v as i64))278                    } else if *ty == Type::INT8 {279                        row.try_get::<_, Option<i64>>(i).ok().flatten().map(Value::Int)280                    } else if *ty == Type::FLOAT8 {281                        row.try_get::<_, Option<f64>>(i).ok().flatten().map(Value::Double)282                    } else if *ty == Type::FLOAT4 {283                        row.try_get::<_, Option<f32>>(i).ok().flatten().map(|v| Value::Double(v as f64))284                    } else if *ty == Type::BOOL {285                        row.try_get::<_, Option<bool>>(i).ok().flatten().map(Value::Bool)286                    } else {287                        return Err(anyhow!("type de colonne non géré : {} ({})", c.name(), ty));288                    };289                    if let Some(v) = val {290                        attrs.push((c.name(), v));291                    }292                }293                b.add(&geom, &attrs);294            }295        }296297        let mut features = 0u32;298        let mut populated = false;299        let mut layer_counts = Vec::new();300        let mut encoded = Vec::new();301        for b in builders {302            if b.is_empty() {303                continue;304            }305            let name = static_name(b_name(&b));306            features += b.count as u32;307            if name == "building" || name == "road" {308                populated = true;309            }310            let n = b.count as u32;311            let bytes = b.finish();312            layer_counts.push((name, n, bytes.len() as u32));313            encoded.push(bytes);314        }315        let (gz, raw_len) = if features == 0 {316            (Vec::new(), 0)317        } else {318            let raw = mvt::assemble(encoded);319            let mut e = GzEncoder::new(Vec::with_capacity(raw.len() / 2), Compression::new(6));320            e.write_all(&raw)?;321            (e.finish()?, raw.len())322        };323        self.generated_total.fetch_add(1, Ordering::Relaxed);324        Ok(Generated { gz, raw_len, features, populated, millis: start.elapsed().as_secs_f64() * 1000.0, layer_counts })325    }326}327328fn b_name(b: &LayerBuilder) -> &str {329    b.name()330}331332fn static_name(n: &str) -> &'static str {333    layers::LAYERS.iter().copied().find(|l| *l == n).unwrap_or("?")334}335336pub fn cache_path(root: &Path, version: &str, t: Tile) -> PathBuf {337    root.join(version).join(t.z.to_string()).join(t.x.to_string()).join(format!("{}.mvt", t.y))338}339340pub fn check_version_name(v: &str) -> Result<()> {341    if v.is_empty() || v.len() > 40 || !v.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') || v.starts_with('.') {342        return Err(anyhow!("nom de version invalide : {v:?}"));343    }344    Ok(())345}346347async fn fetch_active_version(client: &deadpool_postgres::Client) -> Option<String> {348    let row = client349        .query_opt("SELECT version FROM meta.version WHERE status = 'active' ORDER BY activated_at DESC LIMIT 1", &[])350        .await351        .ok()??;352    row.try_get::<_, String>(0).ok()353}354355pub fn fnv1a64(data: &[u8]) -> u64 {356    let mut h: u64 = 0xcbf29ce484222325;357    for b in data {358        h ^= *b as u64;359        h = h.wrapping_mul(0x100000001b3);360    }361    h362}363364pub fn etag_for(version: &str, data: &[u8]) -> String {365    format!("\"{}-{:016x}\"", version, fnv1a64(data))366}367368#[cfg(test)]369mod tests {370    use super::*;371372    #[test]373    fn version_names() {374        assert!(check_version_name("20261130").is_ok());375        assert!(check_version_name("2026-11-30_b").is_ok());376        assert!(check_version_name("").is_err());377        assert!(check_version_name("../etc").is_err());378        assert!(check_version_name(".hidden").is_err());379        assert!(check_version_name("a/b").is_err());380    }381382    #[test]383    fn cache_layout() {384        let p = cache_path(Path::new("/var/lib/kamaps/cache"), "20261130", Tile { z: 14, x: 4843, y: 5859 });385        assert_eq!(p, PathBuf::from("/var/lib/kamaps/cache/20261130/14/4843/5859.mvt"));386    }387388    #[test]389    fn etag_is_stable_and_quoted() {390        let a = etag_for("v1", b"abc");391        assert_eq!(a, etag_for("v1", b"abc"));392        assert_ne!(a, etag_for("v2", b"abc"));393        assert_ne!(a, etag_for("v1", b"abd"));394        assert!(a.starts_with('"') && a.ends_with('"'));395    }396}397
Files main
Menu

Theme