♻️ Delay monitoring Code refactoring.

This commit is contained in:
刘嘉伟 committed 2026-03-20 17:39:29 +08:00
1 parent 893e5bc670
commit 71c1f7633d
11 files changed
+1081 -167

No files matched your search

+184
View File
@@ -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
}
+26 -50
View File
@@ -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)},
+21 -90
View File
@@ -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)
}
}
}
@@ -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 {
+218
View File
@@ -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)
}))
}
+266
View File
@@ -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 (
<motion.div
initial={{ opacity: 0, scale: 0.92, y: -4 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
transition={{ duration: 0.15, ease: "easeOut" }}
style={{
background: "var(--color-panel-solid)",
border: "1px solid var(--gray-5)",
borderRadius: 10,
padding: "8px 12px",
boxShadow: "0 8px 24px rgba(0,0,0,0.14)",
}}
>
<Text size="1" color="gray">{label}</Text>
<Flex align="center" gap="2" mt="1">
<motion.div
animate={{ scale: [1, 1.3, 1] }}
transition={{ repeat: Infinity, duration: 1.5, ease: "easeInOut" }}
style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--green-9)" }}
/>
<Text size="2" weight="bold">{payload[0].value}ms</Text>
</Flex>
</motion.div>
);
}
// ── 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 (
<g>
<circle cx={cx} cy={cy} r={4} fill="var(--green-9)" />
<circle cx={cx} cy={cy} r={4} fill="var(--green-9)" opacity={0.5}>
<animate attributeName="r" from="4" to="14" dur="1.6s" repeatCount="indefinite" />
<animate attributeName="opacity" from="0.5" to="0" dur="1.6s" repeatCount="indefinite" />
</circle>
</g>
);
}
// ── 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 (
<svg width="100%" height={180} style={{ overflow: "hidden" }}>
<defs>
<linearGradient id="shimmer" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stopColor="var(--gray-3)" />
<stop offset="40%" stopColor="var(--gray-5)" />
<stop offset="100%" stopColor="var(--gray-3)" />
<animateTransform
attributeName="gradientTransform"
type="translate"
from="-1 0"
to="2 0"
dur="1.4s"
repeatCount="indefinite"
/>
</linearGradient>
<clipPath id="skeletonClip">
<rect x="0" y="0" width="100%" height="100%" />
</clipPath>
</defs>
{/* Fake grid lines */}
{[40, 80, 120, 160].map((y) => (
<line key={y} x1="52" y1={y} x2="100%" y2={y} stroke="var(--gray-3)" strokeDasharray="4 4" />
))}
{/* Fake Y-axis labels */}
{[40, 80, 120].map((y, i) => (
<rect key={i} x="0" y={y - 6} width="36" height="10" rx="4" fill="url(#shimmer)" />
))}
{/* Fake curve area */}
<path
d={`${path} L360,180 L0,180 Z`}
fill="url(#shimmer)"
opacity={0.5}
clipPath="url(#skeletonClip)"
/>
{/* Fake curve line */}
<path d={path} fill="none" stroke="url(#shimmer)" strokeWidth="2" />
</svg>
);
}
// ── Main component ────────────────────────────────────────────────────────────
interface LatencyChartProps {
serverId: string;
}
export function LatencyChart({ serverId }: LatencyChartProps) {
const { t } = useTranslation();
const [data, setData] = useState<ChartPoint[]>([]);
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 (
<div style={{ position: "relative", height: 180 }}>
<AnimatePresence mode="wait">
{loading ? (
<motion.div
key="skeleton"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.25 }}
style={{ position: "absolute", inset: 0 }}
>
<ChartSkeleton />
</motion.div>
) : isEmpty ? (
<motion.div
key="empty"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}
>
<Text size="2" color="gray">{t("server.probeNoData")}</Text>
</motion.div>
) : (
<motion.div
key={`chart-${animKey}`}
initial={{ opacity: 0, clipPath: "inset(0 100% 0 0)" }}
animate={{ opacity: 1, clipPath: "inset(0 0% 0 0)" }}
transition={{ duration: 0.9, ease: [0.25, 0.46, 0.45, 0.94] }}
style={{ position: "absolute", inset: 0 }}
>
<ResponsiveContainer width="100%" height={180}>
<AreaChart data={data} margin={{ top: 8, right: 4, left: -16, bottom: 0 }}>
<defs>
<linearGradient id="latencyGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="var(--green-9)" stopOpacity={0.28} />
<stop offset="95%" stopColor="var(--green-9)" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="var(--gray-4)" vertical={false} />
<XAxis
dataKey="time"
tick={{ fontSize: 11, fill: "var(--gray-9)" }}
tickLine={false}
axisLine={false}
interval="preserveStartEnd"
/>
<YAxis
tick={{ fontSize: 11, fill: "var(--gray-9)" }}
tickLine={false}
axisLine={false}
tickFormatter={(v) => `${v}ms`}
width={52}
/>
<Tooltip
content={<CustomTooltip />}
cursor={{ stroke: "var(--green-7)", strokeWidth: 1, strokeDasharray: "4 4" }}
/>
<Area
type="monotone"
dataKey="ms"
stroke="var(--green-9)"
strokeWidth={2}
fill="url(#latencyGrad)"
dot={(props: any) => (
<PulsingDot key={props.index} {...props} dataLength={data.length} />
)}
activeDot={{
r: 5,
fill: "var(--green-9)",
stroke: "var(--color-panel-solid)",
strokeWidth: 2,
}}
isAnimationActive={true}
animationDuration={900}
animationEasing="ease-out"
/>
</AreaChart>
</ResponsiveContainer>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
+290
View File
@@ -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<Bucket[]>([]);
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 (
<Flex direction="column" gap="4">
{/* Stats row */}
<Flex gap="5" align="center" wrap="wrap">
{/* Overall status */}
<Flex align="center" gap="2">
{uptime === null || loading ? (
<Badge color="gray" variant="soft">
<Icon icon="lucide:loader-2" width="10" height="10" className="animate-spin" />
{t("server.probeChecking")}
</Badge>
) : uptime === 100 ? (
<Badge color="green" variant="soft">
<motion.span
animate={{ opacity: [1, 0.4, 1] }}
transition={{ repeat: Infinity, duration: 2, ease: "easeInOut" }}
style={{ display: "flex", alignItems: "center" }}
>
<Icon icon="lucide:circle" width="8" height="8" />
</motion.span>
{t("server.probeNormal")}
</Badge>
) : uptime >= 80 ? (
<Badge color="amber" variant="soft">
<Icon icon="lucide:alert-circle" width="10" height="10" />
{t("server.probePartial")}
</Badge>
) : (
<Badge color="red" variant="soft">
<Icon icon="lucide:x-circle" width="10" height="10" />
{t("server.probeOutage")}
</Badge>
)}
</Flex>
{/* Divider */}
<div style={{ width: 1, height: 16, background: "var(--gray-5)" }} />
{/* Uptime */}
{uptime !== null && (
<Flex direction="column" gap="0">
<Text size="1" color="gray">{t("server.probeUptime")}</Text>
<Text size="2" weight="bold" color={uptimeColor}>
{uptime.toFixed(1)}%
</Text>
</Flex>
)}
{/* Avg latency */}
{avgLatency !== null && (
<Flex direction="column" gap="0">
<Text size="1" color="gray">{t("server.probeAvgLatency")}</Text>
<Text size="2" weight="bold">{avgLatency}ms</Text>
</Flex>
)}
{/* Peak latency */}
{maxLatency !== null && (
<Flex direction="column" gap="0">
<Text size="1" color="gray">{t("server.probePeakLatency")}</Text>
<Text size="2" weight="bold" color={maxLatency > 150 ? "red" : maxLatency > 50 ? "amber" : undefined}>
{maxLatency}ms
</Text>
</Flex>
)}
</Flex>
{/* Bar grid */}
<Flex
gap="1"
align="end"
style={{ height: 44, position: "relative" }}
>
{loading
? Array.from({ length: BUCKETS }).map((_, i) => (
<motion.div
key={i}
animate={{ opacity: [0.3, 0.6, 0.3] }}
transition={{
repeat: Infinity,
duration: 1.2,
delay: i * 0.04,
ease: "easeInOut",
}}
style={{
flex: 1,
height: 28 + Math.sin(i * 0.5) * 8,
borderRadius: 4,
background: "var(--gray-4)",
}}
/>
))
: buckets.map((b, i) => {
const isLast = i === lastActiveIdx;
return (
<Tooltip key={`${animKey}-${i}`} content={bucketLabel(b, t("server.probeNoData"), t("server.probeUnreachable"))}>
<motion.div
key={animKey}
initial={{ scaleY: 0, opacity: 0 }}
animate={{ scaleY: 1, opacity: b.avg === null ? 0.35 : 1 }}
transition={{
delay: i * 0.018,
duration: 0.35,
ease: [0.34, 1.56, 0.64, 1], // spring-like
}}
whileHover={{
scaleY: 1.18,
filter: "brightness(1.25)",
transition: { duration: 0.12 },
}}
style={{
flex: 1,
height: 36,
borderRadius: 4,
background: bucketGradient(b.avg),
boxShadow: isLast ? bucketGlow(b.avg) : "none",
transformOrigin: "bottom",
cursor: "default",
position: "relative",
overflow: "hidden",
}}
>
{/* Shine overlay */}
<div
style={{
position: "absolute",
inset: 0,
background:
"linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, transparent 60%)",
borderRadius: 4,
pointerEvents: "none",
}}
/>
{/* Pulse on latest active bar */}
{isLast && b.avg !== null && (
<motion.div
animate={{ opacity: [0, 0.4, 0] }}
transition={{
repeat: Infinity,
duration: 2,
ease: "easeInOut",
}}
style={{
position: "absolute",
inset: 0,
background: "rgba(255,255,255,0.5)",
borderRadius: 4,
pointerEvents: "none",
}}
/>
)}
</motion.div>
</Tooltip>
);
})}
</Flex>
{/* Time labels */}
<Flex justify="between" align="center">
<Text size="1" color="gray">{t("server.probe30mAgo")}</Text>
<Flex align="center" gap="2">
<motion.div
animate={{ opacity: [1, 0.3, 1] }}
transition={{ repeat: Infinity, duration: 2, ease: "easeInOut" }}
style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--green-9)" }}
/>
<Text size="1" color="gray">{t("server.probeNow")}</Text>
</Flex>
</Flex>
</Flex>
);
}
+15 -1
View File
@@ -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",
+15 -1
View File
@@ -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": "代理",
@@ -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() {
</Text>
</Box>
)}
<Box>
<Text size="2" color="gray">
{t("server.latency")}
</Text>
<Box mt="1">
<ServerLatency networkStatus={server.networkStatus} size="3" />
</Box>
</Box>
<Box>
<Text size="2" color="gray">
{t("server.location")}
@@ -364,6 +358,34 @@ export function ServerDetailPage() {
</motion.div>
</Grid>
{/* Probe History */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.5, delay: 0.3, ease: "easeOut" }}
>
<Card size="3">
<Flex direction="column" gap="3">
<Heading size="4">{t("server.statusCard")}</Heading>
<ProbeHistory serverId={id!} />
</Flex>
</Card>
</motion.div>
{/* Latency Chart */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={mounted ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}
transition={{ duration: 0.5, delay: 0.35, ease: "easeOut" }}
>
<Card size="3">
<Flex direction="column" gap="3">
<Heading size="4">{t("server.latencyChartCard")}</Heading>
<LatencyChart serverId={id!} />
</Flex>
</Card>
</motion.div>
{/* Proxy List */}
<motion.div
initial={{ opacity: 0, y: 20 }}
+11 -13
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import pb from "../../lib/pocketbase";
import { apiPost } from "../../lib/api";
import { apiGet, apiPost } from "../../lib/api";
import { toast } from "sonner";
export interface Server {
@@ -75,26 +75,24 @@ export function useServers() {
const fetchServers = useCallback(
async (isRefresh = false) => {
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<Server>(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");