From 3947152336c27671ed1a5eb73cee5b71103d8d71 Mon Sep 17 00:00:00 2001 From: yusing Date: Fri, 25 Apr 2025 11:26:24 +0800 Subject: [PATCH] fix: uptime metrics --- internal/metrics/uptime/uptime.go | 8 ++++++++ internal/route/routes/query.go | 22 ++++++++++++++++++++++ internal/watcher/health/status.go | 17 +++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/internal/metrics/uptime/uptime.go b/internal/metrics/uptime/uptime.go index a8f026ea..50340921 100644 --- a/internal/metrics/uptime/uptime.go +++ b/internal/metrics/uptime/uptime.go @@ -37,6 +37,14 @@ func getStatuses(ctx context.Context, _ *StatusByAlias) (*StatusByAlias, error) }, nil } +func (s *Status) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]any{ + "status": s.Status.String(), + "latency": s.Latency, + "timestamp": s.Timestamp, + }) +} + func aggregateStatuses(entries []*StatusByAlias, query url.Values) (int, Aggregated) { limit := metricsutils.QueryInt(query, "limit", 0) offset := metricsutils.QueryInt(query, "offset", 0) diff --git a/internal/route/routes/query.go b/internal/route/routes/query.go index 8f3195ed..3ba70887 100644 --- a/internal/route/routes/query.go +++ b/internal/route/routes/query.go @@ -1,6 +1,7 @@ package routes import ( + "encoding/json" "time" "github.com/yusing/go-proxy/internal/homepage" @@ -29,6 +30,27 @@ type HealthInfoRaw struct { Latency time.Duration `json:"latency"` } +func (info *HealthInfoRaw) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]any{ + "status": info.Status.String(), + "latency": info.Latency.Milliseconds(), + }) +} + +func (info *HealthInfoRaw) UnmarshalJSON(data []byte) error { + var v map[string]any + if err := json.Unmarshal(data, &v); err != nil { + return err + } + if status, ok := v["status"].(string); ok { + info.Status = health.NewStatus(status) + } + if latency, ok := v["latency"].(float64); ok { + info.Latency = time.Duration(latency) + } + return nil +} + func getHealthInfoRaw(r Route) *HealthInfoRaw { mon := r.HealthMonitor() if mon == nil { diff --git a/internal/watcher/health/status.go b/internal/watcher/health/status.go index 105c5e7d..d8321aaf 100644 --- a/internal/watcher/health/status.go +++ b/internal/watcher/health/status.go @@ -16,6 +16,23 @@ const ( IdlingMask = StatusNapping | StatusStarting ) +func NewStatus(s string) Status { + switch s { + case "healthy": + return StatusHealthy + case "unhealthy": + return StatusUnhealthy + case "napping": + return StatusNapping + case "starting": + return StatusStarting + case "error": + return StatusError + default: + return StatusUnknown + } +} + func (s Status) String() string { switch s { case StatusHealthy: