Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-geo/src/err.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//! Erreurs d'API : JSON court, jamais de détail interne (ni SQL, ni paramètres).8889use axum::http::{header, HeaderValue, StatusCode};90use axum::response::{IntoResponse, Response};9192#[derive(Debug)]93pub struct ApiError {94 pub status: StatusCode,95 pub code: &'static str,96 pub message: String,97}9899impl ApiError {100 pub fn bad(message: impl Into<String>) -> Self {101 Self { status: StatusCode::BAD_REQUEST, code: "requete_invalide", message: message.into() }102 }103 pub fn not_found(message: impl Into<String>) -> Self {104 Self { status: StatusCode::NOT_FOUND, code: "introuvable", message: message.into() }105 }106 pub fn unavailable() -> Self {107 Self { status: StatusCode::SERVICE_UNAVAILABLE, code: "service_indisponible", message: "Service momentanément indisponible.".into() }108 }109 pub fn timeout() -> Self {110 Self { status: StatusCode::GATEWAY_TIMEOUT, code: "delai_depasse", message: "La requête a pris trop de temps.".into() }111 }112 pub fn too_many(wait: f64) -> Response {113 let mut r = Self { status: StatusCode::TOO_MANY_REQUESTS, code: "trop_de_requetes", message: "Trop de requêtes ; réessayez dans un instant.".into() }114 .into_response();115 r.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from_str(&format!("{}", wait.ceil().max(1.0) as u64)).unwrap());116 r117 }118}119120impl IntoResponse for ApiError {121 fn into_response(self) -> Response {122 let body = serde_json::json!({ "error": { "code": self.code, "message": self.message } });123 let mut r = (self.status, axum::Json(body)).into_response();124 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));125 r126 }127}128129/// Erreur de base : on ne journalise que le point d'accès et le code SQLSTATE.130pub fn db_err(endpoint: &'static str, e: impl Into<DbError>) -> ApiError {131 match e.into() {132 DbError::Pg(e) => {133 let code = e.code().map(|c| c.code().to_string()).unwrap_or_else(|| "connexion".into());134 eprintln!("km-geo: erreur base ({endpoint}) sqlstate={code}");135 if code == "57014" { ApiError::timeout() } else { ApiError::unavailable() }136 }137 DbError::Pool => {138 eprintln!("km-geo: erreur base ({endpoint}) pool");139 ApiError::unavailable()140 }141 }142}143144pub enum DbError {145 Pg(tokio_postgres::Error),146 Pool,147}148impl From<tokio_postgres::Error> for DbError {149 fn from(e: tokio_postgres::Error) -> Self {150 DbError::Pg(e)151 }152}153impl From<deadpool_postgres::PoolError> for DbError {154 fn from(e: deadpool_postgres::PoolError) -> Self {155 match e {156 deadpool_postgres::PoolError::Backend(e) => DbError::Pg(e),157 _ => DbError::Pool,158 }159 }160}161