A modern and elegant dashboard for network traffic visualization and analysis.
feat: Introduce a backend health monitoring tab with historical status visualization, API, and country traffic connection counting.
luoleiaced57c41f2f
diff --git a/CHANGELOG.en.md b/CHANGELOG.en.mdindex d9ee342..279c880 100644--- a/CHANGELOG.en.md+++ b/CHANGELOG.en.md@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [1.3.3] - 2026-02-24++### Added++- **Backend Health Monitoring Tab** 🏥+ - New dedicated Health tab for historical health status visualization across all configured backends+ - Per-backend time-series area chart: latency curve for Direct mode, online/offline status for Agent mode+ - Unhealthy and unknown periods are shaded red/amber; interior data gaps (between first and last recorded point) are automatically treated as downtime, while leading/trailing gaps remain blank+ - Multi-range support (1h / 6h / 12h / 24h / 7d / 30d) with axis label format auto-switching (time-only / month+time / date-only) based on span+ - Six summary stat cards at the top: overall uptime %, healthy backends, unhealthy backends, total backends, avg latency, bucket granularity — visual style aligned with the Overview tab+ - Health check interval defaults to 30 seconds (min 5 s), configurable via `BACKEND_HEALTH_CHECK_INTERVAL_MS`+ - New `backend_health_logs` table keyed on `(backend_id, minute)`; multiple checks within the same minute are UPSERT-deduplicated; logs are automatically pruned on a 30-day retention schedule alongside hourly stats+ - Health history API supports filtering by `backendId`; data is grouped by backend and enriched with names in the service layer, keeping the controller as a thin routing layer+- **Country traffic connection counting**+ - Country traffic statistics now include a connections dimension; the Country Traffic panel supports sort-by-connections+ - Agent report payloads include an explicit `connections` field with legacy-compatible fallback+- **Time range preset expansion**+ - `5m` and `30m` quick presets are now available in production environments++### Changed++- **Traffic collection connection counting aligned**+ - Both Agent and Direct modes now count connections once per flush interval, eliminating duplicate increments+ - Removed the connection count accumulation side-effect from the legacy `requeueFront` retry path+- **Case normalization function compatibility**+ - `tr`-based character class conversions replaced with explicit character lists for consistent cross-platform behavior+## [1.3.2] - 2026-02-22### Addeddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex c365d0a..8a54f29 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,33 @@## [未发布]+## [1.3.3] - 2026-02-24++### 新增++- **后端健康监控面板(Health Tab)** 🏥+ - 新增独立 Health 标签页,支持对所有已配置后端进行历史健康状态可视化+ - 每个后端展示一张时序面积图:Direct 模式显示延迟曲线,Agent 模式显示在线/离线状态+ - 异常区间(unhealthy / unknown)以红/橙色背景着色;首末数据点之间的数据缺口自动标记为故障,首尾 leading/trailing 空白保持留白+ - 支持多时间范围(1h / 6h / 12h / 24h / 7d / 30d),X 轴标签随时间跨度自动切换格式(纯时间 / 月日时间 / 纯日期)+ - 顶部 6 张汇总卡片:整体可用率、健康节点数、异常节点数、节点总数、平均延迟、统计粒度,与 Overview 视觉风格统一+ - 健康检查间隔默认 30 秒,最小 5 秒,可通过 `BACKEND_HEALTH_CHECK_INTERVAL_MS` 环境变量自定义+ - 新增 `backend_health_logs` 表,以 `(backend_id, minute)` 为主键,同一分钟内多次检查 UPSERT 去重;历史数据随 hourly stats 同步按 30 天保留期自动清理+ - 健康 history API 支持按 `backendId` 过滤,数据按后端分组并附带名称,Controller 仅负责参数解析+- **国家流量连接数计数**+ - 国家流量统计新增连接数维度,Country Traffic 面板现可按连接数排序+ - Agent 上报数据新增显式 `connections` 字段,带旧版兼容 fallback+- **时间范围预设扩展**+ - `5m` 和 `30m` 快捷预设在生产环境下恢复可用++### 变更++- **流量采集连接数计算对齐**+ - Agent 模式与 Direct 模式的连接数均改为每次 flush 周期计算一次,避免重复计数+ - 移除旧的 `requeueFront` 逻辑中的连接数累加副作用+- **大小写归一化函数兼容性**+ - 字符类转换函数中的 `tr` 字符集改为显式字符列表,提升跨平台一致性+## [1.3.2] - 2026-02-22### 新增diff --git a/apps/collector/src/database/schema.ts b/apps/collector/src/database/schema.tsindex 0517946..1efc36e 100644--- a/apps/collector/src/database/schema.ts+++ b/apps/collector/src/database/schema.ts@@ -503,6 +503,7 @@ export const INDEXES = [// Backend health log indexes`CREATE INDEX IF NOT EXISTS idx_backend_health_logs_backend_minute ON backend_health_logs(backend_id, minute);`,+ `CREATE INDEX IF NOT EXISTS idx_backend_health_logs_minute ON backend_health_logs(minute);`,// Surge policy cache indexes`CREATE INDEX IF NOT EXISTS idx_surge_policy_backend ON surge_policy_cache(backend_id);`,diff --git a/apps/collector/src/modules/backend/backend.controller.ts b/apps/collector/src/modules/backend/backend.controller.tsindex 946765f..9d18cf3 100644--- a/apps/collector/src/modules/backend/backend.controller.ts+++ b/apps/collector/src/modules/backend/backend.controller.ts@@ -186,43 +186,21 @@ const backendController: FastifyPluginAsync = async (fastify: FastifyInstance):// Get health history for all (or a specific) backendfastify.get<{ Querystring: { from?: string; to?: string; backendId?: string } }>('/health/history',- async (request) => {+ async (request, reply) => {const { from, to, backendId } = request.query;- // Default to last 24 hours if not providedconst toISO = (to ?? new Date().toISOString()).slice(0, 16);const fromISO = (from ?? new Date(Date.now() - 24 * 3600_000).toISOString()).slice(0, 16);- const parsedBackendId = backendId ? parseInt(backendId, 10) : undefined;- const rows = service.getHealthHistory(fromISO, toISO, parsedBackendId);-- // Group by backend and enrich with backend name- const backends = service.getAllBackends();- const backendMap = new Map(backends.map((b) => [b.id, b.name]));-- const grouped = new Map<number, {- backendId: number;- backendName: string;- points: Array<{ time: string; status: string; latency_ms: number | null; message: string | null }>;- }>();-- for (const row of rows) {- if (!grouped.has(row.backend_id)) {- grouped.set(row.backend_id, {- backendId: row.backend_id,- backendName: backendMap.get(row.backend_id) ?? `Backend ${row.backend_id}`,- points: [],- });+ let parsedBackendId: number | undefined;+ if (backendId !== undefined) {+ parsedBackendId = parseInt(backendId, 10);+ if (Number.isNaN(parsedBackendId)) {+ return reply.status(400).send({ error: 'Invalid backendId' });}- grouped.get(row.backend_id)!.points.push({- time: row.minute,- status: row.status,- latency_ms: row.latency_ms,- message: row.message,- });}- return Array.from(grouped.values());+ return service.getHealthHistory(fromISO, toISO, parsedBackendId);},);diff --git a/apps/collector/src/modules/backend/backend.service.ts b/apps/collector/src/modules/backend/backend.service.tsindex e766a3b..a802fb7 100644--- a/apps/collector/src/modules/backend/backend.service.ts+++ b/apps/collector/src/modules/backend/backend.service.ts@@ -12,6 +12,7 @@ import type {UpdateBackendInput,BackendResponse,BackendHealthInfo,+ BackendHealthHistory,TestConnectionInput,TestConnectionResult,CreateBackendResult,@@ -22,7 +23,6 @@ import { loadClickHouseConfig, runClickHouseQuery } from '../clickhouse/clickhouimport type { ClickHouseConfig } from '../clickhouse/clickhouse.config.js';import type { AuthService } from '../auth/auth.service.js';-import type { HealthLogRow } from '../../database/repositories/health.repository.js';/*** Mask URL for showcase mode - hides host, port, credentials@@ -167,12 +167,33 @@ export class BackendService {/*** Get health history for all backends (or a single one) over the given UTC ISO range.+ * Returns data grouped by backend and enriched with backend names.*/- getHealthHistory(fromISO: string, toISO: string, backendId?: number): HealthLogRow[] {- if (backendId !== undefined) {- return this.db.repos.health.getHealthHistory(backendId, fromISO, toISO);+ getHealthHistory(fromISO: string, toISO: string, backendId?: number): BackendHealthHistory[] {+ const rows = backendId !== undefined+ ? this.db.repos.health.getHealthHistory(backendId, fromISO, toISO)+ : this.db.repos.health.getHealthHistoryAll(fromISO, toISO);++ const backendMap = new Map(this.getAllBackends().map((b) => [b.id, b.name]));+ const grouped = new Map<number, BackendHealthHistory>();++ for (const row of rows) {+ if (!grouped.has(row.backend_id)) {+ grouped.set(row.backend_id, {+ backendId: row.backend_id,+ backendName: backendMap.get(row.backend_id) ?? `Backend ${row.backend_id}`,+ points: [],+ });+ }+ grouped.get(row.backend_id)!.points.push({+ time: row.minute,+ status: row.status,+ latency_ms: row.latency_ms,+ message: row.message,+ });}- return this.db.repos.health.getHealthHistoryAll(fromISO, toISO);++ return Array.from(grouped.values());}/**diff --git a/apps/collector/src/modules/backend/backend.types.ts b/apps/collector/src/modules/backend/backend.types.tsindex 5adc53e..7f00e0f 100644--- a/apps/collector/src/modules/backend/backend.types.ts+++ b/apps/collector/src/modules/backend/backend.types.ts@@ -89,3 +89,16 @@ export interface RotateAgentTokenResult {message: string;agentToken: string;}++export interface BackendHealthPoint {+ time: string;+ status: 'healthy' | 'unhealthy' | 'unknown';+ latency_ms: number | null;+ message: string | null;+}++export interface BackendHealthHistory {+ backendId: number;+ backendName: string;+ points: BackendHealthPoint[];+}diff --git a/apps/collector/src/modules/cleanup/cleanup.service.ts b/apps/collector/src/modules/cleanup/cleanup.service.tsindex 14f562e..be33500 100644--- a/apps/collector/src/modules/cleanup/cleanup.service.ts+++ b/apps/collector/src/modules/cleanup/cleanup.service.ts@@ -90,10 +90,13 @@ export class CleanupService {try {// Clean up old connection logsconst logsDeleted = this.cleanupConnectionLogs();-+// Clean up old hourly statsconst hourlyDeleted = this.cleanupHourlyStats();+ // Clean up old health logs (same retention as hourly stats)+ this.cleanupHealthLogs();+// Vacuum database to reclaim space (only if significant data deleted)const totalDeleted = logsDeleted + hourlyDeleted;if (totalDeleted > 10000) {@@ -122,6 +125,14 @@ export class CleanupService {return this.db.deleteOldMinuteStats(cutoff);}+ /**+ * Clean up old health logs (retention matches hourly stats)+ */+ private cleanupHealthLogs(): void {+ const config = this.getConfig();+ this.db.repos.health.pruneOldLogs(config.hourlyStatsDays);+ }+/*** Clean up old hourly stats*/diff --git a/apps/web/components/features/health/backend-health-chart.tsx b/apps/web/components/features/health/backend-health-chart.tsxindex 3c20ec2..0b48d2d 100644--- a/apps/web/components/features/health/backend-health-chart.tsx+++ b/apps/web/components/features/health/backend-health-chart.tsx@@ -11,9 +11,9 @@ import {CartesianGrid,ReferenceArea,} from "recharts";+import type { TooltipProps } from "recharts";import { Activity, Clock, Loader2 } from "lucide-react";import { useTranslations } from "next-intl";-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { cn } from "@/lib/utils";import type { BackendHealthHistory, BackendHealthPoint } from "@/lib/api";@@ -79,9 +79,6 @@ function buildSlots(while (cursor <= to) {const bucketStart = cursor.toISOString().slice(0, 16);- const bucketEnd = new Date(cursor.getTime() + bucketMinutes * 60_000)- .toISOString()- .slice(0, 16);// Collect all raw points that fall within this bucketconst bucketPoints: BackendHealthPoint[] = [];@@ -136,7 +133,6 @@ function buildSlots(}cursor.setMinutes(cursor.getMinutes() + bucketMinutes);- void bucketEnd; // suppress unused-var}return slots;@@ -274,9 +270,9 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({// ── Tooltip ────────────────────────────────────────────────────────────────const CustomTooltip = React.useCallback(- ({ active, payload }: any) => {+ ({ active, payload }: TooltipProps<number, string>) => {if (!active || !payload?.length) return null;- const slot: Slot = payload[0].payload;+ const slot = payload[0].payload as Slot;// Parse the stored ISO minute string as UTC → local, then format like Overviewconst slotDate = new Date(@@ -350,14 +346,14 @@ export const BackendHealthChart = React.memo(function BackendHealthChart({// ── Render ─────────────────────────────────────────────────────────────────return (- <div className="space-y-1">- {/* Title row — same pattern as TrafficTrendChart */}- <div className="flex items-center justify-between flex-wrap gap-2">- <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2">- <Activity className="w-4 h-4" />+ <div className="space-y-2">+ {/* Title row */}+ <div className="flex items-center gap-2">+ <Activity className="w-4 h-4 text-muted-foreground shrink-0" />+ <p className="text-sm font-semibold text-muted-foreground uppercase tracking-wider truncate">{history.backendName}- <span className={cn("inline-flex w-2 h-2 rounded-full shrink-0", statusDotClass)} />- </CardTitle>+ </p>+ <span className={cn("inline-flex w-2 h-2 rounded-full shrink-0", statusDotClass)} /></div>{/* Stats row — desktop inline / mobile cards */}diff --git a/apps/web/components/features/health/index.tsx b/apps/web/components/features/health/index.tsxindex 2bbb98a..04df8fb 100644--- a/apps/web/components/features/health/index.tsx+++ b/apps/web/components/features/health/index.tsx@@ -205,7 +205,7 @@ export function HealthContent({ timeRange }: HealthContentProps) {<div className="space-y-4">{data.map((backend) => (<Card key={backend.backendId}>- <CardContent className="px-5 pt-4 pb-3">+ <CardContent className="px-4 pt-3 pb-2"><BackendHealthCharthistory={backend}from={from}diff --git a/package.json b/package.jsonindex 8ae83bf..63d1ef1 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "neko-master",- "version": "1.3.2",+ "version": "1.3.3","description": "Modern traffic analytics for edge gateways","private": true,"workspaces": [