SPB Git

Repository Public

static-map.ts 8.0 KB 176 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : server/km-maps/src/static-map.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/ka-maps-engine11 * Created          : 2026-12-0112 * Last Modified    : 2026-12-0113 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Cartes statiques : validation stricte des paramètres, clé de cache, rendu par kmr, cache disque.43import { createHash, randomBytes } from 'node:crypto';44import { mkdir, readdir, readFile, rename, stat, unlink, utimes } from 'node:fs/promises';45import { join } from 'node:path';46import { APPS } from '../lib/rollout.ts';4748export type StaticParams = {49  lon: number; lat: number; zoom: number; width: number; height: number; scale: number;50  theme: string | null; app: string | null; bearing: number; pitch: number; mode: '2d' | '3d' | null;51  markers: { lon: number; lat: number; label?: string }[];52};5354export const STATIC_LIMITS = { maxSide: 1280, minSide: 32, maxMarkers: 20, maxLabel: 24 };55const ALLOWED = new Set(['center', 'zoom', 'size', 'scale', 'theme', 'app', 'marker', 'bearing', 'pitch', 'mode']);56const NUM = /^-?\d{1,3}(\.\d{1,8})?$/;57const LABEL = /^[\p{L}\p{N} $€%.,'’+\-/#]{1,24}$/u;5859function num(s: string | null, name: string, min: number, max: number, def: number | null): number {60  if (s === null) {61    if (def === null) throw new Error(`${name} requis`);62    return def;63  }64  if (!NUM.test(s)) throw new Error(`${name} : nombre invalide`);65  const v = Number(s);66  if (v < min || v > max) throw new Error(`${name} : hors limites (${min} à ${max})`);67  return v;68}6970/** Analyse la requête ; lève une erreur au message précis (rendu en 400) pour tout paramètre inconnu ou invalide. */71export function parseStaticQuery(q: URLSearchParams): StaticParams {72  for (const k of q.keys()) if (!ALLOWED.has(k)) throw new Error(`paramètre inconnu : ${k.slice(0, 40)}`);73  for (const k of ALLOWED) if (k !== 'marker' && q.getAll(k).length > 1) throw new Error(`${k} : une seule valeur`);74  const center = (q.get('center') ?? '').split(',');75  if (center.length !== 2) throw new Error('center : lon,lat requis');76  const lon = num(center[0], 'center (longitude)', -180, 180, null);77  const lat = num(center[1], 'center (latitude)', -85, 85, null);78  const size = /^(\d{2,4})x(\d{2,4})$/.exec(q.get('size') ?? '600x400');79  if (!size) throw new Error('size : LxH attendu, par exemple 600x400');80  const [width, height] = [Number(size[1]), Number(size[2])];81  for (const v of [width, height]) if (v < STATIC_LIMITS.minSide || v > STATIC_LIMITS.maxSide) throw new Error(`size : chaque côté de ${STATIC_LIMITS.minSide} à ${STATIC_LIMITS.maxSide}`);82  const scaleRaw = q.get('scale') ?? '1';83  if (scaleRaw !== '1' && scaleRaw !== '2') throw new Error('scale : 1 ou 2');84  const theme = q.get('theme');85  if (theme !== null && !/^[a-z][a-z0-9-]{1,30}$/.test(theme)) throw new Error('theme : identifiant invalide');86  const app = q.get('app');87  if (app !== null && !(APPS as readonly string[]).includes(app)) throw new Error(`app : ${APPS.join(', ')}`);88  const mode = q.get('mode');89  if (mode !== null && mode !== '2d' && mode !== '3d') throw new Error('mode : 2d ou 3d');90  const rawMarkers = q.getAll('marker');91  if (rawMarkers.length > STATIC_LIMITS.maxMarkers) throw new Error(`marker : ${STATIC_LIMITS.maxMarkers} au plus`);92  const markers = rawMarkers.map((m, i) => {93    const p = m.split(',');94    if (p.length < 2) throw new Error(`marker ${i + 1} : lon,lat[,étiquette]`);95    const label = p.length > 2 ? p.slice(2).join(',').trim() : undefined;96    if (label !== undefined && !LABEL.test(label)) throw new Error(`marker ${i + 1} : étiquette de 1 à ${STATIC_LIMITS.maxLabel} caractères (lettres, chiffres, espace, $ € % . , ' + - / #)`);97    return { lon: num(p[0], `marker ${i + 1} (longitude)`, -180, 180, null), lat: num(p[1], `marker ${i + 1} (latitude)`, -85, 85, null), ...(label ? { label } : {}) };98  });99  return {100    lon, lat,101    zoom: num(q.get('zoom'), 'zoom', 0, 20, 14),102    width, height,103    scale: Number(scaleRaw),104    theme, app,105    bearing: num(q.get('bearing'), 'bearing', -360, 360, 0),106    pitch: num(q.get('pitch'), 'pitch', 0, 72, 0),107    mode: mode as StaticParams['mode'],108    markers,109  };110}111112/** Clé de cache : paramètres normalisés + tout ce qui change l'image (version du thème, révision de marque, données). */113export function staticKey(p: StaticParams, themeId: string, themeVersion: number, brandRev: number | null, dataVersion: string | null): string {114  const norm = JSON.stringify([p.lon, p.lat, p.zoom, p.width, p.height, p.scale, themeId, themeVersion, p.app, brandRev, ((p.bearing % 360) + 360) % 360, p.pitch, p.mode, p.markers, dataVersion, 'r1']);115  return createHash('sha256').update(norm).digest('hex').slice(0, 40);116}117118export class DiskCache {119  public dir: string;120  private maxBytes: number;121  constructor(dir: string, maxBytes: number) {122    this.dir = dir;123    this.maxBytes = maxBytes;124  }125  path(key: string) {126    return join(this.dir, key.slice(0, 2), `${key}.png`);127  }128  async get(key: string): Promise<Buffer | null> {129    try {130      const p = this.path(key);131      const buf = await readFile(p);132      const now = new Date();133      utimes(p, now, now).catch(() => {});134      return buf;135    } catch {136      return null;137    }138  }139  /** Chemin temporaire où écrire, puis `commit` (renommage atomique). */140  async tmp(key: string): Promise<string> {141    await mkdir(join(this.dir, key.slice(0, 2)), { recursive: true });142    return join(this.dir, key.slice(0, 2), `.${key}.${randomBytes(4).toString('hex')}.tmp`);143  }144  async commit(tmp: string, key: string): Promise<Buffer> {145    const buf = await readFile(tmp);146    await rename(tmp, this.path(key));147    return buf;148  }149  /** Retire les images les moins récemment servies quand le cache dépasse sa taille. */150  async prune(): Promise<{ files: number; bytes: number; removed: number }> {151    const files: { p: string; size: number; t: number }[] = [];152    for (const d of await readdir(this.dir).catch(() => [] as string[])) {153      for (const f of await readdir(join(this.dir, d)).catch(() => [] as string[])) {154        const p = join(this.dir, d, f);155        const s = await stat(p).catch(() => null);156        if (!s) continue;157        if (f.endsWith('.tmp')) {158          if (Date.now() - s.mtimeMs > 600_000) await unlink(p).catch(() => {});159          continue;160        }161        files.push({ p, size: s.size, t: s.mtimeMs });162      }163    }164    let bytes = files.reduce((a, f) => a + f.size, 0);165    let removed = 0;166    files.sort((a, b) => a.t - b.t);167    for (const f of files) {168      if (bytes <= this.maxBytes) break;169      await unlink(f.p).catch(() => {});170      bytes -= f.size;171      removed++;172    }173    return { files: files.length - removed, bytes, removed };174  }175}176
Files main
Menu

Theme