From 71c1f7633de39d528ef4473a6940c03803eee882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=98=89=E4=BC=9F?= <8473136@qq.com> Date: Fri, 20 Mar 2026 17:39:29 +0800 Subject: [PATCH] :recycle: Delay monitoring Code refactoring. --- internal/application/monitoring/metrics.go | 184 +++++++++++ internal/application/monitoring/monitor.go | 76 ++--- internal/application/monitoring/service.go | 111 ++----- .../persistence/server_repository.go | 7 +- internal/interfaces/http/server_handler.go | 218 +++++++++++++ site/src/components/LatencyChart.tsx | 266 ++++++++++++++++ site/src/components/ProbeHistory.tsx | 290 ++++++++++++++++++ site/src/locales/en.json | 16 +- site/src/locales/zh.json | 16 +- .../ServerDetail/ServerDetailPage.view.tsx | 40 ++- site/src/pages/Servers/useServers.ts | 24 +- 11 files changed, 1081 insertions(+), 167 deletions(-) create mode 100644 internal/application/monitoring/metrics.go create mode 100644 internal/interfaces/http/server_handler.go create mode 100644 site/src/components/LatencyChart.tsx create mode 100644 site/src/components/ProbeHistory.tsx diff --git a/internal/application/monitoring/metrics.go b/internal/application/monitoring/metrics.go new file mode 100644 index 0000000..b1d7924 --- /dev/null +++ b/internal/application/monitoring/metrics.go @@ -0,0 +1,184 @@ +package monitoring + +import ( + "fmt" + "sync" + "time" + + "github.com/pocketbase/dbx" + "github.com/pocketbase/pocketbase/core" +) + +const MetricKeyFrpsDelay = "frps_delay" + +// MetricsService handles writing latency data to fh_metrics_targets and fh_metrics_raw. +type MetricsService struct { + app core.App + + // targetCache maps serverID -> fh_metrics_targets record ID + targetCache map[string]string + targetCacheLock sync.RWMutex +} + +// NewMetricsService creates a new MetricsService. +func NewMetricsService(app core.App) *MetricsService { + return &MetricsService{ + app: app, + targetCache: make(map[string]string), + } +} + +// RecordServerLatency records a latency measurement for a server. +// It automatically finds or creates the corresponding fh_metrics_targets record. +// Negative latency (unreachable host) is skipped. +func (s *MetricsService) RecordServerLatency(serverID string, latencyMs int64) error { + if latencyMs < 0 { + return nil + } + + targetID, err := s.getOrCreateServerTarget(serverID) + if err != nil { + return fmt.Errorf("get/create metrics target: %w", err) + } + + return s.recordMetric(targetID, MetricKeyFrpsDelay, float64(latencyMs)) +} + +// getOrCreateServerTarget returns the fh_metrics_targets record ID for a server, +// creating one if it does not exist. Results are cached in memory. +func (s *MetricsService) getOrCreateServerTarget(serverID string) (string, error) { + s.targetCacheLock.RLock() + if id, ok := s.targetCache[serverID]; ok { + s.targetCacheLock.RUnlock() + return id, nil + } + s.targetCacheLock.RUnlock() + + // Acquire write lock for the entire find-or-create to prevent duplicate records + // when multiple goroutines encounter a cache miss simultaneously. + s.targetCacheLock.Lock() + defer s.targetCacheLock.Unlock() + + // Re-check under write lock (another goroutine may have just created it). + if id, ok := s.targetCache[serverID]; ok { + return id, nil + } + + records, err := s.app.FindRecordsByFilter( + "fh_metrics_targets", + "serverId = {:serverId} && proxyId = ''", + "", + 1, + 0, + map[string]any{"serverId": serverID}, + ) + if err != nil { + return "", fmt.Errorf("query metrics target: %w", err) + } + + var targetID string + if len(records) > 0 { + targetID = records[0].Id + } else { + collection, err := s.app.FindCollectionByNameOrId("fh_metrics_targets") + if err != nil { + return "", fmt.Errorf("find collection fh_metrics_targets: %w", err) + } + record := core.NewRecord(collection) + record.Set("serverId", serverID) + if err := s.app.Save(record); err != nil { + return "", fmt.Errorf("save metrics target: %w", err) + } + targetID = record.Id + } + + s.targetCache[serverID] = targetID + return targetID, nil +} + +// GetLatestLatencyBatch returns the most recent latency for every server in one SQL query. +// The returned map key is the server ID. +func (s *MetricsService) GetLatestLatencyBatch() (map[string]*NetworkStatus, error) { + type row struct { + ServerID string `db:"serverId"` + Val float64 `db:"val"` + T string `db:"t"` + } + + var rows []row + err := s.app.DB(). + NewQuery(` + SELECT t.serverId, r.val, r.t + FROM fh_metrics_raw r + INNER JOIN fh_metrics_targets t ON r.target_id = t.id + WHERE r.metric_key = {:key} + AND r.t = ( + SELECT MAX(r2.t) FROM fh_metrics_raw r2 + WHERE r2.target_id = r.target_id AND r2.metric_key = {:key} + ) + `). + Bind(dbx.Params{"key": MetricKeyFrpsDelay}). + All(&rows) + if err != nil { + return nil, err + } + + result := make(map[string]*NetworkStatus, len(rows)) + for _, row := range rows { + latency := int64(row.Val) + t, _ := time.Parse("2006-01-02 15:04:05.000Z", row.T) + result[row.ServerID] = &NetworkStatus{ + Latency: latency, + Reachable: latency >= 0, + LastCheckTime: t, + } + } + return result, nil +} + +// GetLatestServerLatency returns the most recent latency measurement for a server. +// Returns nil if no data has been recorded yet. +func (s *MetricsService) GetLatestServerLatency(serverID string) (*NetworkStatus, error) { + records, err := s.app.FindRecordsByFilter( + "fh_metrics_raw", + "target_id.serverId = {:serverId} && metric_key = {:key}", + "-t", + 1, + 0, + map[string]any{"serverId": serverID, "key": MetricKeyFrpsDelay}, + ) + if err != nil { + return nil, fmt.Errorf("query latest latency: %w", err) + } + if len(records) == 0 { + return nil, nil + } + + r := records[0] + latency := int64(r.GetFloat("val")) + return &NetworkStatus{ + Latency: latency, + Reachable: latency >= 0, + LastCheckTime: r.GetDateTime("t").Time(), + }, nil +} + +// recordMetric writes a single data point to fh_metrics_raw. +func (s *MetricsService) recordMetric(targetID, metricKey string, value float64) error { + collection, err := s.app.FindCollectionByNameOrId("fh_metrics_raw") + if err != nil { + return fmt.Errorf("find collection fh_metrics_raw: %w", err) + } + + record := core.NewRecord(collection) + record.Set("target_id", targetID) + record.Set("metric_key", metricKey) + record.Set("t", time.Now().UTC().Format("2006-01-02 15:04:05.000Z")) + record.Set("val", value) + + if err := s.app.Save(record); err != nil { + return fmt.Errorf("save metric record: %w", err) + } + + return nil +} diff --git a/internal/application/monitoring/monitor.go b/internal/application/monitoring/monitor.go index def7032..ab2304b 100644 --- a/internal/application/monitoring/monitor.go +++ b/internal/application/monitoring/monitor.go @@ -13,18 +13,20 @@ import ( // MonitorService is the background network monitoring service. type MonitorService struct { app core.App - networkService *NetworkService - stopChan chan bool + geoService *GeoService + metricsService *MetricsService + stopChan chan struct{} latencyTicker *time.Ticker geoTicker *time.Ticker } // NewMonitorService creates a new network monitoring service. -func NewMonitorService(app core.App, networkService *NetworkService) *MonitorService { +func NewMonitorService(app core.App, geoService *GeoService, metricsService *MetricsService) *MonitorService { return &MonitorService{ app: app, - networkService: networkService, - stopChan: make(chan bool), + geoService: geoService, + metricsService: metricsService, + stopChan: make(chan struct{}), } } @@ -41,30 +43,26 @@ func (s *MonitorService) Start(latencyInterval, geoInterval time.Duration) { go s.updateAllServersGeoLocation() s.latencyTicker = time.NewTicker(latencyInterval) - go func() { - for { - select { - case <-s.latencyTicker.C: - s.updateAllServersLatency() - case <-s.stopChan: - return - } - } - }() + s.startTicker(s.latencyTicker, s.updateAllServersLatency) s.geoTicker = time.NewTicker(geoInterval) + s.startTicker(s.geoTicker, s.updateAllServersGeoLocation) + + s.app.Logger().Info("Network monitor service started successfully") +} + +// startTicker runs fn on each tick until stopped. +func (s *MonitorService) startTicker(ticker *time.Ticker, fn func()) { go func() { for { select { - case <-s.geoTicker.C: - s.updateAllServersGeoLocation() + case <-ticker.C: + fn() case <-s.stopChan: return } } }() - - s.app.Logger().Info("Network monitor service started successfully") } // Stop halts the background monitoring task. @@ -129,32 +127,16 @@ func (s *MonitorService) updateAllServersGeoLocation() { } } -// updateServerLatency updates latency for a single server. +// updateServerLatency pings a single server and records the result to metrics. func (s *MonitorService) updateServerLatency(serverID string, serverAddr string, serverPort int) { addr := fmt.Sprintf("%s:%d", serverAddr, serverPort) pingResult := utils.PingHost(addr, 5*time.Second) - networkStatus := map[string]interface{}{ - "latency": pingResult.Latency, - "reachable": pingResult.Reachable, - "lastCheckTime": time.Now().Format(time.RFC3339), - "error": pingResult.Error, + if err := s.metricsService.RecordServerLatency(serverID, pingResult.Latency); err != nil { + s.app.Logger().Error("Failed to record server latency metric", "serverId", serverID, "error", err) } - networkStatusJSON, _ := json.Marshal(networkStatus) - - _, err := s.app.DB(). - Update("fh_servers", - dbx.Params{"networkStatus": string(networkStatusJSON)}, - dbx.HashExp{"id": serverID}, - ).Execute() - - if err != nil { - s.app.Logger().Error("Failed to update server latency", "serverId", serverID, "error", err) - return - } - - s.app.Logger().Debug("Updated latency", + s.app.Logger().Debug("Checked latency", "serverId", serverID, "addr", serverAddr, "latency", pingResult.Latency, @@ -164,24 +146,18 @@ func (s *MonitorService) updateServerLatency(serverID string, serverAddr string, // updateServerGeoLocation updates geolocation for a single server. func (s *MonitorService) updateServerGeoLocation(serverID string, serverAddr string) { - location, err := s.networkService.getGeoLocationWithCache(serverAddr) + location, err := s.geoService.Lookup(serverAddr) if err != nil { s.app.Logger().Warn("Failed to get geo location", "serverId", serverID, "addr", serverAddr, "error", err) return } - geoLocation := map[string]interface{}{ - "country": location.Country, - "countryCode": location.CountryCode, - "region": location.Region, - "city": location.City, - "isp": location.ISP, - "lat": location.Latitude, - "lon": location.Longitude, + geoLocationJSON, err := json.Marshal(location) + if err != nil { + s.app.Logger().Error("Failed to marshal geo location", "serverId", serverID, "error", err) + return } - geoLocationJSON, _ := json.Marshal(geoLocation) - _, err = s.app.DB(). Update("fh_servers", dbx.Params{"geoLocation": string(geoLocationJSON)}, diff --git a/internal/application/monitoring/service.go b/internal/application/monitoring/service.go index 69ba9b0..73fd243 100644 --- a/internal/application/monitoring/service.go +++ b/internal/application/monitoring/service.go @@ -1,7 +1,6 @@ package monitoring import ( - "fmt" "podux/pkg/utils" "sync" "time" @@ -9,123 +8,55 @@ import ( "github.com/pocketbase/pocketbase/core" ) -// NetworkService is the network diagnostic service. -type NetworkService struct { - app core.App - geoCache map[string]*geoCacheItem // IP geolocation cache - geoCacheLock sync.RWMutex // Cache read-write lock +// GeoService resolves IP addresses to geolocation data with a 24-hour in-memory cache. +type GeoService struct { + app core.App + cache map[string]*geoCacheItem + cacheLock sync.RWMutex } -// geoCacheItem is a geolocation cache entry. type geoCacheItem struct { Location *utils.GeoLocation ExpiresAt time.Time } -// ServerNetworkStatus holds network status for a server. -type ServerNetworkStatus struct { - ServerID string `json:"serverId"` - ServerName string `json:"serverName"` - ServerAddr string `json:"serverAddr"` - ServerPort int `json:"serverPort"` - NetworkStatus *NetworkStatus `json:"networkStatus"` - GeoLocation *utils.GeoLocation `json:"geoLocation,omitempty"` -} - // NetworkStatus holds latency and reachability information. type NetworkStatus struct { - Latency int64 `json:"latency"` // Latency in milliseconds - Reachable bool `json:"reachable"` // Whether the host is reachable - LastCheckTime time.Time `json:"lastCheckTime"` // Last check timestamp + Latency int64 `json:"latency"` + Reachable bool `json:"reachable"` + LastCheckTime time.Time `json:"lastCheckTime"` Error string `json:"error,omitempty"` } -// NewNetworkService creates a new network diagnostic service. -func NewNetworkService(app core.App) *NetworkService { - return &NetworkService{ - app: app, - geoCache: make(map[string]*geoCacheItem), +func NewGeoService(app core.App) *GeoService { + return &GeoService{ + app: app, + cache: make(map[string]*geoCacheItem), } } -// GetServerNetworkStatus retrieves server network status. -func (s *NetworkService) GetServerNetworkStatus(serverID string) (*ServerNetworkStatus, error) { - record, err := s.app.FindRecordById("fh_servers", serverID) - if err != nil { - return nil, fmt.Errorf("server not found: %w", err) - } - - serverName := record.GetString("name") - serverAddr := record.GetString("serverAddr") - serverPort := record.GetInt("serverPort") - - addr := fmt.Sprintf("%s:%d", serverAddr, serverPort) - pingResult := utils.PingHost(addr, 5*time.Second) - - networkStatus := &NetworkStatus{ - Latency: pingResult.Latency, - Reachable: pingResult.Reachable, - LastCheckTime: time.Now(), - Error: pingResult.Error, - } - - geoLocation, err := s.getGeoLocationWithCache(serverAddr) - if err != nil { - s.app.Logger().Warn("Failed to get geo location", "addr", serverAddr, "error", err) - } - - return &ServerNetworkStatus{ - ServerID: serverID, - ServerName: serverName, - ServerAddr: serverAddr, - ServerPort: serverPort, - NetworkStatus: networkStatus, - GeoLocation: geoLocation, - }, nil -} - -// getGeoLocationWithCache retrieves geolocation information with a 24-hour cache. -func (s *NetworkService) getGeoLocationWithCache(addr string) (*utils.GeoLocation, error) { - s.geoCacheLock.RLock() - if item, exists := s.geoCache[addr]; exists { +// Lookup returns geolocation for the given address, using the cache when valid. +func (s *GeoService) Lookup(addr string) (*utils.GeoLocation, error) { + s.cacheLock.RLock() + if item, exists := s.cache[addr]; exists { if time.Now().Before(item.ExpiresAt) { - s.geoCacheLock.RUnlock() + s.cacheLock.RUnlock() return item.Location, nil } } - s.geoCacheLock.RUnlock() + s.cacheLock.RUnlock() location, err := utils.GetGeoLocation(addr) if err != nil { return nil, err } - s.geoCacheLock.Lock() - s.geoCache[addr] = &geoCacheItem{ + s.cacheLock.Lock() + s.cache[addr] = &geoCacheItem{ Location: location, ExpiresAt: time.Now().Add(24 * time.Hour), } - s.geoCacheLock.Unlock() + s.cacheLock.Unlock() return location, nil } - -// ClearGeoCache clears the geolocation cache. -func (s *NetworkService) ClearGeoCache() { - s.geoCacheLock.Lock() - defer s.geoCacheLock.Unlock() - s.geoCache = make(map[string]*geoCacheItem) -} - -// CleanExpiredCache removes expired entries from the geolocation cache. -func (s *NetworkService) CleanExpiredCache() { - s.geoCacheLock.Lock() - defer s.geoCacheLock.Unlock() - - now := time.Now() - for addr, item := range s.geoCache { - if now.After(item.ExpiresAt) { - delete(s.geoCache, addr) - } - } -} diff --git a/internal/infrastructure/persistence/server_repository.go b/internal/infrastructure/persistence/server_repository.go index 315c18f..701d4c5 100644 --- a/internal/infrastructure/persistence/server_repository.go +++ b/internal/infrastructure/persistence/server_repository.go @@ -79,10 +79,11 @@ func (r *ServerRepository) ResetAllBootStatus() error { func (r *ServerRepository) GetMaxLatency() (int64, error) { var maxLatency int64 + // Get the max latency among each target's most recent measurement. err := r.app.DB(). - Select("MAX(CAST(json_extract(networkStatus, '$.latency') AS INTEGER))"). - From("fh_servers"). - Where(dbx.NewExp("networkStatus IS NOT NULL AND networkStatus != ''")). + Select("MAX(val)"). + From("fh_metrics_raw"). + Where(dbx.NewExp("metric_key = 'frps_delay' AND t IN (SELECT MAX(t) FROM fh_metrics_raw WHERE metric_key = 'frps_delay' GROUP BY target_id)")). Row(&maxLatency) if err != nil { diff --git a/internal/interfaces/http/server_handler.go b/internal/interfaces/http/server_handler.go new file mode 100644 index 0000000..0a81c03 --- /dev/null +++ b/internal/interfaces/http/server_handler.go @@ -0,0 +1,218 @@ +package httphandler + +import ( + "fmt" + "math" + "strconv" + "time" + + "podux/internal/application/monitoring" + "podux/pkg/response" + + "github.com/pocketbase/dbx" + "github.com/pocketbase/pocketbase/core" +) + +type ServerHandler struct { + app core.App + metricsService *monitoring.MetricsService +} + +func NewServerHandler(app core.App, metricsService *monitoring.MetricsService) *ServerHandler { + return &ServerHandler{app: app, metricsService: metricsService} +} + +type serverVO struct { + ID string `json:"id"` + ServerName string `json:"serverName"` + User string `json:"user"` + ServerAddr string `json:"serverAddr"` + ServerPort int `json:"serverPort"` + Description string `json:"description"` + BootStatus string `json:"bootStatus"` + AutoConnection bool `json:"autoConnection"` + SendRate float64 `json:"sendRate"` + RecvRate float64 `json:"recvRate"` + GeoLocation any `json:"geoLocation,omitempty"` + Log any `json:"log,omitempty"` + Auth any `json:"auth,omitempty"` + Transport any `json:"transport,omitempty"` + Metadatas any `json:"metadatas,omitempty"` + Created string `json:"created"` + Updated string `json:"updated"` + NetworkStatus *monitoring.NetworkStatus `json:"networkStatus,omitempty"` +} + +type serverListResponse struct { + Page int `json:"page"` + PerPage int `json:"perPage"` + TotalItems int64 `json:"totalItems"` + TotalPages int `json:"totalPages"` + Items []serverVO `json:"items"` +} + +type serverOptionVO struct { + ID string `json:"id"` + ServerName string `json:"serverName"` + BootStatus string `json:"bootStatus"` + NetworkStatus *monitoring.NetworkStatus `json:"networkStatus,omitempty"` +} + +type probePoint struct { + T string `json:"t"` + Val float64 `json:"val"` +} + +func (h *ServerHandler) RegisterHandlers(e *core.ServeEvent) { + // Paginated server list with assembled latency metrics. + e.Router.GET("/api/servers", requireAuth(func(e *core.RequestEvent) error { + page, _ := strconv.Atoi(e.Request.URL.Query().Get("page")) + if page < 1 { + page = 1 + } + perPage, _ := strconv.Atoi(e.Request.URL.Query().Get("perPage")) + if perPage < 1 { + perPage = 10 + } + search := e.Request.URL.Query().Get("search") + + // Count total matching records + var total int64 + countQ := h.app.DB().Select("COUNT(*)").From("fh_servers") + if search != "" { + countQ = countQ.Where(dbx.NewExp( + "(serverName LIKE {:s} OR serverAddr LIKE {:s} OR description LIKE {:s})", + dbx.Params{"s": "%" + search + "%"}, + )) + } + if err := countQ.Row(&total); err != nil { + return e.JSON(500, response.Error(err)) + } + + // Fetch the page of records + var records []*core.Record + var err error + if search != "" { + records, err = h.app.FindRecordsByFilter( + "fh_servers", + "serverName ~ {:s} || serverAddr ~ {:s} || description ~ {:s}", + "-created", + perPage, + (page-1)*perPage, + map[string]any{"s": search}, + ) + } else { + records, err = h.app.FindRecordsByFilter("fh_servers", "", "-created", perPage, (page-1)*perPage) + } + if err != nil { + return e.JSON(500, response.Error(err)) + } + + latencyMap, err := h.metricsService.GetLatestLatencyBatch() + if err != nil { + h.app.Logger().Warn("Failed to get latency batch", "error", err) + latencyMap = map[string]*monitoring.NetworkStatus{} + } + + totalPages := int(math.Ceil(float64(total) / float64(perPage))) + items := make([]serverVO, 0, len(records)) + for _, r := range records { + items = append(items, serverVO{ + ID: r.Id, + ServerName: r.GetString("serverName"), + User: r.GetString("user"), + ServerAddr: r.GetString("serverAddr"), + ServerPort: r.GetInt("serverPort"), + Description: r.GetString("description"), + BootStatus: r.GetString("bootStatus"), + AutoConnection: r.GetBool("autoConnection"), + SendRate: r.GetFloat("sendRate"), + RecvRate: r.GetFloat("recvRate"), + GeoLocation: r.Get("geoLocation"), + Log: r.Get("log"), + Auth: r.Get("auth"), + Transport: r.Get("transport"), + Metadatas: r.Get("metadatas"), + Created: r.GetString("created"), + Updated: r.GetString("updated"), + NetworkStatus: latencyMap[r.Id], + }) + } + + return e.JSON(200, serverListResponse{ + Page: page, + PerPage: perPage, + TotalItems: total, + TotalPages: totalPages, + Items: items, + }) + })) + + // Probe history for a single server — last 30 minutes of latency data. + e.Router.GET("/api/servers/probe-history", requireAuth(func(e *core.RequestEvent) error { + serverID := e.Request.URL.Query().Get("serverId") + if serverID == "" { + return e.JSON(400, response.Error(fmt.Errorf("serverId is required"))) + } + + since := time.Now().UTC().Add(-30 * time.Minute).Format("2006-01-02 15:04:05.000Z") + + type row struct { + T string `db:"t"` + Val float64 `db:"val"` + } + var rows []row + err := h.app.DB(). + NewQuery(` + SELECT r.t, r.val + FROM fh_metrics_raw r + INNER JOIN fh_metrics_targets t ON r.target_id = t.id + WHERE t.serverId = {:serverId} + AND r.metric_key = {:key} + AND r.t >= {:since} + ORDER BY r.t ASC + LIMIT 500 + `). + Bind(dbx.Params{ + "serverId": serverID, + "key": monitoring.MetricKeyFrpsDelay, + "since": since, + }). + All(&rows) + if err != nil { + return e.JSON(500, response.Error(err)) + } + + points := make([]probePoint, 0, len(rows)) + for _, r := range rows { + points = append(points, probePoint{T: r.T, Val: r.Val}) + } + return e.JSON(200, points) + })) + + // Flat server list for dropdowns, with latest latency assembled. + e.Router.GET("/api/servers/options", requireAuth(func(e *core.RequestEvent) error { + records, err := h.app.FindRecordsByFilter("fh_servers", "", "-created", 500, 0) + if err != nil { + return e.JSON(500, response.Error(err)) + } + + latencyMap, err := h.metricsService.GetLatestLatencyBatch() + if err != nil { + h.app.Logger().Warn("Failed to get latency batch for options", "error", err) + latencyMap = map[string]*monitoring.NetworkStatus{} + } + + items := make([]serverOptionVO, 0, len(records)) + for _, r := range records { + items = append(items, serverOptionVO{ + ID: r.Id, + ServerName: r.GetString("serverName"), + BootStatus: r.GetString("bootStatus"), + NetworkStatus: latencyMap[r.Id], + }) + } + + return e.JSON(200, items) + })) +} diff --git a/site/src/components/LatencyChart.tsx b/site/src/components/LatencyChart.tsx new file mode 100644 index 0000000..006ff24 --- /dev/null +++ b/site/src/components/LatencyChart.tsx @@ -0,0 +1,266 @@ +import { useEffect, useState, useCallback } from "react"; +import { Flex, Text } from "@radix-ui/themes"; +import { motion, AnimatePresence } from "framer-motion"; +import { useTranslation } from "react-i18next"; +import { + AreaChart, + Area, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + ResponsiveContainer, +} from "recharts"; +import { apiGet } from "../lib/api"; + +interface ProbePoint { + t: string; + val: number; +} + +interface ChartPoint { + time: string; + ms: number; +} + +function toChartPoints(points: ProbePoint[]): ChartPoint[] { + return points + .filter((p) => p.val >= 0) + .map((p) => ({ + time: new Date(p.t.replace(" ", "T").replace(/Z$/, "+00:00")).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }), + ms: Math.round(p.val), + })); +} + +// ── Custom tooltip ──────────────────────────────────────────────────────────── + +interface CustomTooltipProps { + active?: boolean; + payload?: { value: number }[]; + label?: string; +} + +function CustomTooltip({ active, payload, label }: CustomTooltipProps) { + if (!active || !payload?.length) return null; + return ( + + {label} + + + {payload[0].value}ms + + + ); +} + +// ── Pulsing dot on the last data point ─────────────────────────────────────── + +interface DotProps { + cx?: number; + cy?: number; + index?: number; + dataLength: number; +} + +function PulsingDot({ cx = 0, cy = 0, index = 0, dataLength }: DotProps) { + if (index !== dataLength - 1) return null; + return ( + + + + + + + + ); +} + +// ── Skeleton loader ─────────────────────────────────────────────────────────── + +function ChartSkeleton() { + // Fake wave path to mimic a latency curve + const path = "M0,60 C20,55 40,70 60,50 C80,30 100,65 120,45 C140,25 160,55 180,40 C200,25 220,50 240,35 C260,20 280,45 300,30 C320,15 340,40 360,25"; + return ( + + + + + + + + + + + + + {/* Fake grid lines */} + {[40, 80, 120, 160].map((y) => ( + + ))} + {/* Fake Y-axis labels */} + {[40, 80, 120].map((y, i) => ( + + ))} + {/* Fake curve area */} + + {/* Fake curve line */} + + + ); +} + +// ── Main component ──────────────────────────────────────────────────────────── + +interface LatencyChartProps { + serverId: string; +} + +export function LatencyChart({ serverId }: LatencyChartProps) { + const { t } = useTranslation(); + const [data, setData] = useState([]); + const [loading, setLoading] = useState(true); + const [animKey, setAnimKey] = useState(0); + + const load = useCallback(async () => { + try { + const res = await apiGet(`/api/servers/probe-history?serverId=${serverId}`); + if (!res.ok) return; + const points: ProbePoint[] = await res.json(); + setData(toChartPoints(points)); + setAnimKey((k) => k + 1); + } catch { + // silent + } finally { + setLoading(false); + } + }, [serverId]); + + useEffect(() => { + load(); + const interval = setInterval(load, 30_000); + return () => clearInterval(interval); + }, [load]); + + const isEmpty = !loading && data.length === 0; + + return ( +
+ + {loading ? ( + + + + ) : isEmpty ? ( + + {t("server.probeNoData")} + + ) : ( + + + + + + + + + + + + + + + `${v}ms`} + width={52} + /> + + } + cursor={{ stroke: "var(--green-7)", strokeWidth: 1, strokeDasharray: "4 4" }} + /> + + ( + + )} + activeDot={{ + r: 5, + fill: "var(--green-9)", + stroke: "var(--color-panel-solid)", + strokeWidth: 2, + }} + isAnimationActive={true} + animationDuration={900} + animationEasing="ease-out" + /> + + + + )} + +
+ ); +} diff --git a/site/src/components/ProbeHistory.tsx b/site/src/components/ProbeHistory.tsx new file mode 100644 index 0000000..ef77724 --- /dev/null +++ b/site/src/components/ProbeHistory.tsx @@ -0,0 +1,290 @@ +import { useEffect, useState, useCallback } from "react"; +import { Flex, Text, Tooltip, Badge } from "@radix-ui/themes"; +import { motion } from "framer-motion"; +import { Icon } from "@iconify/react"; +import { useTranslation } from "react-i18next"; +import { apiGet } from "../lib/api"; + +interface ProbePoint { + t: string; + val: number; +} + +interface Bucket { + start: number; + end: number; + avg: number | null; // null = no data, -1 = unreachable +} + +const BUCKETS = 30; +const WINDOW_MS = 30 * 60 * 1000; + +function buildBuckets(points: ProbePoint[]): Bucket[] { + const now = Date.now(); + const slotMs = WINDOW_MS / BUCKETS; + + const buckets: Bucket[] = Array.from({ length: BUCKETS }, (_, i) => ({ + start: now - WINDOW_MS + i * slotMs, + end: now - WINDOW_MS + (i + 1) * slotMs, + avg: null, + })); + + for (const p of points) { + const ts = new Date(p.t.replace(" ", "T").replace(/Z$/, "+00:00")).getTime(); + const idx = Math.floor((ts - (now - WINDOW_MS)) / slotMs); + if (idx < 0 || idx >= BUCKETS) continue; + const b = buckets[idx]; + if (p.val < 0) { + b.avg = -1; + } else if (b.avg === null) { + b.avg = p.val; + } else if (b.avg >= 0) { + b.avg = (b.avg + p.val) / 2; + } + } + + return buckets; +} + +function bucketGradient(avg: number | null): string { + if (avg === null) return "linear-gradient(to top, var(--gray-4), var(--gray-5))"; + if (avg < 0) return "linear-gradient(to top, var(--red-6), var(--red-8))"; + if (avg < 50) return "linear-gradient(to top, var(--green-7), var(--green-9))"; + if (avg < 150) return "linear-gradient(to top, var(--amber-7), var(--amber-9))"; + return "linear-gradient(to top, var(--red-7), var(--red-9))"; +} + +function bucketGlow(avg: number | null): string { + if (avg === null || avg < 0) return "none"; + if (avg < 50) return "0 2px 8px var(--green-a6)"; + if (avg < 150) return "0 2px 8px var(--amber-a6)"; + return "0 2px 8px var(--red-a6)"; +} + +function bucketLabel(b: Bucket, noData: string, unreachable: string): string { + const fmt = (ts: number) => + new Date(ts).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + const range = `${fmt(b.start)} – ${fmt(b.end)}`; + if (b.avg === null) return `${range}\n${noData}`; + if (b.avg < 0) return `${range}\n${unreachable}`; + return `${range}\n${Math.round(b.avg)}ms`; +} + +interface ProbeHistoryProps { + serverId: string; +} + +export function ProbeHistory({ serverId }: ProbeHistoryProps) { + const { t } = useTranslation(); + const [buckets, setBuckets] = useState([]); + const [loading, setLoading] = useState(true); + const [animKey, setAnimKey] = useState(0); + + const load = useCallback(async () => { + try { + const res = await apiGet(`/api/servers/probe-history?serverId=${serverId}`); + if (!res.ok) return; + const points: ProbePoint[] = await res.json(); + setBuckets(buildBuckets(points)); + setAnimKey((k) => k + 1); + } catch { + // silent + } finally { + setLoading(false); + } + }, [serverId]); + + useEffect(() => { + load(); + const interval = setInterval(load, 30_000); + return () => clearInterval(interval); + }, [load]); + + // Stats + const valid = buckets.filter((b) => b.avg !== null); + const reachable = valid.filter((b) => b.avg! >= 0); + const uptime = valid.length > 0 ? (reachable.length / valid.length) * 100 : null; + const avgLatency = + reachable.length > 0 + ? Math.round(reachable.reduce((s, b) => s + b.avg!, 0) / reachable.length) + : null; + const maxLatency = + reachable.length > 0 ? Math.round(Math.max(...reachable.map((b) => b.avg!))) : null; + + const lastActiveIdx = buckets.reduce((last, b, i) => (b.avg !== null ? i : last), -1); + + const uptimeColor = + uptime === null ? "gray" : uptime === 100 ? "green" : uptime >= 80 ? "amber" : "red"; + + return ( + + {/* Stats row */} + + {/* Overall status */} + + {uptime === null || loading ? ( + + + {t("server.probeChecking")} + + ) : uptime === 100 ? ( + + + + + {t("server.probeNormal")} + + ) : uptime >= 80 ? ( + + + {t("server.probePartial")} + + ) : ( + + + {t("server.probeOutage")} + + )} + + + {/* Divider */} +
+ + {/* Uptime */} + {uptime !== null && ( + + {t("server.probeUptime")} + + {uptime.toFixed(1)}% + + + )} + + {/* Avg latency */} + {avgLatency !== null && ( + + {t("server.probeAvgLatency")} + {avgLatency}ms + + )} + + {/* Peak latency */} + {maxLatency !== null && ( + + {t("server.probePeakLatency")} + 150 ? "red" : maxLatency > 50 ? "amber" : undefined}> + {maxLatency}ms + + + )} + + + {/* Bar grid */} + + {loading + ? Array.from({ length: BUCKETS }).map((_, i) => ( + + )) + : buckets.map((b, i) => { + const isLast = i === lastActiveIdx; + return ( + + + {/* Shine overlay */} +
+ {/* Pulse on latest active bar */} + {isLast && b.avg !== null && ( + + )} + + + ); + })} + + + {/* Time labels */} + + {t("server.probe30mAgo")} + + + {t("server.probeNow")} + + + + ); +} diff --git a/site/src/locales/en.json b/site/src/locales/en.json index 43d1de1..1210f4c 100644 --- a/site/src/locales/en.json +++ b/site/src/locales/en.json @@ -238,7 +238,21 @@ "startSuccess": "Server started successfully", "startFailed": "Failed to start server", "stopSuccess": "Server stopped successfully", - "stopFailed": "Failed to stop server" + "stopFailed": "Failed to stop server", + "statusCard": "Server Status", + "latencyChartCard": "Latency History", + "probeNormal": "Normal", + "probePartial": "Partial Outage", + "probeOutage": "Outage", + "probeChecking": "Checking", + "probeUptime": "Uptime", + "probeAvgLatency": "Avg Latency", + "probePeakLatency": "Peak Latency", + "probeNoData": "No data", + "probeUnreachable": "Unreachable", + "probeNow": "Now", + "probe30mAgo": "30 min ago", + "latencyMs": "Latency (ms)" }, "proxy": { "title": "Proxies", diff --git a/site/src/locales/zh.json b/site/src/locales/zh.json index f539fb9..d16ba93 100644 --- a/site/src/locales/zh.json +++ b/site/src/locales/zh.json @@ -238,7 +238,21 @@ "startSuccess": "服务器启动成功", "startFailed": "服务器启动失败", "stopSuccess": "服务器停止成功", - "stopFailed": "服务器停止失败" + "stopFailed": "服务器停止失败", + "statusCard": "服务器状态", + "latencyChartCard": "延迟曲线", + "probeNormal": "正常", + "probePartial": "部分异常", + "probeOutage": "异常", + "probeChecking": "检测中", + "probeUptime": "可达率", + "probeAvgLatency": "平均延迟", + "probePeakLatency": "峰值延迟", + "probeNoData": "无数据", + "probeUnreachable": "不可达", + "probeNow": "现在", + "probe30mAgo": "30 分钟前", + "latencyMs": "延迟 (ms)" }, "proxy": { "title": "代理", diff --git a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx index 6422e76..9f506fc 100644 --- a/site/src/pages/ServerDetail/ServerDetailPage.view.tsx +++ b/site/src/pages/ServerDetail/ServerDetailPage.view.tsx @@ -8,8 +8,9 @@ import pb from "../../lib/pocketbase"; import type { Server } from "../Servers/useServers"; import { toast } from "sonner"; import { motion } from "framer-motion"; -import { ServerLatency } from "../../components/ServerLatency"; import { ServerLocation } from "../../components/ServerLocation"; +import { ProbeHistory } from "../../components/ProbeHistory"; +import { LatencyChart } from "../../components/LatencyChart"; import { useTranslation } from "react-i18next"; import { useServerProxies } from "./useServerProxies"; import { apiPost } from "../../lib/api"; @@ -241,14 +242,7 @@ export function ServerDetailPage() { )} - - - {t("server.latency")} - - - - - + {t("server.location")} @@ -364,6 +358,34 @@ export function ServerDetailPage() { + {/* Probe History */} + + + + {t("server.statusCard")} + + + + + + {/* Latency Chart */} + + + + {t("server.latencyChartCard")} + + + + + {/* Proxy List */} { try { - // Only show loading spinner on initial load, not on refresh if (!isRefresh && servers.length === 0) { setLoading(true); } else if (isRefresh) { setRefreshing(true); } - const options: any = { - sort: "-created", - }; + const params = new URLSearchParams({ + page: String(page), + perPage: String(PER_PAGE), + }); + if (search) params.set("search", search); - if (search) { - options.filter = `serverName ~ "${search}" || serverAddr ~ "${search}" || description ~ "${search}"`; - } + const res = await apiGet(`/api/servers?${params}`); + if (!res.ok) throw new Error("Failed to fetch servers"); + const data = await res.json(); - const result = await pb.collection("fh_servers").getList(page, PER_PAGE, options); - - // Network status is already stored in database, no need to fetch separately - setServers(result.items); - setTotalPages(result.totalPages); + setServers(data.items); + setTotalPages(data.totalPages); } catch (err) { if ((err as any)?.isAbort) return; toast.error(err instanceof Error ? err.message : "Failed to fetch servers");