feat: enhance API key usage grouping with base URL inclusion

- Updated `GetAPIKeyUsage` to group API key usage by "base_url|api_key" composite keys.
- Adjusted logic to handle `base_url` extraction from auth attributes.
- Revised unit tests to validate "base_url|api_key" grouping behavior.
This commit is contained in:
Luis Pater
2026-05-02 02:20:49 +08:00
parent e37f3be0bf
commit 8c2f1a80d3
2 changed files with 18 additions and 8 deletions
@@ -35,7 +35,7 @@ func mergeRecentRequestBuckets(dst, src []coreauth.RecentRequestBucket) []coreau
}
// GetAPIKeyUsage returns recent request buckets for all in-memory api_key auths,
// grouped by provider and keyed by the raw api-key value.
// grouped by provider and keyed by "base_url|api_key".
func (h *Handler) GetAPIKeyUsage(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler not initialized"})
@@ -64,6 +64,14 @@ func (h *Handler) GetAPIKeyUsage(c *gin.Context) {
if apiKey == "" {
continue
}
baseURL := ""
if auth.Attributes != nil {
baseURL = strings.TrimSpace(auth.Attributes["base_url"])
if baseURL == "" {
baseURL = strings.TrimSpace(auth.Attributes["base-url"])
}
}
compositeKey := baseURL + "|" + apiKey
provider := strings.ToLower(strings.TrimSpace(auth.Provider))
if provider == "" {
provider = "unknown"
@@ -75,11 +83,11 @@ func (h *Handler) GetAPIKeyUsage(c *gin.Context) {
providerBucket = make(map[string][]coreauth.RecentRequestBucket)
out[provider] = providerBucket
}
if existing, exists := providerBucket[apiKey]; exists {
providerBucket[apiKey] = mergeRecentRequestBuckets(existing, recent)
if existing, exists := providerBucket[compositeKey]; exists {
providerBucket[compositeKey] = mergeRecentRequestBuckets(existing, recent)
continue
}
providerBucket[apiKey] = recent
providerBucket[compositeKey] = recent
}
c.JSON(http.StatusOK, out)