const META_PREFIX = "meta:isp:"; export const LEGACY_POINT_LIMIT = 200; export const LOCAL_POINT_LIMIT = 2000; export function buildPointKey(isp, pointIndex) { return `${isp}:${pointIndex}`; } export function sanitizeIspName(value) { const normalized = String(value || "").toLowerCase(); if (!/^(isp[a-z0-9_]*|trend_[a-z0-9_]+)$/.test(normalized)) { throw new Error("Invalid trend table name."); } return normalized; } export function sanitizePointIndex(value) { const pointIndex = Number(value); if (!Number.isInteger(pointIndex) || pointIndex < 1 || pointIndex > LOCAL_POINT_LIMIT) { throw new Error(`Point index must be between 1 and ${LOCAL_POINT_LIMIT}.`); } return pointIndex; } export function parseTrendValue(rawValue, factor = 1) { if (rawValue === null || rawValue === undefined) { return { raw: null, numeric: null }; } const raw = String(rawValue).trim(); if (!raw) { return { raw: null, numeric: null }; } const normalized = raw.replace(",", "."); const numeric = Number(normalized); const safeFactor = Number.isFinite(Number(factor)) ? Number(factor) : 1; return { raw, numeric: Number.isFinite(numeric) ? numeric * safeFactor : null, }; } function buildValueColumns() { const columns = []; for (let index = 1; index <= LOCAL_POINT_LIMIT; index += 1) { columns.push('`Wert' + index + '` TEXT NULL'); } return columns.join(", "); } function hslToHex(hue, saturation, lightness) { const s = saturation / 100; const l = lightness / 100; const c = (1 - Math.abs(2 * l - 1)) * s; const x = c * (1 - Math.abs((hue / 60) % 2 - 1)); const m = l - c / 2; let red = 0; let green = 0; let blue = 0; if (hue < 60) { red = c; green = x; } else if (hue < 120) { red = x; green = c; } else if (hue < 180) { green = c; blue = x; } else if (hue < 240) { green = x; blue = c; } else if (hue < 300) { red = x; blue = c; } else { red = c; blue = x; } const toHex = (value) => Math.round((value + m) * 255).toString(16).padStart(2, "0"); return `#${toHex(red)}${toHex(green)}${toHex(blue)}`; } function parseHslColor(value) { const match = String(value || "").match(/^hsl\((\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)%\s+(\d+(?:\.\d+)?)%\)$/i); if (!match) { return null; } return { hue: Number(match[1]), saturation: Number(match[2]), lightness: Number(match[3]), }; } function createRandomPointColor(seed) { const hue = Math.round((seed * 47 + 17 + Math.random() * 28) % 360); const saturation = 72 + (seed % 4) * 4; const lightness = 45 + (seed % 3) * 4; return hslToHex(hue, saturation, lightness); } export function normalizeEngineeringUnit(value, kind = "analog") { const normalizedKind = kind === "digital" ? "digital" : "analog"; const raw = String(value ?? "").trim(); if (!raw) { return normalizedKind === "digital" ? "bool" : "\u00B0C"; } if (normalizedKind === "digital" && /^(?:bool|boolean)$/i.test(raw)) { return "bool"; } if (/^\?C$/i.test(raw) || /^\u00B0\s*C$/i.test(raw) || (/[^\x00-\x7F]/.test(raw) && /C/i.test(raw))) { return normalizedKind === "digital" ? "bool" : "\u00B0C"; } return raw; } function createDefaultPoint(index) { return { alias: `Wert${index}`, unit: "\u00B0C", factor: 1, kind: "analog", min: 0, max: 100, color: createRandomPointColor(index), }; } async function ensureWideTrendColumns(pool, tableName) { const [columns] = await pool.query( ` SELECT COLUMN_NAME AS columnName FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME LIKE 'Wert%' `, [tableName] ); const existing = new Set(columns.map((column) => column.columnName)); const missing = []; for (let index = 1; index <= LOCAL_POINT_LIMIT; index += 1) { const columnName = `Wert${index}`; if (!existing.has(columnName)) { missing.push(`ADD COLUMN \`${columnName}\` TEXT NULL`); } } for (let index = 0; index < missing.length; index += 50) { await pool.query(`ALTER TABLE \`${tableName}\` ${missing.slice(index, index + 50).join(", ")}`); } } export async function createLegacyWideTrendTable(pool, tableName) { const safeTable = sanitizeIspName(tableName); const sql = ` CREATE TABLE IF NOT EXISTS \`${safeTable}\` ( \`id\` INT(11) NOT NULL AUTO_INCREMENT, \`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, \`userlevel\` INT(1) NOT NULL, ${buildValueColumns()}, PRIMARY KEY (\`id\`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `; await pool.query(sql); await ensureWideTrendColumns(pool, safeTable); return safeTable; } export async function createTrendTable(pool, tableName) { const safeTable = sanitizeIspName(tableName); await pool.query(` CREATE TABLE IF NOT EXISTS \`${safeTable}\` ( \`id\` BIGINT NOT NULL AUTO_INCREMENT, \`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, \`userlevel\` INT(1) NOT NULL DEFAULT 0, \`source_id\` VARCHAR(191) NOT NULL, \`point_index\` INT NOT NULL, \`alias\` VARCHAR(255) NOT NULL, \`value\` TEXT NULL, PRIMARY KEY (\`id\`), KEY \`idx_${safeTable}_datum\` (\`datum\`), KEY \`idx_${safeTable}_point_datum\` (\`point_index\`, \`datum\`), KEY \`idx_${safeTable}_source_point\` (\`source_id\`, \`point_index\`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `); return safeTable; } async function loadSourcePointSeeds(pool, tableName) { const safeTable = sanitizeIspName(tableName); try { const [rows] = await pool.query( ` SELECT point_index AS pointIndex, alias, name, unit, kind FROM \`source_datapoint_registry\` WHERE table_name = ? ORDER BY point_index ASC, updated_at ASC `, [safeTable] ); return rows.map((row) => ({ pointIndex: sanitizePointIndex(row.pointIndex), alias: String(row.alias || "").trim(), name: String(row.name || "").trim(), unit: String(row.unit || "").trim(), kind: row.kind === "digital" ? "digital" : "analog", })); } catch (error) { if (String(error?.message || "").includes("doesn't exist")) { return []; } throw error; } } async function hasSourceRegistryEntry(pool, tableName) { const safeTable = sanitizeIspName(tableName); try { const [rows] = await pool.query( "SELECT 1 FROM `source_registry` WHERE table_name = ? LIMIT 1", [safeTable] ); return rows.length > 0; } catch (error) { if (String(error?.message || "").includes("doesn't exist")) { return false; } throw error; } } async function describeTrendTable(pool, dbName, tableName) { const safeTable = sanitizeIspName(tableName); const usesExplicitSchema = Boolean(dbName); const [columns] = await pool.query( ` SELECT COLUMN_NAME AS columnName FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ${usesExplicitSchema ? "?" : "DATABASE()"} AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION `, usesExplicitSchema ? [dbName, safeTable] : [safeTable] ); const columnNames = columns.map((column) => column.columnName); const lowerNames = new Set(columnNames.map((name) => String(name).toLowerCase())); const widePointCount = columnNames.filter((name) => /^Wert\d+$/i.test(name)).length; if (widePointCount > 0) { const [rows] = await pool.query(`SELECT COUNT(*) AS rowCount, MAX(datum) AS latestTimestamp FROM \`${safeTable}\``); return { tableName: safeTable, storage: "wide", pointCount: widePointCount, rowCount: Number(rows[0]?.rowCount || 0), latestTimestamp: rows[0]?.latestTimestamp || null, }; } if (lowerNames.has("datum") && lowerNames.has("point_index") && lowerNames.has("value")) { const sourceSeeds = await loadSourcePointSeeds(pool, safeTable); const sourceBacked = await hasSourceRegistryEntry(pool, safeTable); const [rows] = await pool.query( ` SELECT COUNT(*) AS rowCount, MAX(datum) AS latestTimestamp, COALESCE(MAX(point_index), 0) AS pointCount FROM \`${safeTable}\` ` ); const measuredPointCount = Number(rows[0]?.pointCount || 0); const pointCount = sourceSeeds.length ? sourceSeeds.length : measuredPointCount; return { tableName: safeTable, storage: "narrow", pointCount: pointCount || (sourceBacked ? 0 : (safeTable.startsWith("trend_") ? LOCAL_POINT_LIMIT : LEGACY_POINT_LIMIT)), rowCount: Number(rows[0]?.rowCount || 0), latestTimestamp: rows[0]?.latestTimestamp || null, }; } return null; } export async function resolveTrendTablePointCount(pool, dbName, tableName) { const safeTable = sanitizeIspName(tableName); const info = await describeTrendTable(pool, dbName, safeTable); if (!info) { return safeTable.startsWith("trend_") ? LOCAL_POINT_LIMIT : LEGACY_POINT_LIMIT; } return Number(info.pointCount || 0) || (safeTable.startsWith("trend_") ? LOCAL_POINT_LIMIT : LEGACY_POINT_LIMIT); } export async function getAvailableIsps(pool, dbName) { const [tables] = await pool.query( ` SELECT t.TABLE_NAME AS tableName FROM information_schema.TABLES t WHERE t.TABLE_SCHEMA = ? AND (t.TABLE_NAME LIKE 'isp%' OR t.TABLE_NAME LIKE 'trend_%') ORDER BY t.TABLE_NAME `, [dbName] ); const described = await Promise.all(tables.map((table) => describeTrendTable(pool, dbName, table.tableName))); return described.filter(Boolean); } export function createDefaultMetadata(isp, pointCount = LEGACY_POINT_LIMIT) { const points = {}; const pointOrder = []; for (let index = 1; index <= pointCount; index += 1) { const key = String(index); points[key] = createDefaultPoint(index); pointOrder.push(key); } return { isp, displayName: isp.toUpperCase(), description: "", points, pointOrder, }; } export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_POINT_LIMIT) { const safeIsp = sanitizeIspName(isp); const key = `${META_PREFIX}${safeIsp}`; const sourceSeeds = await loadSourcePointSeeds(pool, safeIsp); const seedMap = new Map(sourceSeeds.map((seed) => [String(seed.pointIndex), seed])); const pointOrder = sourceSeeds.length ? sourceSeeds.map((seed) => String(seed.pointIndex)) : Array.from({ length: pointCount }, (_value, index) => String(index + 1)); const existing = await redis.get(key); if (existing) { const parsed = JSON.parse(existing); let changed = false; if (!parsed.points) { parsed.points = {}; changed = true; } if (!Array.isArray(parsed.pointOrder)) { parsed.pointOrder = []; changed = true; } if (JSON.stringify(parsed.pointOrder) !== JSON.stringify(pointOrder)) { parsed.pointOrder = pointOrder; changed = true; } pointOrder.forEach((pointKey) => { const index = Number(pointKey); const defaultPoint = createDefaultPoint(index); const sourceSeed = seedMap.get(pointKey); const initialAlias = sourceSeed?.alias || sourceSeed?.name || defaultPoint.alias; if (!parsed.points[pointKey]) { parsed.points[pointKey] = { ...defaultPoint, alias: initialAlias, unit: normalizeEngineeringUnit(sourceSeed?.unit || defaultPoint.unit, sourceSeed?.kind || defaultPoint.kind), kind: sourceSeed?.kind || defaultPoint.kind, }; changed = true; return; } const point = parsed.points[pointKey]; if (!point.alias || point.alias === defaultPoint.alias) { const nextAlias = initialAlias || defaultPoint.alias; if (point.alias !== nextAlias) { point.alias = nextAlias; changed = true; } } if (sourceSeed?.kind && !point.kind) { point.kind = sourceSeed.kind; changed = true; } const normalizedUnit = normalizeEngineeringUnit(point.unit, point.kind || sourceSeed?.kind || defaultPoint.kind); if (normalizedUnit !== point.unit) { point.unit = normalizedUnit; changed = true; } if ((!point.unit || point.unit === normalizeEngineeringUnit(defaultPoint.unit, defaultPoint.kind)) && sourceSeed?.unit) { const seededUnit = normalizeEngineeringUnit(sourceSeed.unit, sourceSeed.kind || point.kind || defaultPoint.kind); if (point.unit !== seededUnit) { point.unit = seededUnit; changed = true; } } if (!point.kind) { point.kind = sourceSeed?.kind || defaultPoint.kind; changed = true; } if (!Number.isFinite(Number(point.factor))) { point.factor = defaultPoint.factor; changed = true; } if (!Number.isFinite(Number(point.min))) { point.min = defaultPoint.min; changed = true; } if (!Number.isFinite(Number(point.max))) { point.max = defaultPoint.max; changed = true; } const parsedHslColor = parseHslColor(point.color); if (parsedHslColor) { point.color = hslToHex(parsedHslColor.hue, parsedHslColor.saturation, parsedHslColor.lightness); changed = true; } if (!point.color) { point.color = defaultPoint.color; changed = true; } }); if (changed) { await redis.set(key, JSON.stringify(parsed)); } return parsed; } const metadata = createDefaultMetadata(safeIsp, pointCount); metadata.pointOrder = pointOrder; pointOrder.forEach((pointKey) => { const sourceSeed = seedMap.get(pointKey); if (!sourceSeed) { return; } metadata.points[pointKey] = { ...metadata.points[pointKey], alias: sourceSeed.alias || sourceSeed.name || metadata.points[pointKey].alias, unit: normalizeEngineeringUnit(sourceSeed.unit || metadata.points[pointKey].unit, sourceSeed.kind || metadata.points[pointKey].kind), kind: sourceSeed.kind || metadata.points[pointKey].kind, }; }); await redis.set(key, JSON.stringify(metadata)); return metadata; } export async function updateIspMetadata(pool, redis, isp, updater, pointCount = LEGACY_POINT_LIMIT) { const metadata = await ensureIspMetadata(pool, redis, isp, pointCount); const updated = updater(JSON.parse(JSON.stringify(metadata))); await redis.set(`${META_PREFIX}${sanitizeIspName(isp)}`, JSON.stringify(updated)); return updated; } export async function getPointDescriptors(pool, redis, points) { const grouped = new Map(); points.forEach((point) => { const isp = sanitizeIspName(point.isp); const pointIndex = sanitizePointIndex(point.pointIndex); if (!grouped.has(isp)) { grouped.set(isp, []); } grouped.get(isp).push(pointIndex); }); const descriptors = []; for (const [isp, pointIndexes] of grouped.entries()) { const pointCount = await resolveTrendTablePointCount(pool, null, isp); const metadata = await ensureIspMetadata(pool, redis, isp, pointCount); pointIndexes.forEach((pointIndex) => { const pointMeta = metadata.points[String(pointIndex)] || createDefaultPoint(pointIndex); descriptors.push({ isp, pointIndex, key: buildPointKey(isp, pointIndex), displayName: metadata.displayName, alias: pointMeta.alias, unit: normalizeEngineeringUnit(pointMeta.unit, pointMeta.kind), factor: pointMeta.factor, kind: pointMeta.kind, min: pointMeta.min, max: pointMeta.max, color: pointMeta.color || "", }); }); } return descriptors; } export async function fetchTrendSeries(pool, redis, points, range) { const descriptors = await getPointDescriptors(pool, redis, points); const grouped = descriptors.reduce((accumulator, descriptor) => { if (!accumulator.has(descriptor.isp)) { accumulator.set(descriptor.isp, []); } accumulator.get(descriptor.isp).push(descriptor); return accumulator; }, new Map()); const mergedRows = new Map(); for (const [isp, pointDescriptors] of grouped.entries()) { const tableInfo = await describeTrendTable(pool, null, isp); if (!tableInfo) { continue; } if (tableInfo.storage === "narrow") { const placeholders = pointDescriptors.map(() => "?").join(", "); const limit = Math.max(pointDescriptors.length, (range.maxRows || 4000) * Math.max(1, pointDescriptors.length)); const [rows] = await pool.query( ` SELECT datum, point_index, value FROM \`${isp}\` WHERE point_index IN (${placeholders}) AND datum BETWEEN ? AND ? ORDER BY datum DESC, id DESC LIMIT ? `, [...pointDescriptors.map((descriptor) => descriptor.pointIndex), range.from, range.to, limit] ); rows.reverse().forEach((row) => { const timestamp = new Date(row.datum).toISOString(); if (!mergedRows.has(timestamp)) { mergedRows.set(timestamp, { timestamp }); } const target = mergedRows.get(timestamp); const descriptor = pointDescriptors.find((item) => item.pointIndex === Number(row.point_index)); if (!descriptor) { return; } const parsed = parseTrendValue(row.value, descriptor.factor); target[descriptor.key] = parsed.numeric; target[`${descriptor.key}:raw`] = parsed.raw; }); continue; } const columns = pointDescriptors .map((descriptor) => `\`Wert${descriptor.pointIndex}\``) .join(", "); const limit = range.maxRows || 4000; const [rows] = await pool.query( `SELECT datum, ${columns} FROM \`${isp}\` WHERE datum BETWEEN ? AND ? ORDER BY datum DESC LIMIT ?`, [range.from, range.to, limit] ); rows.reverse().forEach((row) => { const timestamp = new Date(row.datum).toISOString(); if (!mergedRows.has(timestamp)) { mergedRows.set(timestamp, { timestamp }); } const target = mergedRows.get(timestamp); pointDescriptors.forEach((descriptor) => { const rawValue = row[`Wert${descriptor.pointIndex}`]; const parsed = parseTrendValue(rawValue, descriptor.factor); target[descriptor.key] = parsed.numeric; target[`${descriptor.key}:raw`] = parsed.raw; }); }); } return { series: descriptors, rows: [...mergedRows.values()].sort((left, right) => left.timestamp.localeCompare(right.timestamp)), }; } export async function fetchLatestValues(pool, redis, points) { const descriptors = await getPointDescriptors(pool, redis, points); const grouped = descriptors.reduce((accumulator, descriptor) => { if (!accumulator.has(descriptor.isp)) { accumulator.set(descriptor.isp, []); } accumulator.get(descriptor.isp).push(descriptor); return accumulator; }, new Map()); const values = []; for (const [isp, pointDescriptors] of grouped.entries()) { const tableInfo = await describeTrendTable(pool, null, isp); if (!tableInfo) { pointDescriptors.forEach((descriptor) => { values.push({ ...descriptor, timestamp: null, raw: null, value: null, }); }); continue; } if (tableInfo.storage === "narrow") { const placeholders = pointDescriptors.map(() => "?").join(", "); const [rows] = await pool.query( ` SELECT point_index, datum, value FROM ( SELECT point_index, datum, value, ROW_NUMBER() OVER (PARTITION BY point_index ORDER BY datum DESC, id DESC) AS point_rank FROM \`${isp}\` WHERE point_index IN (${placeholders}) ) ranked WHERE point_rank = 1 `, pointDescriptors.map((descriptor) => descriptor.pointIndex) ); const latestByPoint = new Map(rows.map((row) => [Number(row.point_index), row])); pointDescriptors.forEach((descriptor) => { const row = latestByPoint.get(descriptor.pointIndex); const parsed = parseTrendValue(row?.value, descriptor.factor); values.push({ ...descriptor, timestamp: row?.datum ? new Date(row.datum).toISOString() : null, raw: parsed.raw, value: parsed.numeric, }); }); continue; } const columns = pointDescriptors .map((descriptor) => `\`Wert${descriptor.pointIndex}\``) .join(", "); const [rows] = await pool.query(`SELECT datum, ${columns} FROM \`${isp}\` ORDER BY datum DESC LIMIT 1`); const row = rows[0]; pointDescriptors.forEach((descriptor) => { const parsed = parseTrendValue(row?.[`Wert${descriptor.pointIndex}`], descriptor.factor); values.push({ ...descriptor, timestamp: row?.datum ? new Date(row.datum).toISOString() : null, raw: parsed.raw, value: parsed.numeric, }); }); } return values; } export function normalizeRange(input = {}) { const presetDays = Number(input.presetDays || 1); const maxRows = Number(input.maxRows || 4000); const now = new Date(); const to = input.to ? new Date(input.to) : now; const from = input.from ? new Date(input.from) : new Date(now.getTime() - presetDays * 24 * 60 * 60 * 1000); return { from, to, maxRows: Number.isFinite(maxRows) ? Math.max(100, Math.min(maxRows, 10000)) : 4000, }; }