|
1 | | -// internal/metrics/prometheus.go |
| 1 | +package metrics |
| 2 | + |
| 3 | +import ( |
| 4 | + "time" |
| 5 | + |
| 6 | + "github.com/prometheus/client_golang/prometheus" |
| 7 | + "github.com/prometheus/client_golang/prometheus/promauto" |
| 8 | +) |
| 9 | + |
| 10 | +var ( |
| 11 | + requestsTotal = promauto.NewCounterVec(prometheus.CounterOpts{ |
| 12 | + Name: "ratelimiter_requests_total", |
| 13 | + Help: "Total rate-limit decisions, labelled by api_key and status (allowed|rejected)", |
| 14 | + }, []string{"api_key", "status"}) |
| 15 | + |
| 16 | + decisionLatency = promauto.NewHistogram(prometheus.HistogramOpts{ |
| 17 | + Name: "ratelimiter_decision_latency_seconds", |
| 18 | + Help: "E2E latency of AllowRequest and Redis round-trip", |
| 19 | + Buckets: []float64{0.001, 0.005, 0.010, 0.025, 0.050, 0.100}, |
| 20 | + }) |
| 21 | + |
| 22 | + redisCommandDuration = promauto.NewHistogram(prometheus.HistogramOpts{ |
| 23 | + Name: "ratelimiter_redis_command_duration_seconds", |
| 24 | + Help: "Latency of Redis EVALSHA commands", |
| 25 | + Buckets: []float64{0.0005, 0.001, 0.005, 0.010, 0.025}, |
| 26 | + }) |
| 27 | + |
| 28 | + redisErrors = promauto.NewCounter(prometheus.CounterOpts{ |
| 29 | + Name: "ratelimiter_redis_errors_total", |
| 30 | + Help: "Total Redis errors encountered. Non-zero triggers fail-open behaviour.", |
| 31 | + }) |
| 32 | +) |
| 33 | + |
| 34 | +// Register is a no-op; promauto registers automatically on package import. |
| 35 | +// Call it in main to ensure this package is imported and metrics are registered. |
| 36 | +func Register() {} |
| 37 | + |
| 38 | +func RecordDecision(apiKey string, allowed bool) { |
| 39 | + status := "rejected" |
| 40 | + if allowed { |
| 41 | + status = "allowed" |
| 42 | + } |
| 43 | + requestsTotal.WithLabelValues(apiKey, status).Inc() |
| 44 | +} |
| 45 | + |
| 46 | +func RecordRedisLatency(d time.Duration) { |
| 47 | + redisCommandDuration.Observe(d.Seconds()) |
| 48 | +} |
| 49 | + |
| 50 | +func RecordDecisionLatency(d time.Duration) { |
| 51 | + decisionLatency.Observe(d.Seconds()) |
| 52 | +} |
| 53 | + |
| 54 | +func RecordRedisError() { |
| 55 | + redisErrors.Inc() |
| 56 | +} |
0 commit comments