feat(stats): add usage stats and quota reset

This commit is contained in:
zenfun
2025-12-19 21:50:28 +08:00
parent 524f8c5a4e
commit ac9f0cd0a7
9 changed files with 713 additions and 3 deletions

View File

@@ -0,0 +1,52 @@
package service
import (
"context"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
)
func TestStatsService_KeyRealtimeStats(t *testing.T) {
t.Parallel()
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
svc := NewStatsService(rdb)
mr.Set("key:stats:hash:requests", "3")
mr.Set("key:stats:hash:tokens", "42")
mr.Set("key:stats:hash:last_access", "1700000000")
stats, err := svc.GetKeyRealtimeStats(context.Background(), "hash")
if err != nil {
t.Fatalf("GetKeyRealtimeStats: %v", err)
}
if stats.Requests != 3 || stats.Tokens != 42 {
t.Fatalf("unexpected stats: %+v", stats)
}
if stats.LastAccessedAt == nil || !stats.LastAccessedAt.Equal(time.Unix(1700000000, 0).UTC()) {
t.Fatalf("unexpected last access: %+v", stats.LastAccessedAt)
}
}
func TestStatsService_MasterRealtimeStats(t *testing.T) {
t.Parallel()
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
svc := NewStatsService(rdb)
mr.Set("master:stats:99:requests", "7")
mr.Set("master:stats:99:tokens", "100")
stats, err := svc.GetMasterRealtimeStats(context.Background(), 99)
if err != nil {
t.Fatalf("GetMasterRealtimeStats: %v", err)
}
if stats.Requests != 7 || stats.Tokens != 100 {
t.Fatalf("unexpected stats: %+v", stats)
}
}