|
| 1 | +// Package metrics provides handlers for the metrics endpoints. |
| 2 | +package metrics |
| 3 | + |
| 4 | +import ( |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "sort" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/gin-gonic/gin" |
| 12 | + "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" |
| 13 | +) |
| 14 | + |
| 15 | +// Handler holds the dependencies for the metrics handlers. |
| 16 | +type Handler struct { |
| 17 | + Stats *usage.RequestStatistics |
| 18 | +} |
| 19 | + |
| 20 | +// NewHandler creates a new metrics handler. |
| 21 | +func NewHandler(stats *usage.RequestStatistics) *Handler { |
| 22 | + return &Handler{Stats: stats} |
| 23 | +} |
| 24 | + |
| 25 | +// MetricsResponse is the top-level struct for the metrics endpoint response. |
| 26 | +type MetricsResponse struct { |
| 27 | + Totals TotalsMetrics `json:"totals"` |
| 28 | + ByModel []ModelMetrics `json:"by_model"` |
| 29 | + Timeseries []TimeseriesBucket `json:"timeseries"` |
| 30 | +} |
| 31 | + |
| 32 | +// TotalsMetrics holds the aggregated totals for the queried period. |
| 33 | +type TotalsMetrics struct { |
| 34 | + Tokens int64 `json:"tokens"` |
| 35 | + Requests int64 `json:"requests"` |
| 36 | +} |
| 37 | + |
| 38 | +// ModelMetrics holds the aggregated metrics for a specific model. |
| 39 | +type ModelMetrics struct { |
| 40 | + Model string `json:"model"` |
| 41 | + Tokens int64 `json:"tokens"` |
| 42 | + Requests int64 `json:"requests"` |
| 43 | +} |
| 44 | + |
| 45 | +// TimeseriesBucket holds the aggregated metrics for a specific time bucket. |
| 46 | +type TimeseriesBucket struct { |
| 47 | + BucketStart string `json:"bucket_start"` // ISO 8601 format |
| 48 | + Tokens int64 `json:"tokens"` |
| 49 | + Requests int64 `json:"requests"` |
| 50 | +} |
| 51 | + |
| 52 | +// GetMetrics is the handler for the /_qs/metrics endpoint. |
| 53 | +func (h *Handler) GetMetrics(c *gin.Context) { |
| 54 | + fromStr := c.Query("from") |
| 55 | + toStr := c.Query("to") |
| 56 | + modelFilter := c.Query("model") |
| 57 | + |
| 58 | + var fromTime, toTime time.Time |
| 59 | + var err error |
| 60 | + |
| 61 | + // Default to last 24 hours if no time range is given |
| 62 | + if fromStr == "" && toStr == "" { |
| 63 | + toTime = time.Now() |
| 64 | + fromTime = toTime.Add(-24 * time.Hour) |
| 65 | + } else { |
| 66 | + if fromStr != "" { |
| 67 | + fromTime, err = time.Parse(time.RFC3339, fromStr) |
| 68 | + if err != nil { |
| 69 | + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid 'from' timestamp format"}) |
| 70 | + return |
| 71 | + } |
| 72 | + } |
| 73 | + if toStr != "" { |
| 74 | + toTime, err = time.Parse(time.RFC3339, toStr) |
| 75 | + if err != nil { |
| 76 | + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid 'to' timestamp format"}) |
| 77 | + return |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + snapshot := h.Stats.Snapshot() |
| 83 | + |
| 84 | + modelMetricsMap := make(map[string]*ModelMetrics) |
| 85 | + timeseriesMap := make(map[time.Time]*TimeseriesBucket) |
| 86 | + var totalTokens int64 |
| 87 | + var totalRequests int64 |
| 88 | + |
| 89 | + for _, apiSnapshot := range snapshot.APIs { |
| 90 | + for modelName, modelSnapshot := range apiSnapshot.Models { |
| 91 | + if modelFilter != "" && modelFilter != modelName { |
| 92 | + continue |
| 93 | + } |
| 94 | + |
| 95 | + for _, detail := range modelSnapshot.Details { |
| 96 | + if !fromTime.IsZero() && detail.Timestamp.Before(fromTime) { |
| 97 | + continue |
| 98 | + } |
| 99 | + if !toTime.IsZero() && detail.Timestamp.After(toTime) { |
| 100 | + continue |
| 101 | + } |
| 102 | + |
| 103 | + totalRequests++ |
| 104 | + totalTokens += detail.Tokens.TotalTokens |
| 105 | + |
| 106 | + if _, ok := modelMetricsMap[modelName]; !ok { |
| 107 | + modelMetricsMap[modelName] = &ModelMetrics{Model: modelName} |
| 108 | + } |
| 109 | + modelMetricsMap[modelName].Requests++ |
| 110 | + modelMetricsMap[modelName].Tokens += detail.Tokens.TotalTokens |
| 111 | + |
| 112 | + bucket := detail.Timestamp.Truncate(time.Hour) |
| 113 | + if _, ok := timeseriesMap[bucket]; !ok { |
| 114 | + timeseriesMap[bucket] = &TimeseriesBucket{BucketStart: bucket.Format(time.RFC3339)} |
| 115 | + } |
| 116 | + timeseriesMap[bucket].Requests++ |
| 117 | + timeseriesMap[bucket].Tokens += detail.Tokens.TotalTokens |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + resp := MetricsResponse{ |
| 123 | + Totals: TotalsMetrics{ |
| 124 | + Tokens: totalTokens, |
| 125 | + Requests: totalRequests, |
| 126 | + }, |
| 127 | + ByModel: make([]ModelMetrics, 0, len(modelMetricsMap)), |
| 128 | + Timeseries: make([]TimeseriesBucket, 0, len(timeseriesMap)), |
| 129 | + } |
| 130 | + |
| 131 | + for _, mm := range modelMetricsMap { |
| 132 | + resp.ByModel = append(resp.ByModel, *mm) |
| 133 | + } |
| 134 | + |
| 135 | + sort.Slice(resp.ByModel, func(i, j int) bool { |
| 136 | + return resp.ByModel[i].Model < resp.ByModel[j].Model |
| 137 | + }) |
| 138 | + |
| 139 | + for _, tb := range timeseriesMap { |
| 140 | + resp.Timeseries = append(resp.Timeseries, *tb) |
| 141 | + } |
| 142 | + |
| 143 | + sort.Slice(resp.Timeseries, func(i, j int) bool { |
| 144 | + return resp.Timeseries[i].BucketStart < resp.Timeseries[j].BucketStart |
| 145 | + }) |
| 146 | + |
| 147 | + if jsonData, err := json.MarshalIndent(resp, "", " "); err == nil { |
| 148 | + fmt.Println(string(jsonData)) |
| 149 | + } |
| 150 | + |
| 151 | + c.JSON(http.StatusOK, resp) |
| 152 | +} |
0 commit comments