Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : server/km-maps/lib/snapshot.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// Instantané cohérent de ce qui est publié (lu en une transaction) et construction du manifeste.43import type { Pool } from 'pg';44import { type AppConfig, applyLayerSwitches, brandDocument } from './brand.ts';45import { sha256hex } from './http.ts';46import { kmrValidate } from './kmr.ts';47import { APPS, type ChannelState, resolveTheme } from './rollout.ts';4849export type VersionInfo = { version: number; minEngine: string; sha256: string; bytes: number; createdAt: string };50export type Snapshot = {51 revision: number;52 themes: Map<string, { id: string; title: string; versions: VersionInfo[] }>;53 channels: Map<string, ChannelState>;54 apps: Map<string, { rev: number; config: AppConfig; brandText: string; brandSha: string }>;55 icons: { name: string; sha256: string; bytes: number }[];56 datasets: any[];57 dataVersion: string | null;58};5960export const channelKey = (theme: string, app: string, platform: string) => `${theme}|${app}|${platform}`;6162export async function readRevision(pool: Pool, schema = 'studio'): Promise<number> {63 const r = await pool.query(`SELECT value FROM ${schema}.state WHERE key = 'revision'`);64 return Number(r.rows[0]?.value ?? 0);65}6667export async function loadSnapshot(pool: Pool, schema = 'studio'): Promise<Snapshot> {68 const c = await pool.connect();69 try {70 await c.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');71 const rev = await c.query(`SELECT value FROM ${schema}.state WHERE key = 'revision'`);72 const th = await c.query(`SELECT id, title FROM ${schema}.theme WHERE archived_at IS NULL ORDER BY id`);73 const ve = await c.query(`SELECT theme_id, version, min_engine, sha256, octet_length(doc_text) AS bytes, created_at FROM ${schema}.theme_version ORDER BY theme_id, version`);74 const ch = await c.query(`SELECT theme_id, app, platform, stable_version, candidate_version, candidate_percent FROM ${schema}.channel`);75 const ap = await c.query(`SELECT DISTINCT ON (app) app, id, config FROM ${schema}.app_config_rev ORDER BY app, id DESC`);76 const ic = await c.query(`SELECT name, sha256, bytes FROM ${schema}.icon ORDER BY name`);77 let datasets: any[] = [];78 let dataVersion: string | null = null;79 try {80 await c.query('SAVEPOINT meta');81 datasets = (await c.query(`SELECT id, title, provider, url, licence, licence_url, attribution, source_date, layers, status FROM meta.dataset ORDER BY provider, title`)).rows;82 dataVersion = (await c.query(`SELECT version FROM meta.version WHERE status = 'active'`)).rows[0]?.version ?? null;83 } catch {84 await c.query('ROLLBACK TO SAVEPOINT meta');85 }86 await c.query('COMMIT');87 const themes: Snapshot['themes'] = new Map();88 for (const t of th.rows) themes.set(t.id, { id: t.id, title: t.title, versions: [] });89 for (const v of ve.rows)90 themes.get(v.theme_id)?.versions.push({ version: v.version, minEngine: v.min_engine, sha256: v.sha256, bytes: Number(v.bytes), createdAt: new Date(v.created_at).toISOString() });91 const channels: Snapshot['channels'] = new Map();92 for (const r of ch.rows) channels.set(channelKey(r.theme_id, r.app, r.platform), { stable: r.stable_version, candidate: r.candidate_version, percent: r.candidate_percent });93 const apps: Snapshot['apps'] = new Map();94 for (const r of ap.rows) {95 const brandText = JSON.stringify(brandDocument(r.app, r.config));96 apps.set(r.app, { rev: Number(r.id), config: r.config, brandText, brandSha: sha256hex(brandText) });97 }98 return { revision: Number(rev.rows[0]?.value ?? 0), themes, channels, apps, icons: ic.rows, datasets, dataVersion };99 } catch (e) {100 await c.query('ROLLBACK').catch(() => {});101 throw e;102 } finally {103 c.release();104 }105}106107export type Endpoints = { tiles: string; terrain: string; geo: string; maps: string };108export type ManifestQuery = { app: string; platform: string; engine: string | null; bucket: number | null };109110/** Manifeste d'une application : fonction pure de l'instantané et de la requête. */111export function buildManifest(s: Snapshot, q: ManifestQuery, endpoints: Endpoints, sdk: { version: string } | null) {112 const app = s.apps.get(q.app);113 if (!app) return null;114 const themes: any[] = [];115 const unavailable: any[] = [];116 for (const id of app.config.themes) {117 const t = s.themes.get(id);118 if (!t) continue;119 const ch = s.channels.get(channelKey(id, q.app, q.platform)) ?? { stable: null, candidate: null, percent: 0 };120 const r = resolveTheme(id, t.versions, ch, q.engine, q.bucket);121 if (r.version === null) {122 unavailable.push({ id, reason: r.reason });123 continue;124 }125 const v = t.versions.find((x) => x.version === r.version)!;126 themes.push({127 id,128 title: t.title,129 version: v.version,130 styleVersion: `${v.version}.0.0`,131 minEngine: v.minEngine,132 channel: r.channel,133 ...(r.downgraded ? { compatibility: { target: r.target, served: v.version } } : {}),134 url: `${endpoints.maps}/v1/themes/${id}/${v.version}.json`,135 sha256: v.sha256,136 bytes: v.bytes,137 effectiveUrl: `${endpoints.maps}/v1/themes/${id}/${v.version}.json?app=${q.app}&brand=${app.rev}`,138 });139 }140 const defaultTheme = themes.some((t) => t.id === app.config.defaultTheme) ? app.config.defaultTheme : (themes[0]?.id ?? null);141 return {142 manifest: 1,143 app: q.app,144 platform: q.platform,145 engine: q.engine,146 bucket: q.bucket,147 revision: s.revision,148 endpoints,149 dataVersion: s.dataVersion,150 config: { rev: app.rev, defaultTheme, zoom: app.config.zoom, layers: app.config.layers, flags: app.config.flags },151 brand: { rev: app.rev, url: `${endpoints.maps}/v1/brands/${q.app}/${app.rev}.json`, sha256: app.brandSha },152 themes,153 unavailable,154 icons: { index: `${endpoints.maps}/v1/icons/index.json`, count: s.icons.length },155 sdk: sdk ? { web: { version: sdk.version, url: `${endpoints.maps}/sdk/${sdk.version}/` } } : null,156 attribution: '© OpenStreetMap, Gouvernement du Québec, RNCan',157 licences: `${endpoints.maps}/licences`,158 };159}160161/** Accès aux documents publiés, avec petit cache en mémoire (les versions sont immuables). */162export class Documents {163 private texts = new Map<string, string>();164 private effective = new Map<string, Promise<string>>();165 private pool: Pool;166 private schema: string;167 constructor(pool: Pool, schema: string = 'studio') {168 this.pool = pool;169 this.schema = schema;170 }171172 async themeText(id: string, version: number): Promise<string | null> {173 const k = `${id}@${version}`;174 const hit = this.texts.get(k);175 if (hit) return hit;176 const r = await this.pool.query(`SELECT doc_text FROM ${this.schema}.theme_version WHERE theme_id = $1 AND version = $2`, [id, version]);177 if (!r.rows[0]) return null;178 if (this.texts.size > 96) this.texts.delete(this.texts.keys().next().value!);179 this.texts.set(k, r.rows[0].doc_text);180 return r.rows[0].doc_text;181 }182183 async appRev(app: string, rev: number): Promise<AppConfig | null> {184 const r = await this.pool.query(`SELECT config FROM ${this.schema}.app_config_rev WHERE app = $1 AND id = $2`, [app, rev]);185 return r.rows[0]?.config ?? null;186 }187188 /** Thème + marque + couches coupées de l'application : le document que le SDK peut charger tel quel. */189 effectiveText(id: string, version: number, app: string, rev: number): Promise<string | null> {190 if (!(APPS as readonly string[]).includes(app)) return Promise.resolve(null);191 const k = `${id}@${version}|${app}@${rev}`;192 const hit = this.effective.get(k);193 if (hit) return hit;194 const p = (async () => {195 const [text, config] = await Promise.all([this.themeText(id, version), this.appRev(app, rev)]);196 if (!text || !config) return null;197 const r = await kmrValidate(JSON.parse(text), brandDocument(app, config), true);198 if (!r.ok) throw new Error(`marque ${app} (rév. ${rev}) incompatible avec ${id} v${version} : ${r.errors[0]?.path} — ${r.errors[0]?.message}`);199 return JSON.stringify(applyLayerSwitches(r.effective, config.layers));200 })();201 if (this.effective.size > 96) this.effective.delete(this.effective.keys().next().value!);202 this.effective.set(k, p);203 p.catch(() => this.effective.delete(k));204 return p;205 }206}207