Files
shaw 38903b6d1d fix(accounts): 上游分组文字入库前校验,include 支持多值
- 上游分组名称/描述与探测快照、倍率在同一条 UPDATE 中写库。gjson 对未转义
  字符串返回原始字节,非法 UTF-8 会被 PostgreSQL 以 22021 拒绝,导致整条
  UPDATE 失败:快照与倍率都写不进去,next_probe_at 不推进,账号每个调度
  周期都被重试并挤占探测名额。现在非法 UTF-8 只丢弃对应字段
- 名称拒绝控制字符,备注仅保留换行与制表符,避免上游向管理端写入
  转义序列等不可见内容
- /v1/sub2api/billing 的 include 按逗号分隔列表解析并支持重复参数,
  后续新增可选段时不会让 include=group 失效
2026-11-24 08:58:55 +08:00

137 lines
5.1 KiB
Go

package handler
import (
"log/slog"
"net/http"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
const keyBillingInfoSchemaVersion = 1
type keyBillingInfoResponse struct {
*service.BillingGroupInfo
Object string `json:"object"`
SchemaVersion int `json:"schema_version"`
BillingScope string `json:"billing_scope"`
GroupRateMultiplier float64 `json:"group_rate_multiplier"`
UserRateMultiplier *float64 `json:"user_rate_multiplier,omitempty"`
ResolvedRateMultiplier float64 `json:"resolved_rate_multiplier"`
PeakRateEnabled bool `json:"peak_rate_enabled"`
PeakStart *string `json:"peak_start,omitempty"`
PeakEnd *string `json:"peak_end,omitempty"`
PeakRateMultiplier *float64 `json:"peak_rate_multiplier,omitempty"`
AppliedPeakMultiplier *float64 `json:"applied_peak_multiplier,omitempty"`
EffectiveRateMultiplier float64 `json:"effective_rate_multiplier"`
Timezone *string `json:"timezone,omitempty"`
ObservedAt time.Time `json:"observed_at"`
}
// KeyBillingInfo returns the token billing multiplier effective for the authenticated API key.
// GET /v1/sub2api/billing (include=group also returns the group's display name and description).
func (h *GatewayHandler) KeyBillingInfo(c *gin.Context) {
apiKey, ok := middleware2.GetAPIKeyFromContext(c)
if !ok {
h.errorResponse(c, http.StatusUnauthorized, "authentication_error", "Invalid API key")
return
}
if h.cfg != nil && h.cfg.RunMode == config.RunModeSimple {
h.errorResponse(c, http.StatusNotFound, "not_found_error", "Billing information is not supported in simple mode")
return
}
if apiKey.GroupID == nil {
h.errorResponse(c, http.StatusForbidden, "permission_error", "API key is not assigned to a group")
return
}
if apiKey.Group == nil {
h.errorResponse(c, http.StatusInternalServerError, "api_error", "Billing information is unavailable")
return
}
resolvedRate, ok := h.resolveKeyBillingRate(c, apiKey)
if !ok {
h.errorResponse(c, http.StatusInternalServerError, "api_error", "Billing information is unavailable")
return
}
info := buildKeyBillingInfo(apiKey, resolvedRate, timezone.Now())
if keyBillingIncludes(c, "group") {
group, err := h.apiKeyService.GetBillingGroupInfo(c.Request.Context(), *apiKey.GroupID, c.GetHeader("Accept-Language"))
if err != nil {
slog.WarnContext(c.Request.Context(), "billing group display text unavailable", "group_id", *apiKey.GroupID, "error", err)
} else {
info.BillingGroupInfo = group
}
}
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusOK, info)
}
// keyBillingIncludes reports whether the caller asked for an optional response section.
// include is a comma-separated list and may be repeated, so a client can request several
// sections in one call (include=group,other or include=group&include=other); unknown sections
// are ignored. An exact-match comparison would stop returning the group as soon as a second
// section exists.
func keyBillingIncludes(c *gin.Context, section string) bool {
for _, value := range c.QueryArray("include") {
for _, item := range strings.Split(value, ",") {
if strings.TrimSpace(item) == section {
return true
}
}
}
return false
}
func (h *GatewayHandler) resolveKeyBillingRate(c *gin.Context, apiKey *service.APIKey) (float64, bool) {
groupRate := apiKey.Group.RateMultiplier
switch apiKey.Group.Platform {
case service.PlatformOpenAI, service.PlatformGrok:
if h.openAIGatewayService == nil {
return 0, false
}
return h.openAIGatewayService.ResolveUserGroupRateMultiplier(c.Request.Context(), apiKey.UserID, *apiKey.GroupID, groupRate), true
default:
if h.gatewayService == nil {
return 0, false
}
return h.gatewayService.ResolveUserGroupRateMultiplier(c.Request.Context(), apiKey.UserID, *apiKey.GroupID, groupRate), true
}
}
func buildKeyBillingInfo(apiKey *service.APIKey, resolvedRate float64, now time.Time) keyBillingInfoResponse {
groupRate := apiKey.Group.RateMultiplier
var userRate *float64
if resolvedRate != groupRate {
userRate = &resolvedRate
}
appliedPeak := apiKey.Group.PeakMultiplierAt(now)
response := keyBillingInfoResponse{
Object: "sub2api.key_billing",
SchemaVersion: keyBillingInfoSchemaVersion,
BillingScope: "token",
GroupRateMultiplier: groupRate,
UserRateMultiplier: userRate,
ResolvedRateMultiplier: resolvedRate,
PeakRateEnabled: apiKey.Group.PeakRateEnabled,
EffectiveRateMultiplier: resolvedRate * appliedPeak,
ObservedAt: now.UTC(),
}
if apiKey.Group.PeakRateEnabled {
response.PeakStart = &apiKey.Group.PeakStart
response.PeakEnd = &apiKey.Group.PeakEnd
response.PeakRateMultiplier = &apiKey.Group.PeakRateMultiplier
response.AppliedPeakMultiplier = &appliedPeak
tz := timezone.Location().String()
response.Timezone = &tz
}
return response
}