-
-
Notifications
You must be signed in to change notification settings - Fork 7.8k
feat: 新增自用模式下的 API 密钥统计功能 #4959
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SHLE1
wants to merge
5
commits into
QuantumNous:main
Choose a base branch
from
SHLE1:codex/api-key-status
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d16d36b
feat: 添加 API Key 使用统计功能及相关图表
SHLE1 119f0fe
fix: 调整侧边栏菜单的间距防止粘连
SHLE1 83eb895
feat: 仅在自用模式下显示 API 密钥统计功能并添加开关
SHLE1 c1142dd
fix: address api key stats review feedback
SHLE1 3c36d96
Merge remote-tracking branch 'upstream/main' into codex/api-key-status
SHLE1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| package controller | ||
|
|
||
| import ( | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/model" | ||
| "github.com/QuantumNous/new-api/setting/operation_setting" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func withApiKeyStatsSettings(t *testing.T, selfUseModeEnabled, apiKeyStatsEnabled bool) { | ||
| t.Helper() | ||
|
|
||
| originalSelfUseModeEnabled := operation_setting.SelfUseModeEnabled | ||
| originalApiKeyStatsEnabled := common.ApiKeyStatsEnabled | ||
| operation_setting.SelfUseModeEnabled = selfUseModeEnabled | ||
| common.ApiKeyStatsEnabled = apiKeyStatsEnabled | ||
| t.Cleanup(func() { | ||
| operation_setting.SelfUseModeEnabled = originalSelfUseModeEnabled | ||
| common.ApiKeyStatsEnabled = originalApiKeyStatsEnabled | ||
| }) | ||
| } | ||
|
|
||
| func performTokenStatsRequest(handler gin.HandlerFunc) *httptest.ResponseRecorder { | ||
| recorder := httptest.NewRecorder() | ||
| ctx, _ := gin.CreateTestContext(recorder) | ||
| req := httptest.NewRequest(http.MethodGet, "/api/log/stat/tokens", nil) | ||
| ctx.Request = req | ||
| handler(ctx) | ||
| return recorder | ||
| } | ||
|
|
||
| func TestGetLogStatsByTokenRejectsWhenApiKeyStatsDisabled(t *testing.T) { | ||
| gin.SetMode(gin.TestMode) | ||
| withApiKeyStatsSettings(t, true, false) | ||
|
|
||
| recorder := performTokenStatsRequest(GetLogStatsByToken) | ||
|
|
||
| require.Equal(t, http.StatusForbidden, recorder.Code) | ||
| require.Contains(t, recorder.Body.String(), "api key statistics is disabled") | ||
| } | ||
|
|
||
| func TestGetLogStatsByTokenRejectsWhenSelfUseModeDisabled(t *testing.T) { | ||
| gin.SetMode(gin.TestMode) | ||
| withApiKeyStatsSettings(t, false, true) | ||
|
|
||
| recorder := performTokenStatsRequest(GetLogStatsByToken) | ||
|
|
||
| require.Equal(t, http.StatusForbidden, recorder.Code) | ||
| require.Contains(t, recorder.Body.String(), "api key statistics is disabled") | ||
| } | ||
|
|
||
| func TestGetLogStatsByTokenAllowsWhenEnabled(t *testing.T) { | ||
| gin.SetMode(gin.TestMode) | ||
| withApiKeyStatsSettings(t, true, true) | ||
| db := setupModelListControllerTestDB(t) | ||
| require.NoError(t, db.AutoMigrate(&model.Log{})) | ||
|
|
||
| recorder := performTokenStatsRequest(GetLogStatsByToken) | ||
|
|
||
| require.Equal(t, http.StatusOK, recorder.Code) | ||
| require.Contains(t, recorder.Body.String(), `"success":true`) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| package model | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| ) | ||
|
|
||
| const ( | ||
| tokenStatsDefaultRangeSeconds = 24 * 60 * 60 | ||
| tokenStatsMaxRangeSeconds = 30 * 24 * 60 * 60 | ||
| ) | ||
|
|
||
| // TokenQuotaData is hourly aggregated usage data by API key. | ||
| type TokenQuotaData struct { | ||
| TokenId int `json:"token_id"` | ||
| TokenName string `json:"token_name"` | ||
| CreatedAt int64 `json:"created_at"` | ||
| Count int `json:"count"` | ||
| Quota int `json:"quota"` | ||
| TokenUsed int `json:"token_used"` | ||
| } | ||
|
|
||
| // GetLogStatsByToken aggregates consume logs by API key and hour. | ||
| // userId = 0 returns all users' data; userId > 0 limits data to that user. | ||
| func GetLogStatsByToken(userId int, startTime, endTime int64) ([]*TokenQuotaData, error) { | ||
| var results []*TokenQuotaData | ||
|
|
||
| startTime, endTime, err := normalizeTokenStatsTimeRange(startTime, endTime, time.Now().Unix()) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| query := LOG_DB.Table("logs"). | ||
| Select(`token_id, | ||
| token_name, | ||
| (created_at - created_at % 3600) AS created_at, | ||
| COUNT(*) AS count, | ||
| COALESCE(SUM(quota), 0) AS quota, | ||
| COALESCE(SUM(prompt_tokens), 0) + COALESCE(SUM(completion_tokens), 0) AS token_used`). | ||
| Where("type = ?", LogTypeConsume). | ||
| Where("token_id != 0"). | ||
| Where("token_name != ''"). | ||
| Group("token_id, token_name, (created_at - created_at % 3600)"). | ||
| Order("(created_at - created_at % 3600)") | ||
|
|
||
| if userId > 0 { | ||
| query = query.Where("user_id = ?", userId) | ||
| } | ||
| if startTime != 0 { | ||
| query = query.Where("created_at >= ?", startTime) | ||
| } | ||
| if endTime != 0 { | ||
| query = query.Where("created_at <= ?", endTime) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| if err := query.Scan(&results).Error; err != nil { | ||
| common.SysError("failed to query token quota data: " + err.Error()) | ||
| return nil, err | ||
| } | ||
| return results, nil | ||
| } | ||
|
|
||
| func normalizeTokenStatsTimeRange(startTime, endTime, now int64) (int64, int64, error) { | ||
| if startTime == 0 && endTime == 0 { | ||
| endTime = now | ||
| startTime = endTime - tokenStatsDefaultRangeSeconds | ||
| } else if endTime == 0 { | ||
| endTime = now | ||
| } else if startTime == 0 { | ||
| startTime = endTime - tokenStatsMaxRangeSeconds | ||
| } | ||
|
|
||
| if endTime < startTime { | ||
| return 0, 0, fmt.Errorf("invalid time range: end_timestamp < start_timestamp") | ||
| } | ||
| if endTime-startTime > tokenStatsMaxRangeSeconds { | ||
| startTime = endTime - tokenStatsMaxRangeSeconds | ||
| } | ||
| return startTime, endTime, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package model | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestNormalizeTokenStatsTimeRangeDefaultsToRecentDay(t *testing.T) { | ||
| startTime, endTime, err := normalizeTokenStatsTimeRange(0, 0, 1_700_000_000) | ||
| require.NoError(t, err) | ||
| require.Equal(t, int64(1_700_000_000), endTime) | ||
| require.Equal(t, int64(1_700_000_000-tokenStatsDefaultRangeSeconds), startTime) | ||
| } | ||
|
|
||
| func TestNormalizeTokenStatsTimeRangeFillsMissingBoundary(t *testing.T) { | ||
| startTime, endTime, err := normalizeTokenStatsTimeRange(1_699_999_000, 0, 1_700_000_000) | ||
| require.NoError(t, err) | ||
| require.Equal(t, int64(1_699_999_000), startTime) | ||
| require.Equal(t, int64(1_700_000_000), endTime) | ||
|
|
||
| startTime, endTime, err = normalizeTokenStatsTimeRange(0, 1_700_000_000, 1_700_000_100) | ||
| require.NoError(t, err) | ||
| require.Equal(t, int64(1_700_000_000-tokenStatsMaxRangeSeconds), startTime) | ||
| require.Equal(t, int64(1_700_000_000), endTime) | ||
| } | ||
|
|
||
| func TestNormalizeTokenStatsTimeRangeCapsRange(t *testing.T) { | ||
| startTime, endTime, err := normalizeTokenStatsTimeRange(1_600_000_000, 1_700_000_000, 1_700_000_000) | ||
| require.NoError(t, err) | ||
| require.Equal(t, int64(1_700_000_000-tokenStatsMaxRangeSeconds), startTime) | ||
| require.Equal(t, int64(1_700_000_000), endTime) | ||
| } | ||
|
|
||
| func TestNormalizeTokenStatsTimeRangeRejectsInvalidRange(t *testing.T) { | ||
| _, _, err := normalizeTokenStatsTimeRange(1_700_000_001, 1_700_000_000, 1_700_000_000) | ||
| require.Error(t, err) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.