feat(usage): add in-memory usage statistics tracking and API endpoint

- Introduced in-memory request statistics aggregation in `LoggerPlugin`.
- Added new structures for detailed metrics collection (e.g., token breakdown, request success/failure).
- Implemented `/usage` management API endpoint for retrieving aggregated statistics.
- Updated management handlers to support the new usage statistics functionality.
- Enhanced documentation to describe the usage metrics API.
This commit is contained in:
Luis Pater
2025-09-25 01:06:02 +08:00
parent 0db0b03db9
commit 19609db13c
7 changed files with 434 additions and 40 deletions

View File

@@ -11,6 +11,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
"golang.org/x/crypto/bcrypt"
)
@@ -29,11 +30,18 @@ type Handler struct {
attemptsMu sync.Mutex
failedAttempts map[string]*attemptInfo // keyed by client IP
authManager *coreauth.Manager
usageStats *usage.RequestStatistics
}
// NewHandler creates a new management handler instance.
func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Manager) *Handler {
return &Handler{cfg: cfg, configFilePath: configFilePath, failedAttempts: make(map[string]*attemptInfo), authManager: manager}
return &Handler{
cfg: cfg,
configFilePath: configFilePath,
failedAttempts: make(map[string]*attemptInfo),
authManager: manager,
usageStats: usage.GetRequestStatistics(),
}
}
// SetConfig updates the in-memory config reference when the server hot-reloads.
@@ -42,6 +50,9 @@ func (h *Handler) SetConfig(cfg *config.Config) { h.cfg = cfg }
// SetAuthManager updates the auth manager reference used by management endpoints.
func (h *Handler) SetAuthManager(manager *coreauth.Manager) { h.authManager = manager }
// SetUsageStatistics allows replacing the usage statistics reference.
func (h *Handler) SetUsageStatistics(stats *usage.RequestStatistics) { h.usageStats = stats }
// Middleware enforces access control for management endpoints.
// All requests (local and remote) require a valid management key.
// Additionally, remote access requires allow-remote-management=true.

View File

@@ -0,0 +1,17 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
)
// GetUsageStatistics returns the in-memory request statistics snapshot.
func (h *Handler) GetUsageStatistics(c *gin.Context) {
var snapshot usage.StatisticsSnapshot
if h != nil && h.usageStats != nil {
snapshot = h.usageStats.Snapshot()
}
c.JSON(http.StatusOK, gin.H{"usage": snapshot})
}