-
Notifications
You must be signed in to change notification settings - Fork 11.1k
feat(channel): add balance query for New API channels #6737
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
lelinhomafx4021-creator
wants to merge
3
commits into
QuantumNous:main
Choose a base branch
from
lelinhomafx4021-creator:pr/newapi-upstream-balance
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
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| package controller | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/model" | ||
| "github.com/shopspring/decimal" | ||
| ) | ||
|
|
||
| type newAPITokenUsageResponse struct { | ||
| Code bool `json:"code"` | ||
| Data *newAPITokenUsageData `json:"data"` | ||
| } | ||
|
|
||
| type newAPITokenUsageData struct { | ||
| TotalAvailable *decimal.Decimal `json:"total_available"` | ||
| UnlimitedQuota bool `json:"unlimited_quota"` | ||
| ExpiresAt int64 `json:"expires_at"` | ||
| } | ||
|
|
||
| type newAPIStatusResponse struct { | ||
| Success bool `json:"success"` | ||
| Data *newAPIStatusData `json:"data"` | ||
| } | ||
|
|
||
| type newAPIStatusData struct { | ||
| QuotaPerUnit *decimal.Decimal `json:"quota_per_unit"` | ||
| QuotaDisplayType string `json:"quota_display_type"` | ||
| USDExchangeRate *decimal.Decimal `json:"usd_exchange_rate"` | ||
| CustomCurrencySymbol string `json:"custom_currency_symbol"` | ||
| CustomCurrencyExchangeRate *decimal.Decimal `json:"custom_currency_exchange_rate"` | ||
| } | ||
|
|
||
| func updateChannelNewAPIBalance(channel *model.Channel) (*model.ChannelBalanceInfo, *float64, error) { | ||
| usageBody, err := getNewAPIChannelResponse(channel, "/api/usage/token/") | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| var usage newAPITokenUsageResponse | ||
| if err := common.Unmarshal(usageBody, &usage); err != nil { | ||
| return nil, nil, fmt.Errorf("invalid New API token usage response: %w", err) | ||
| } | ||
| if !usage.Code || usage.Data == nil || usage.Data.TotalAvailable == nil { | ||
| return nil, nil, errors.New("New API token usage response is invalid") | ||
| } | ||
| if usage.Data.ExpiresAt > 0 && usage.Data.ExpiresAt < time.Now().Unix() { | ||
| return nil, nil, errors.New("New API token is expired") | ||
| } | ||
|
|
||
| var status *newAPIStatusData | ||
| if statusBody, statusErr := getNewAPIChannelResponse(channel, "/api/status"); statusErr == nil { | ||
| var parsed newAPIStatusResponse | ||
| if common.Unmarshal(statusBody, &parsed) == nil && parsed.Success && parsed.Data != nil { | ||
| status = parsed.Data | ||
| } | ||
| } | ||
| info, legacyBalance := normalizeNewAPIBalance(*usage.Data.TotalAvailable, usage.Data.UnlimitedQuota, status) | ||
| if err := channel.UpdateBalanceInfo(info, legacyBalance); err != nil { | ||
| return nil, nil, err | ||
| } | ||
| return &info, legacyBalance, nil | ||
| } | ||
|
|
||
| func getNewAPIChannelResponse(channel *model.Channel, path string) ([]byte, error) { | ||
| baseURL, err := url.Parse(strings.TrimSpace(channel.GetBaseURL())) | ||
| if err != nil || (baseURL.Scheme != "http" && baseURL.Scheme != "https") || baseURL.Host == "" || baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" { | ||
| return nil, errors.New("invalid New API channel base URL") | ||
| } | ||
| baseURL.Path = strings.TrimRight(baseURL.Path, "/") + path | ||
| baseURL.RawPath = "" | ||
| return GetResponseBody(http.MethodGet, baseURL.String(), channel, GetAuthHeader(channel.Key)) | ||
| } | ||
|
|
||
| func normalizeNewAPIBalance(remaining decimal.Decimal, unlimited bool, status *newAPIStatusData) (model.ChannelBalanceInfo, *float64) { | ||
| if !unlimited && remaining.IsNegative() { | ||
| remaining = decimal.Zero | ||
| } | ||
| info := model.ChannelBalanceInfo{ | ||
| Remaining: remaining.String(), | ||
| Unit: model.ChannelBalanceUnitCredits, | ||
| DisplayUnit: "credits", | ||
| Unlimited: unlimited, | ||
| UpdatedAt: common.GetTimestamp(), | ||
| } | ||
| if unlimited { | ||
| info.Remaining = "" | ||
| } | ||
| if status == nil || status.QuotaPerUnit == nil || !status.QuotaPerUnit.IsPositive() { | ||
| return info, nil | ||
| } | ||
|
|
||
| convert := func(multiplier decimal.Decimal) decimal.Decimal { | ||
| return remaining.Div(*status.QuotaPerUnit).Mul(multiplier) | ||
| } | ||
| var legacyBalance *float64 | ||
| switch strings.ToUpper(status.QuotaDisplayType) { | ||
| case "USD": | ||
| amount := convert(decimal.NewFromInt(1)) | ||
| info.Unit, info.Currency, info.DisplayUnit = model.ChannelBalanceUnitMoney, "USD", "$" | ||
| if !unlimited { | ||
| info.Remaining = amount.String() | ||
| value := amount.InexactFloat64() | ||
| legacyBalance = &value | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
| case "CNY": | ||
| if status.USDExchangeRate != nil && status.USDExchangeRate.IsPositive() { | ||
| amount := convert(*status.USDExchangeRate) | ||
| info.Unit, info.Currency, info.DisplayUnit = model.ChannelBalanceUnitMoney, "CNY", "¥" | ||
| if !unlimited { | ||
| info.Remaining = amount.String() | ||
| } | ||
| } | ||
| case "TOKENS": | ||
| info.Unit, info.DisplayUnit = model.ChannelBalanceUnitTokens, "tokens" | ||
| case "CUSTOM": | ||
| if status.CustomCurrencyExchangeRate != nil && status.CustomCurrencyExchangeRate.IsPositive() { | ||
| amount := convert(*status.CustomCurrencyExchangeRate) | ||
| info.Unit, info.Currency = model.ChannelBalanceUnitMoney, "CUSTOM" | ||
| info.DisplayUnit = strings.TrimSpace(status.CustomCurrencySymbol) | ||
| if info.DisplayUnit == "" { | ||
| info.DisplayUnit = "¤" | ||
| } | ||
| if !unlimited { | ||
| info.Remaining = amount.String() | ||
| } | ||
| } | ||
| } | ||
| return info, legacyBalance | ||
| } | ||
|
|
||
| func newAPIBalanceExhausted(info *model.ChannelBalanceInfo) bool { | ||
| if info == nil || info.Unlimited || info.Remaining == "" { | ||
| return false | ||
| } | ||
| remaining, err := decimal.NewFromString(info.Remaining) | ||
| return err == nil && !remaining.IsPositive() | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Close failed upstream response bodies.
GetResponseBodyreturns before it closesres.Bodywhen the upstream returns a non-200 status. This new flow calls it for/api/status, then intentionally ignores that error. Repeated status failures can retain connections and file descriptors.Close the body on every path in
GetResponseBody.Proposed fix
res, err := client.Do(req) if err != nil { return nil, err } +defer func() { + _ = res.Body.Close() +}() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("status code: %d", res.StatusCode) } body, err := io.ReadAll(res.Body) if err != nil { return nil, err } -err = res.Body.Close() -if err != nil { - return nil, err -} return body, nil🤖 Prompt for AI Agents