Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : server/km-maps/src/app.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// Service public de manifeste : routes, caches, compteurs agrégés.43import { readdir, readFile, stat } from 'node:fs/promises';44import type { IncomingMessage, ServerResponse } from 'node:http';45import { extname, join, normalize } from 'node:path';46import { brotliCompressSync, gzipSync, constants as zc } from 'node:zlib';47import type { Pool } from 'pg';48import { brandDocument } from '../lib/brand.ts';49import { clientIp, etagOf, json, Metrics, problem, RateLimiter, type Reply, send } from '../lib/http.ts';50import { Gate, kmrRender } from '../lib/kmr.ts';51import { APPS, PLATFORMS } from '../lib/rollout.ts';52import { compareSemver, SEMVER_RE } from '../lib/semver.ts';53import { buildManifest, channelKey, Documents, type Endpoints, loadSnapshot, readRevision, type Snapshot } from '../lib/snapshot.ts';54import { landingPage, licencesPage, type ServiceState, SITE_CSS } from './pages.ts';55import { DiskCache, parseStaticQuery, staticKey } from './static-map.ts';5657export type Config = {58 schema: string;59 endpoints: Endpoints;60 tilerLocal: string;61 health: { name: string; label: string; url: string; public: string }[];62 sdkDir: string;63 staticCacheDir: string;64 staticCacheMax: number;65 licensingMd: string;66 staticEnabled: boolean;67 rate: { general: number; staticMiss: number };68 pollMs: number;69};7071export function configFromEnv(env = process.env): Config {72 const e = (k: string, d: string) => env[k] ?? d;73 return {74 schema: e('KM_MAPS_SCHEMA', 'studio'),75 endpoints: {76 tiles: e('KM_PUBLIC_TILES', 'https://tiles.spboucher.ai'),77 terrain: e('KM_PUBLIC_TERRAIN', 'https://terrain.spboucher.ai'),78 geo: e('KM_PUBLIC_GEO', 'https://geo.spboucher.ai'),79 maps: e('KM_PUBLIC_MAPS', 'https://maps.spboucher.ai'),80 },81 tilerLocal: e('KM_TILER_LOCAL', 'http://127.0.0.1:8901'),82 health: [83 { name: 'km-tiler', label: 'Tuiles vectorielles', url: e('KM_HEALTH_TILER', 'http://127.0.0.1:8901/healthz'), public: e('KM_PUBLIC_TILES', 'https://tiles.spboucher.ai') },84 { name: 'km-geo', label: "Recherche d'adresses", url: e('KM_HEALTH_GEO', 'http://127.0.0.1:8902/healthz'), public: e('KM_PUBLIC_GEO', 'https://geo.spboucher.ai') },85 { name: 'km-terrain', label: 'Relief', url: e('KM_HEALTH_TERRAIN', 'http://127.0.0.1:8903/healthz'), public: e('KM_PUBLIC_TERRAIN', 'https://terrain.spboucher.ai') },86 ],87 sdkDir: e('KM_SDK_DIR', '/var/lib/kamaps/sdk'),88 staticCacheDir: e('KM_STATIC_CACHE', '/var/lib/kamaps/static-maps'),89 staticCacheMax: Number(e('KM_STATIC_CACHE_MAX', String(2 * 1024 ** 3))),90 licensingMd: e('KM_LICENSING_MD', '/opt/kamaps/app/docs/DATA_LICENSING.md'),91 staticEnabled: e('KM_STATIC_ENABLED', '1') === '1',92 rate: { general: Number(e('KM_RATE_GENERAL', '600')), staticMiss: Number(e('KM_RATE_STATIC', '30')) },93 pollMs: Number(e('KM_POLL_MS', '2000')),94 };95}9697const MIME: Record<string, string> = {98 '.wasm': 'application/wasm', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',99 '.json': 'application/json; charset=utf-8', '.map': 'application/json; charset=utf-8', '.css': 'text/css; charset=utf-8',100 '.html': 'text/html; charset=utf-8', '.ts': 'text/plain; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.md': 'text/plain; charset=utf-8',101 '.png': 'image/png', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.bin': 'application/octet-stream',102};103const CORS = { 'Access-Control-Allow-Origin': '*', 'Cross-Origin-Resource-Policy': 'cross-origin', 'Timing-Allow-Origin': '*' };104const IMMUTABLE = 'public, max-age=31536000, immutable';105const SHORT = 'public, max-age=60, stale-while-revalidate=600';106const HTML_HEADERS = {107 'Content-Security-Policy': "default-src 'none'; style-src 'self'; img-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",108 'X-Frame-Options': 'DENY',109 'Referrer-Policy': 'no-referrer',110 'Cache-Control': 'public, max-age=60',111};112113export function createApp(pool: Pool, cfg: Config) {114 const metrics = new Metrics('km_maps');115 const docs = new Documents(pool, cfg.schema);116 const general = new RateLimiter(cfg.rate.general, cfg.rate.general);117 const staticMiss = new RateLimiter(cfg.rate.staticMiss, Math.max(5, Math.round(cfg.rate.staticMiss / 2)));118 const gate = new Gate(3, 12);119 const disk = new DiskCache(cfg.staticCacheDir, cfg.staticCacheMax);120 const inflight = new Map<string, Promise<Buffer>>();121 const usage = new Map<string, number>();122 const memo = new Map<string, { body: string; etag: string }>();123 const sdkFiles = new Map<string, { raw: Buffer; br?: Buffer; gzip?: Buffer; etag: string; mtime: number }>();124 let snap: Snapshot | null = null;125 let snapError: string | null = null;126 let services: ServiceState[] = cfg.health.map((h) => ({ name: h.name, label: h.label, url: h.public, ok: null, ms: null, checkedAt: null }));127 let sdkVersions: string[] = [];128 let licensing: string | null = null;129 const timers: NodeJS.Timeout[] = [];130 const started = Date.now();131132 const count = (app: string | null, platform: string | null, kind: string) => {133 const k = `${new Date().toISOString().slice(0, 10)}|${app ?? '-'}|${platform ?? '-'}|${kind}`;134 usage.set(k, (usage.get(k) ?? 0) + 1);135 };136137 async function flushUsage() {138 if (usage.size === 0) return;139 const rows = [...usage.entries()];140 usage.clear();141 try {142 const vals: any[] = [];143 const ph = rows.map(([k, n], i) => {144 const [day, app, platform, kind] = k.split('|');145 vals.push(day, app, platform, kind, n);146 return `($${i * 5 + 1}, $${i * 5 + 2}, $${i * 5 + 3}, $${i * 5 + 4}, $${i * 5 + 5})`;147 });148 await pool.query(`INSERT INTO ${cfg.schema}.usage_daily (day, app, platform, kind, count) VALUES ${ph.join(',')} ON CONFLICT (day, app, platform, kind) DO UPDATE SET count = ${cfg.schema}.usage_daily.count + EXCLUDED.count`, vals);149 } catch {150 for (const [k, n] of rows) usage.set(k, (usage.get(k) ?? 0) + n);151 }152 }153154 async function refresh(force = false) {155 try {156 if (!force && snap) {157 const rev = await readRevision(pool, cfg.schema);158 if (rev === snap.revision) return;159 }160 snap = await loadSnapshot(pool, cfg.schema);161 memo.clear();162 snapError = null;163 } catch (e: any) {164 snapError = String(e?.message ?? e); // l'instantané précédent continue d'être servi165 }166 }167168 async function checkServices() {169 services = await Promise.all(170 cfg.health.map(async (h) => {171 const t0 = performance.now();172 try {173 const r = await fetch(h.url, { signal: AbortSignal.timeout(3000) });174 await r.arrayBuffer();175 return { name: h.name, label: h.label, url: h.public, ok: r.ok, ms: performance.now() - t0, checkedAt: new Date().toISOString() };176 } catch {177 return { name: h.name, label: h.label, url: h.public, ok: false, ms: null, checkedAt: new Date().toISOString() };178 }179 }),180 );181 }182183 async function scanSdk() {184 const list = await readdir(cfg.sdkDir, { withFileTypes: true }).catch(() => []);185 sdkVersions = list.filter((d) => d.isDirectory() && SEMVER_RE.test(d.name)).map((d) => d.name).sort(compareSemver).reverse();186 licensing = await readFile(cfg.licensingMd, 'utf8').catch(() => null);187 }188189 async function start() {190 await refresh(true);191 await Promise.all([checkServices(), scanSdk()]);192 timers.push(setInterval(() => refresh(), cfg.pollMs), setInterval(() => refresh(true), 60_000), setInterval(checkServices, 30_000), setInterval(scanSdk, 30_000), setInterval(flushUsage, 30_000), setInterval(() => disk.prune().catch(() => {}), 3600_000));193 for (const t of timers) t.unref();194 }195 async function stop() {196 for (const t of timers) clearInterval(t);197 await flushUsage();198 }199200 // ---------- routes201 function manifest(q: URLSearchParams): Reply {202 const app = q.get('app');203 const platform = q.get('platform') ?? 'web';204 const engine = q.get('engine');205 const bucketRaw = q.get('bucket');206 if (!app || !(APPS as readonly string[]).includes(app)) return problem(400, `app requis : ${APPS.join(', ')}`);207 if (!(PLATFORMS as readonly string[]).includes(platform)) return problem(400, `platform : ${PLATFORMS.join(', ')}`);208 if (engine !== null && !SEMVER_RE.test(engine)) return problem(400, 'engine : version a.b.c attendue');209 if (bucketRaw !== null && !/^\d{1,2}$/.test(bucketRaw)) return problem(400, 'bucket : entier de 0 à 99');210 if (!snap) return problem(503, 'manifeste indisponible');211 const bucket = bucketRaw === null ? null : Number(bucketRaw);212 const k = `m|${app}|${platform}|${engine}|${bucket}`;213 let m = memo.get(k);214 if (!m) {215 const doc = buildManifest(snap, { app, platform, engine, bucket }, cfg.endpoints, sdkVersions[0] ? { version: sdkVersions[0] } : null);216 if (!doc) return problem(404, 'application sans configuration publiée');217 const body = JSON.stringify(doc);218 m = { body, etag: etagOf(body) };219 if (memo.size > 5000) memo.clear();220 memo.set(k, m);221 }222 count(app, platform, 'manifest');223 return { type: 'application/json; charset=utf-8', body: m.body, headers: { ...CORS, ETag: m.etag, 'Cache-Control': SHORT } };224 }225226 async function themeVersion(id: string, versionStr: string, q: URLSearchParams): Promise<Reply> {227 const version = Number(versionStr);228 const app = q.get('app');229 const brand = q.get('brand');230 if (app !== null || brand !== null) {231 if (!app || !(APPS as readonly string[]).includes(app) || !brand || !/^\d{1,9}$/.test(brand)) return problem(400, 'app et brand (révision) vont ensemble');232 const text = await docs.effectiveText(id, version, app, Number(brand));233 if (text === null) return problem(404, 'version ou révision inconnue');234 count(app, null, 'theme');235 return { type: 'application/json; charset=utf-8', body: text, headers: { ...CORS, ETag: etagOf(text), 'Cache-Control': IMMUTABLE } };236 }237 const text = await docs.themeText(id, version);238 if (text === null) return problem(404, 'version inconnue');239 count(null, null, 'theme');240 return { type: 'application/json; charset=utf-8', body: text, headers: { ...CORS, ETag: etagOf(text), 'Cache-Control': IMMUTABLE } };241 }242243 async function themeCurrent(id: string, q: URLSearchParams): Promise<Reply> {244 const app = q.get('app');245 const platform = q.get('platform') ?? 'web';246 const engine = q.get('engine');247 const bucketRaw = q.get('bucket');248 if (!app || !(APPS as readonly string[]).includes(app)) return problem(400, `app requis : ${APPS.join(', ')}`);249 if (!(PLATFORMS as readonly string[]).includes(platform)) return problem(400, `platform : ${PLATFORMS.join(', ')}`);250 if (engine !== null && !SEMVER_RE.test(engine)) return problem(400, 'engine : version a.b.c attendue');251 if (bucketRaw !== null && !/^\d{1,2}$/.test(bucketRaw)) return problem(400, 'bucket : entier de 0 à 99');252 if (!snap) return problem(503, 'manifeste indisponible');253 const m = buildManifest(snap, { app, platform, engine, bucket: bucketRaw === null ? null : Number(bucketRaw) }, cfg.endpoints, null);254 const t = m?.themes.find((x: any) => x.id === id);255 if (!m || !t) return problem(404, 'thème non servi à cette application');256 const text = await docs.effectiveText(id, t.version, app, m.config.rev);257 if (text === null) return problem(404, 'thème introuvable');258 count(app, platform, 'theme');259 return { type: 'application/json; charset=utf-8', body: text, headers: { ...CORS, ETag: etagOf(text), 'Cache-Control': SHORT, 'X-KA-Theme-Version': String(t.version), 'X-KA-Brand-Rev': String(m.config.rev), 'Access-Control-Expose-Headers': 'X-KA-Theme-Version, X-KA-Brand-Rev' } };260 }261262 async function brandRev(app: string, revStr: string): Promise<Reply> {263 const config = await docs.appRev(app, Number(revStr));264 if (!config) return problem(404, 'révision inconnue');265 const text = JSON.stringify(brandDocument(app, config));266 return { type: 'application/json; charset=utf-8', body: text, headers: { ...CORS, ETag: etagOf(text), 'Cache-Control': IMMUTABLE } };267 }268269 async function icon(name: string): Promise<Reply> {270 const r = await pool.query(`SELECT svg, sha256 FROM ${cfg.schema}.icon WHERE name = $1`, [name]);271 if (!r.rows[0]) return problem(404, 'icône inconnue');272 return { type: 'image/svg+xml', body: r.rows[0].svg, headers: { ...CORS, ETag: `"${r.rows[0].sha256.slice(0, 27)}"`, 'Cache-Control': 'public, max-age=300, stale-while-revalidate=86400', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox", 'X-Content-Type-Options': 'nosniff' } };273 }274275 async function staticMap(req: IncomingMessage, q: URLSearchParams): Promise<Reply> {276 if (!cfg.staticEnabled) return problem(503, 'rendu statique désactivé');277 let p;278 try {279 p = parseStaticQuery(q);280 } catch (e: any) {281 metrics.inc('static_total', { result: 'invalid' });282 return problem(400, e.message);283 }284 if (!snap) return problem(503, 'manifeste indisponible');285 const appCfg = p.app ? snap.apps.get(p.app) : undefined;286 if (p.app && !appCfg) return problem(404, 'application sans configuration publiée');287 const themeId = p.theme ?? appCfg?.config.defaultTheme ?? 'signature';288 const theme = snap.themes.get(themeId);289 if (!theme) return problem(404, `thème inconnu : ${themeId}`);290 // Version stable (jamais la candidate) : celle de l'application sur le Web, sinon la plus haute en service.291 let version: number | null = null;292 if (p.app) version = snap.channels.get(channelKey(themeId, p.app, 'web'))?.stable ?? null;293 else for (const a of APPS) for (const pf of PLATFORMS) version = Math.max(version ?? 0, snap.channels.get(channelKey(themeId, a, pf))?.stable ?? 0) || null;294 if (version === null) return problem(404, 'thème non publié');295 const key = staticKey(p, themeId, version, appCfg?.rev ?? null, snap.dataVersion);296 const headers = { ...CORS, ETag: `"${key.slice(0, 27)}"`, 'Cache-Control': 'public, max-age=86400, stale-while-revalidate=604800', 'X-KA-Theme-Version': String(version) };297 const inm = String(req.headers['if-none-match'] ?? '');298 let buf = inm.includes(headers.ETag) ? Buffer.alloc(0) : await disk.get(key);299 if (buf) {300 metrics.inc('static_total', { result: 'hit' });301 } else {302 if (!staticMiss.take(clientIp(req))) {303 metrics.inc('static_total', { result: 'limited' });304 return problem(429, 'trop de rendus demandés, réessayer dans une minute', undefined);305 }306 let job = inflight.get(key);307 if (!job) {308 job = gate.run(async () => {309 const text = await docs.themeText(themeId, version!);310 if (!text) throw new Error('thème introuvable');311 const tmp = await disk.tmp(key);312 const t0 = performance.now();313 const r = await kmrRender({314 theme: JSON.parse(text),315 ...(appCfg ? { brand: brandDocument(p.app!, appCfg.config) } : {}),316 center: [p.lon, p.lat], zoom: p.zoom, pitch: p.pitch, bearing: p.bearing,317 ...(p.mode ? { mode: p.mode } : {}),318 width: p.width, height: p.height, scale: p.scale, tiles: cfg.tilerLocal, markers: p.markers, timeout: 20,319 }, tmp);320 if (!r.ok) throw new Error(`rendu refusé : ${JSON.stringify(r.errors).slice(0, 300)}`);321 metrics.observe('static_render_ms', {}, performance.now() - t0);322 return disk.commit(tmp, key);323 });324 inflight.set(key, job);325 job.finally(() => inflight.delete(key)).catch(() => {});326 }327 try {328 buf = await job;329 metrics.inc('static_total', { result: 'rendered' });330 } catch (e: any) {331 if (e.code === 'BUSY') {332 metrics.inc('static_total', { result: 'busy' });333 return { ...problem(503, 'rendu saturé, réessayer'), headers: { 'Retry-After': '2', 'Cache-Control': 'no-store' } };334 }335 metrics.inc('static_total', { result: 'error' });336 console.error(`static: ${e.message}`);337 return problem(500, 'rendu impossible');338 }339 }340 count(p.app, null, 'static');341 return { type: 'image/png', body: buf, headers };342 }343344 async function sdkFile(rel: string): Promise<{ reply: Reply; pre?: { br?: Buffer; gzip?: Buffer } }> {345 if (rel === 'index.json') return { reply: json({ versions: sdkVersions, latest: sdkVersions[0] ?? null }, { headers: { ...CORS, 'Cache-Control': SHORT } }) };346 if (!/^[A-Za-z0-9._\-/]{1,200}$/.test(rel) || rel.includes('..')) return { reply: problem(400, 'chemin invalide') };347 const [version, ...rest] = rel.split('/');348 if (!sdkVersions.includes(version)) return { reply: problem(404, 'version du SDK inconnue') };349 let file = normalize(join(cfg.sdkDir, version, rest.join('/') || 'index.js'));350 if (!file.startsWith(join(cfg.sdkDir, version) + '/')) return { reply: problem(400, 'chemin invalide') };351 const st = await stat(file).catch(() => null);352 if (!st || !st.isFile()) return { reply: problem(404, 'fichier inconnu') };353 const type = MIME[extname(file)] ?? 'application/octet-stream';354 let f = sdkFiles.get(file);355 if (!f || f.mtime !== st.mtimeMs) {356 const raw = await readFile(file);357 f = { raw, etag: etagOf(raw), mtime: st.mtimeMs };358 if (raw.length > 1024 && /wasm|javascript|json|css|svg|text/.test(type)) {359 f.br = brotliCompressSync(raw, { params: { [zc.BROTLI_PARAM_QUALITY]: 9, [zc.BROTLI_PARAM_SIZE_HINT]: raw.length } });360 f.gzip = gzipSync(raw, { level: 9 });361 }362 if (sdkFiles.size > 200) sdkFiles.clear();363 sdkFiles.set(file, f);364 }365 count(null, 'web', 'sdk');366 return { reply: { type, body: f.raw, headers: { ...CORS, ETag: f.etag, 'Cache-Control': IMMUTABLE, 'X-Content-Type-Options': 'nosniff' } }, pre: { br: f.br, gzip: f.gzip } };367 }368369 async function route(req: IncomingMessage, url: URL): Promise<{ reply: Reply; route: string; pre?: { br?: Buffer; gzip?: Buffer } }> {370 const p = url.pathname;371 const q = url.searchParams;372 let m: RegExpExecArray | null;373 if (p === '/healthz') return { route: 'healthz', reply: json({ status: snap ? 'ok' : 'starting', revision: snap?.revision ?? null, stale: snapError !== null, uptime_s: Math.round((Date.now() - started) / 1000) }, { status: snap ? 200 : 503, headers: { 'Cache-Control': 'no-store' } }) };374 if (p === '/v1/manifest.json') return { route: 'manifest', reply: manifest(q) };375 if ((m = /^\/v1\/themes\/([a-z][a-z0-9-]{1,30})\/(\d{1,6})\.json$/.exec(p))) return { route: 'theme', reply: await themeVersion(m[1], m[2], q) };376 if ((m = /^\/v1\/themes\/([a-z][a-z0-9-]{1,30})\/current\.json$/.exec(p))) return { route: 'theme_current', reply: await themeCurrent(m[1], q) };377 if ((m = /^\/v1\/brands\/([a-z]{3,12})\/(\d{1,9})\.json$/.exec(p))) return { route: 'brand', reply: await brandRev(m[1], m[2]) };378 if (p === '/v1/icons/index.json') return { route: 'icons', reply: json({ icons: (snap?.icons ?? []).map((i) => ({ ...i, url: `${cfg.endpoints.maps}/v1/icons/${i.name}.svg` })) }, { headers: { ...CORS, 'Cache-Control': SHORT } }) };379 if ((m = /^\/v1\/icons\/([a-z][a-z0-9-]{0,40})\.svg$/.exec(p))) return { route: 'icon', reply: await icon(m[1]) };380 if (p === '/v1/static') return { route: 'static', reply: await staticMap(req, q) };381 if (p.startsWith('/sdk/')) return { route: 'sdk', ...(await sdkFile(p.slice(5))) };382 if (p === '/status.json') return { route: 'status', reply: json({ services: services.map((s) => ({ name: s.name, ok: s.ok, ms: s.ms === null ? null : Math.round(s.ms), checkedAt: s.checkedAt })), dataVersion: snap?.dataVersion ?? null, revision: snap?.revision ?? null, sdk: sdkVersions[0] ?? null, staticMaps: cfg.staticEnabled }, { headers: { ...CORS, 'Cache-Control': 'public, max-age=30' } }) };383 if (p === '/') {384 if (!snap) return { route: 'page', reply: problem(503, 'indisponible') };385 const body = landingPage(snap, services, cfg.staticEnabled && snap.themes.has('signature'), sdkVersions[0] ?? null);386 return { route: 'page', reply: { type: 'text/html; charset=utf-8', body, headers: { ...HTML_HEADERS, ETag: etagOf(body) } } };387 }388 if (p === '/licences') {389 const body = licencesPage(licensing, snap?.datasets ?? []);390 return { route: 'page', reply: { type: 'text/html; charset=utf-8', body, headers: { ...HTML_HEADERS, ETag: etagOf(body) } } };391 }392 if (p === '/site.css') return { route: 'page', reply: { type: 'text/css; charset=utf-8', body: SITE_CSS, headers: { ETag: etagOf(SITE_CSS), 'Cache-Control': 'public, max-age=3600' } } };393 if (p === '/robots.txt') return { route: 'page', reply: { type: 'text/plain; charset=utf-8', body: 'User-agent: *\nDisallow: /v1/\nDisallow: /sdk/\n', headers: { 'Cache-Control': 'public, max-age=86400' } } };394 return { route: 'other', reply: problem(404, 'introuvable') };395 }396397 async function handler(req: IncomingMessage, res: ServerResponse) {398 const t0 = performance.now();399 let routeName = 'other';400 let status = 500;401 try {402 const base = { 'X-Content-Type-Options': 'nosniff', 'Strict-Transport-Security': 'max-age=31536000' };403 if (req.method === 'OPTIONS') {404 res.writeHead(204, { ...CORS, 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS', 'Access-Control-Allow-Headers': 'If-None-Match', 'Access-Control-Max-Age': '86400' });405 res.end();406 status = 204;407 return;408 }409 if (req.method !== 'GET' && req.method !== 'HEAD') {410 status = send(req, res, { ...problem(405, 'lecture seule'), headers: { Allow: 'GET, HEAD, OPTIONS', 'Cache-Control': 'no-store' } });411 return;412 }413 if (!general.take(clientIp(req))) {414 routeName = 'limited';415 status = send(req, res, { ...problem(429, 'trop de requêtes'), headers: { 'Retry-After': '10', 'Cache-Control': 'no-store' } });416 return;417 }418 if ((req.url ?? '').length > 4096) {419 status = send(req, res, problem(414, 'adresse trop longue'));420 return;421 }422 const url = new URL(req.url ?? '/', 'http://x');423 const r = await route(req, url);424 routeName = r.route;425 r.reply.headers = { ...base, ...(r.reply.headers ?? {}) };426 status = send(req, res, r.reply, { precompressed: r.pre });427 } catch (e: any) {428 console.error(`erreur ${req.method} ${String(req.url).split('?')[0]} : ${e?.message ?? e}`);429 if (!res.headersSent) status = send(req, res, problem(500, 'erreur interne'));430 else res.end();431 } finally {432 metrics.inc('requests_total', { route: routeName, status: `${Math.floor(status / 100)}xx` });433 metrics.observe('duration_ms', { route: routeName }, performance.now() - t0);434 }435 }436437 function metricsText(): string {438 return metrics.render({ uptime_seconds: Math.round((Date.now() - started) / 1000), snapshot_revision: snap?.revision ?? 0, snapshot_stale: snapError ? 1 : 0, render_running: gate.load.running, render_waiting: gate.load.waiting });439 }440441 return { handler, start, stop, refresh, flushUsage, metricsText, state: () => ({ snap, snapError, services, sdkVersions }) };442}443