sky/internal/platform/metrics/metrics.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

212 lines
7.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package metrics
import (
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Registry 是进程内唯一的指标注册表。
// 用自定义 registry 而非 prometheus.DefaultRegisterer:
// 测试里多次 new 不会因重复注册 panic。
type Registry struct {
Reg *prometheus.Registry
// HTTP 层
HTTPRequests *prometheus.CounterVec
HTTPDuration *prometheus.HistogramVec
HTTPInFlight prometheus.Gauge
HTTPRespSize *prometheus.HistogramVec
// 缓存层:这三个数字决定你能不能扛住并发
CacheHits prometheus.Counter
CacheMisses prometheus.Counter
CacheErrors prometheus.Counter
CacheFlight *prometheus.CounterVec
// 业务层
ArticlesCreated prometheus.Counter
CommentsCreated prometheus.Counter
LikesTotal prometheus.Counter
AuthFailures *prometheus.CounterVec
RateLimitedTotal prometheus.Counter
// 媒体
MediaPresigned prometheus.Counter
MediaConfirmed prometheus.Counter
// worker
CounterFlushed prometheus.Counter
OutboxProcessed prometheus.Counter
}
func New() *Registry {
reg := prometheus.NewRegistry()
m := &Registry{
Reg: reg,
HTTPRequests: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "HTTP 请求总数,按方法/路由/状态码分组",
}, []string{"method", "route", "status"}),
HTTPDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP 请求耗时分布",
// 分桶按实际观测值设计:本地实测 P99 在 10~130ms 区间,
// 桶要覆盖这个范围才能算出有意义的 P99,否则全落在一个桶里
Buckets: []float64{0.001, 0.002, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5},
}, []string{"method", "route", "status"}),
HTTPInFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Name: "http_requests_in_flight",
Help: "当前正在处理的请求数",
}),
HTTPRespSize: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_response_size_bytes",
Help: "响应体字节数",
Buckets: prometheus.ExponentialBuckets(256, 4, 8),
}, []string{"route"}),
CacheHits: prometheus.NewCounter(prometheus.CounterOpts{
Name: "cache_hits_total", Help: "缓存命中次数",
}),
CacheMisses: prometheus.NewCounter(prometheus.CounterOpts{
Name: "cache_misses_total", Help: "缓存未命中次数",
}),
CacheErrors: prometheus.NewCounter(prometheus.CounterOpts{
Name: "cache_errors_total", Help: "缓存读写失败次数(降级回源)",
}),
CacheFlight: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "cache_singleflight_merged_total", Help: "被 singleflight 合并的回源请求数",
}, []string{"key_type"}),
ArticlesCreated: prometheus.NewCounter(prometheus.CounterOpts{
Name: "articles_created_total", Help: "创建的文章数",
}),
CommentsCreated: prometheus.NewCounter(prometheus.CounterOpts{
Name: "comments_created_total", Help: "创建的评论数",
}),
LikesTotal: prometheus.NewCounter(prometheus.CounterOpts{
Name: "likes_total", Help: "点赞次数",
}),
AuthFailures: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "auth_failures_total", Help: "认证失败次数",
}, []string{"reason"}),
RateLimitedTotal: prometheus.NewCounter(prometheus.CounterOpts{
Name: "rate_limited_total", Help: "被限流的请求数",
}),
MediaPresigned: prometheus.NewCounter(prometheus.CounterOpts{
Name: "media_presigned_total", Help: "签发的上传凭证数",
}),
MediaConfirmed: prometheus.NewCounter(prometheus.CounterOpts{
Name: "media_confirmed_total", Help: "确认完成的上传数",
}),
CounterFlushed: prometheus.NewCounter(prometheus.CounterOpts{
Name: "worker_counter_flushed_total", Help: "worker 落库的计数条数",
}),
OutboxProcessed: prometheus.NewCounter(prometheus.CounterOpts{
Name: "worker_outbox_processed_total", Help: "worker 消费的 outbox 条数",
}),
}
reg.MustRegister(
m.HTTPRequests, m.HTTPDuration, m.HTTPInFlight, m.HTTPRespSize,
m.CacheHits, m.CacheMisses, m.CacheErrors, m.CacheFlight,
m.ArticlesCreated, m.CommentsCreated, m.LikesTotal, m.AuthFailures, m.RateLimitedTotal,
m.MediaPresigned, m.MediaConfirmed,
m.CounterFlushed, m.OutboxProcessed,
)
// 进程指标:GC、goroutine 数、内存、CPU。排障时第一眼要看这些
reg.MustRegister(collectors.NewGoCollector())
reg.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
return m
}
// Handler 暴露 /metrics 给 Prometheus 抓取
func (m *Registry) Handler() http.Handler {
return promhttp.HandlerFor(m.Reg, promhttp.HandlerOpts{
ErrorHandling: promhttp.ContinueOnError,
})
}
// Middleware 采集每个请求的计数、耗时、状态码。
//
// 路由标签用 chi 的 RoutePattern 而非 URL.Path:
// /api/v1/articles/art_abc123 会归一成 /api/v1/articles/{maskID},
// 否则每个文章 ID 都会生成一条独立的时间序列,把 Prometheus 撑爆。
func (m *Registry) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// /metrics 和健康检查自身不计入,避免抓取行为污染业务指标
if r.URL.Path == "/metrics" || r.URL.Path == "/healthz" || r.URL.Path == "/readyz" {
next.ServeHTTP(w, r)
return
}
m.HTTPInFlight.Inc()
defer m.HTTPInFlight.Dec()
ww := &statusWriter{ResponseWriter: w, status: 200}
start := time.Now()
next.ServeHTTP(ww, r)
route := chi.RouteContext(r.Context()).RoutePattern()
if route == "" {
route = "unmatched"
}
status := strconv.Itoa(ww.status)
elapsed := time.Since(start).Seconds()
m.HTTPRequests.WithLabelValues(r.Method, route, status).Inc()
m.HTTPDuration.WithLabelValues(r.Method, route, status).Observe(elapsed)
m.HTTPRespSize.WithLabelValues(route).Observe(float64(ww.written))
})
}
// CacheStats 把 metrics 注册表适配成 cache.Stats 接口。
// 放在 metrics 包里而不在 cache 包里,保证依赖方向单向:
// cache(底层)不 import metrics(上层)。
type CacheStats struct{ Reg *Registry }
func (c CacheStats) Hit() { c.Reg.CacheHits.Inc() }
func (c CacheStats) Miss() { c.Reg.CacheMisses.Inc() }
func (c CacheStats) Error() { c.Reg.CacheErrors.Inc() }
func (c CacheStats) FlightMerged() { c.Reg.CacheFlight.WithLabelValues("article").Inc() }
// RateLimited 适配 middleware.RateLimiter 的接口
func (r *Registry) RateLimited() { r.RateLimitedTotal.Inc() }
// AuthFailed 适配 middleware.Auth 的接口
func (r *Registry) AuthFailed(reason string) {
r.AuthFailures.WithLabelValues(reason).Inc()
}
// statusWriter 包装 ResponseWriter 以捕获状态码
type statusWriter struct {
http.ResponseWriter
status int
written int
}
func (w *statusWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func (w *statusWriter) Write(b []byte) (int, error) {
n, err := w.ResponseWriter.Write(b)
w.written += n
return n, err
}