mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
feat(accounts): 按账号自动同步上游分组名称与备注
This commit is contained in:
1 parent
a95c9e2631
commit
03aa05fd9f
26 files changed
+433
-162
No files matched your search
@@ -136,17 +136,16 @@ type AccountDuplicateRepository interface {
|
||||
CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error
|
||||
}
|
||||
|
||||
// AccountBillingSettingsRepository applies an admin edit without overwriting a
|
||||
// rate_multiplier that a successful upstream probe synchronized after the edit
|
||||
// form was loaded. A nil rateMultiplier means the request did not edit it.
|
||||
// AccountBillingSettingsUpdate carries explicit edits to fields shared with the billing probe.
|
||||
// Omitted fields retain the values in the locked row.
|
||||
type AccountBillingSettingsUpdate struct {
|
||||
ProbeEnabled, RateSyncEnabled, GroupSyncEnabled *bool
|
||||
RateMultiplier *float64
|
||||
SetName, SetNotes bool
|
||||
}
|
||||
|
||||
type AccountBillingSettingsRepository interface {
|
||||
UpdateWithAccountBillingSettings(
|
||||
ctx context.Context,
|
||||
account *Account,
|
||||
probeEnabled *bool,
|
||||
rateSyncEnabled *bool,
|
||||
rateMultiplier *float64,
|
||||
) error
|
||||
UpdateWithAccountBillingSettings(context.Context, *Account, AccountBillingSettingsUpdate) error
|
||||
}
|
||||
|
||||
// AdminAccountRepository makes the account-duplication write capability an explicit
|
||||
|
||||
@@ -100,6 +100,8 @@ func cloneAccountJSONMap(value map[string]any) (map[string]any, error) {
|
||||
var duplicateAccountDiscardedExtraKeys = map[string]struct{}{
|
||||
// A retry identity belongs to the operation that created one copy, not to later copies.
|
||||
duplicateAccountOperationIDExtraKey: {},
|
||||
// Keep the copy's local name until its administrator opts into group sync.
|
||||
UpstreamBillingGroupSyncEnabledExtraKey: {},
|
||||
// External sync identity belongs to one local account only.
|
||||
"crs_account_id": {},
|
||||
"crs_kind": {},
|
||||
@@ -414,9 +416,10 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an
|
||||
if input.Platform == PlatformTypeSafe && input.Type != AccountTypeAPIKey {
|
||||
return nil, errors.New("typesafe accounts only support apikey credentials")
|
||||
}
|
||||
// Probe/session state is system-managed. New accounts always start with automatic refresh disabled.
|
||||
// Probe/session state is system-managed. Only explicit account settings can enable it.
|
||||
delete(accountExtra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(accountExtra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(accountExtra, UpstreamBillingGroupSyncEnabledExtraKey)
|
||||
delete(accountExtra, UpstreamBillingProbeExtraKey)
|
||||
delete(accountExtra, OllamaCloudUsageSessionExtraKey)
|
||||
delete(accountExtra, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
@@ -437,7 +440,11 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an
|
||||
Status: StatusActive,
|
||||
Schedulable: true,
|
||||
}
|
||||
if input.ProbeEnabled != nil && *input.ProbeEnabled {
|
||||
groupSync := input.GroupSyncEnabled != nil && *input.GroupSyncEnabled
|
||||
if groupSync && input.ProbeEnabled != nil && !*input.ProbeEnabled {
|
||||
return nil, ErrUpstreamBillingGroupSyncRequiresProbe
|
||||
}
|
||||
if groupSync || (input.ProbeEnabled != nil && *input.ProbeEnabled) {
|
||||
if !isUpstreamBillingProbeAccount(account) {
|
||||
return nil, ErrUpstreamBillingProbeAccountInvalid
|
||||
}
|
||||
@@ -445,6 +452,9 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an
|
||||
account.Extra = make(map[string]any)
|
||||
}
|
||||
account.Extra[UpstreamBillingProbeEnabledExtraKey] = true
|
||||
if groupSync {
|
||||
account.Extra[UpstreamBillingGroupSyncEnabledExtraKey] = true
|
||||
}
|
||||
}
|
||||
// 预计算固定时间重置的下次重置时间
|
||||
if account.Extra != nil {
|
||||
@@ -667,6 +677,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
// 关闭配额限制时前端会删除 quota_* 键并提交 extra:{},此时也必须落库。
|
||||
requestedProbeEnabledUpdate := input.ProbeEnabled
|
||||
requestedRateSyncEnabledUpdate := input.RateSyncEnabled
|
||||
groupSyncUpdate := input.GroupSyncEnabled
|
||||
if input.Extra != nil {
|
||||
requestedProbeEnabled, hasRequestedProbeEnabled := normalizedExtra[UpstreamBillingProbeEnabledExtraKey]
|
||||
if hasRequestedProbeEnabled {
|
||||
@@ -681,6 +692,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
}
|
||||
delete(normalizedExtra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(normalizedExtra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(normalizedExtra, UpstreamBillingGroupSyncEnabledExtraKey)
|
||||
delete(normalizedExtra, UpstreamBillingProbeExtraKey)
|
||||
delete(normalizedExtra, OllamaCloudUsageSessionExtraKey)
|
||||
delete(normalizedExtra, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
@@ -702,6 +714,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
UpstreamModelMetadataExtraKey,
|
||||
UpstreamBillingProbeEnabledExtraKey,
|
||||
UpstreamBillingRateSyncEnabledExtraKey,
|
||||
UpstreamBillingGroupSyncEnabledExtraKey,
|
||||
UpstreamBillingProbeExtraKey,
|
||||
OllamaCloudUsageSessionExtraKey,
|
||||
OllamaCloudUsageAutoRefreshExtraKey,
|
||||
@@ -737,6 +750,12 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if input.Extra == nil {
|
||||
account.Extra = prepareCodexFingerprintExtraForUpdate(account, account.Extra)
|
||||
}
|
||||
if groupSyncUpdate != nil && *groupSyncUpdate {
|
||||
if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate {
|
||||
return nil, ErrUpstreamBillingGroupSyncRequiresProbe
|
||||
}
|
||||
requestedProbeEnabledUpdate = groupSyncUpdate
|
||||
}
|
||||
if requestedRateSyncEnabledUpdate != nil && *requestedRateSyncEnabledUpdate {
|
||||
if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate {
|
||||
return nil, infraerrors.BadRequest(
|
||||
@@ -750,6 +769,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate {
|
||||
disabled := false
|
||||
requestedRateSyncEnabledUpdate = &disabled
|
||||
groupSyncUpdate = &disabled
|
||||
}
|
||||
if (requestedProbeEnabledUpdate != nil && *requestedProbeEnabledUpdate) ||
|
||||
(requestedRateSyncEnabledUpdate != nil && *requestedRateSyncEnabledUpdate) {
|
||||
@@ -757,7 +777,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
return nil, ErrUpstreamBillingProbeAccountInvalid
|
||||
}
|
||||
}
|
||||
if account.Extra == nil && (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil) {
|
||||
if account.Extra == nil && (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil || groupSyncUpdate != nil) {
|
||||
account.Extra = make(map[string]any)
|
||||
}
|
||||
if requestedProbeEnabledUpdate != nil {
|
||||
@@ -766,6 +786,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if requestedRateSyncEnabledUpdate != nil {
|
||||
account.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *requestedRateSyncEnabledUpdate
|
||||
}
|
||||
if groupSyncUpdate != nil {
|
||||
account.Extra[UpstreamBillingGroupSyncEnabledExtraKey] = *groupSyncUpdate
|
||||
}
|
||||
// 影子代理恒继承母账号(由 propagateProxyToShadows 同步),不接受独立编辑——外审 B/P1;
|
||||
// 否则要等母账号下次改 proxy 才被覆盖,期间影子会出现"有时继承、有时独立"的漂移。
|
||||
if input.ProxyID != nil && !account.IsCredentialShadow() {
|
||||
@@ -782,6 +805,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if !isUpstreamBillingProbeAccount(account) {
|
||||
delete(account.Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(account.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(account.Extra, UpstreamBillingGroupSyncEnabledExtraKey)
|
||||
}
|
||||
}
|
||||
if account.Extra != nil {
|
||||
@@ -878,11 +902,11 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
}
|
||||
if updater != nil {
|
||||
if err := updater.UpdateWithAccountBillingSettings(
|
||||
ctx,
|
||||
account,
|
||||
requestedProbeEnabledUpdate,
|
||||
requestedRateSyncEnabledUpdate,
|
||||
input.RateMultiplier,
|
||||
ctx, account, AccountBillingSettingsUpdate{
|
||||
ProbeEnabled: requestedProbeEnabledUpdate, RateSyncEnabled: requestedRateSyncEnabledUpdate,
|
||||
GroupSyncEnabled: groupSyncUpdate, RateMultiplier: input.RateMultiplier,
|
||||
SetName: input.Name != "", SetNotes: input.Notes != nil,
|
||||
},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -892,15 +916,18 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
|
||||
if err := s.accountRepo.Update(ctx, account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil) &&
|
||||
if (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil || groupSyncUpdate != nil) &&
|
||||
isUpstreamBillingProbeAccount(account) {
|
||||
settings := make(map[string]any, 2)
|
||||
settings := make(map[string]any, 3)
|
||||
if requestedProbeEnabledUpdate != nil {
|
||||
settings[UpstreamBillingProbeEnabledExtraKey] = *requestedProbeEnabledUpdate
|
||||
}
|
||||
if requestedRateSyncEnabledUpdate != nil {
|
||||
settings[UpstreamBillingRateSyncEnabledExtraKey] = *requestedRateSyncEnabledUpdate
|
||||
}
|
||||
if groupSyncUpdate != nil {
|
||||
settings[UpstreamBillingGroupSyncEnabledExtraKey] = *groupSyncUpdate
|
||||
}
|
||||
if err := s.accountRepo.UpdateExtra(ctx, account.ID, settings); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -937,6 +964,7 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd
|
||||
updates = stripOpenAIAutoResetCreditManagedExtra(updates, true)
|
||||
delete(updates, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(updates, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(updates, UpstreamBillingGroupSyncEnabledExtraKey)
|
||||
delete(updates, UpstreamBillingProbeExtraKey)
|
||||
delete(updates, OllamaCloudUsageSessionExtraKey)
|
||||
delete(updates, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
@@ -966,6 +994,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
input.Extra = stripOpenAIAutoResetCreditManagedExtra(input.Extra, true)
|
||||
delete(input.Extra, UpstreamBillingProbeEnabledExtraKey)
|
||||
delete(input.Extra, UpstreamBillingRateSyncEnabledExtraKey)
|
||||
delete(input.Extra, UpstreamBillingGroupSyncEnabledExtraKey)
|
||||
delete(input.Extra, UpstreamBillingProbeExtraKey)
|
||||
delete(input.Extra, OllamaCloudUsageSessionExtraKey)
|
||||
delete(input.Extra, OllamaCloudUsageAutoRefreshExtraKey)
|
||||
@@ -1132,6 +1161,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
|
||||
repoUpdates.Extra[UpstreamBillingProbeEnabledExtraKey] = *input.ProbeEnabled
|
||||
if !*input.ProbeEnabled {
|
||||
repoUpdates.Extra[UpstreamBillingRateSyncEnabledExtraKey] = false
|
||||
repoUpdates.Extra[UpstreamBillingGroupSyncEnabledExtraKey] = false
|
||||
}
|
||||
}
|
||||
if updatesUpstreamBillingProbeIdentity(input.Credentials) || input.ProxyID != nil {
|
||||
|
||||
@@ -28,9 +28,7 @@ type accountBillingSettingsAdminRepo struct {
|
||||
func (r *accountBillingSettingsAdminRepo) UpdateWithAccountBillingSettings(
|
||||
_ context.Context,
|
||||
account *Account,
|
||||
probeEnabled *bool,
|
||||
rateSyncEnabled *bool,
|
||||
rateMultiplier *float64,
|
||||
settings AccountBillingSettingsUpdate,
|
||||
) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
@@ -45,15 +43,15 @@ func (r *accountBillingSettingsAdminRepo) UpdateWithAccountBillingSettings(
|
||||
if updated.Extra == nil {
|
||||
updated.Extra = make(map[string]any)
|
||||
}
|
||||
if probeEnabled != nil {
|
||||
updated.Extra[UpstreamBillingProbeEnabledExtraKey] = *probeEnabled
|
||||
if settings.ProbeEnabled != nil {
|
||||
updated.Extra[UpstreamBillingProbeEnabledExtraKey] = *settings.ProbeEnabled
|
||||
}
|
||||
if rateSyncEnabled != nil {
|
||||
updated.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *rateSyncEnabled
|
||||
if settings.RateSyncEnabled != nil {
|
||||
updated.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *settings.RateSyncEnabled
|
||||
}
|
||||
switch {
|
||||
case rateMultiplier != nil:
|
||||
value := *rateMultiplier
|
||||
case settings.RateMultiplier != nil:
|
||||
value := *settings.RateMultiplier
|
||||
updated.RateMultiplier = &value
|
||||
r.lastExplicitRate = &value
|
||||
case r.concurrentRate != nil:
|
||||
@@ -913,3 +911,23 @@ func TestCreateAccountDropsOpenCodeGoManagedKeys(t *testing.T) {
|
||||
require.NotContains(t, created.Extra, OpenCodeGoUsageSnapshotExtraKey)
|
||||
require.Equal(t, "value", created.Extra["custom"])
|
||||
}
|
||||
|
||||
func TestCreateAccountGroupSyncIsExplicitAndEnablesOnlyTheProbe(t *testing.T) {
|
||||
enabled, disabled := true, false
|
||||
input := &CreateAccountInput{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
|
||||
account, err := buildAccountForCreate(input, map[string]any{UpstreamBillingGroupSyncEnabledExtraKey: true})
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, account.Extra, UpstreamBillingGroupSyncEnabledExtraKey)
|
||||
input.GroupSyncEnabled = &enabled
|
||||
account, err = buildAccountForCreate(input, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, upstreamBillingProbeEnabled(account))
|
||||
require.Equal(t, true, account.Extra[UpstreamBillingGroupSyncEnabledExtraKey])
|
||||
require.False(t, upstreamBillingRateSyncEnabled(account))
|
||||
copyExtra, err := duplicateAccountExtra(account.Extra)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, copyExtra, UpstreamBillingGroupSyncEnabledExtraKey)
|
||||
input.ProbeEnabled = &disabled
|
||||
_, err = buildAccountForCreate(input, nil)
|
||||
require.ErrorIs(t, err, ErrUpstreamBillingGroupSyncRequiresProbe)
|
||||
}
|
||||
@@ -420,6 +420,7 @@ type CreateAccountInput struct {
|
||||
ExpiresAt *int64
|
||||
AutoPauseOnExpired *bool
|
||||
ProbeEnabled *bool
|
||||
GroupSyncEnabled *bool
|
||||
// SkipDefaultGroupBind prevents auto-binding to platform default group when GroupIDs is empty.
|
||||
SkipDefaultGroupBind bool
|
||||
// SkipMixedChannelCheck skips the mixed channel risk check when binding groups.
|
||||
@@ -453,6 +454,7 @@ type UpdateAccountInput struct {
|
||||
ExpiresAt *int64
|
||||
AutoPauseOnExpired *bool
|
||||
ProbeEnabled *bool
|
||||
GroupSyncEnabled *bool
|
||||
RateSyncEnabled *bool
|
||||
SkipMixedChannelCheck bool // 跳过混合渠道检查(用户已确认风险)
|
||||
}
|
||||
|
||||
@@ -1163,6 +1163,7 @@ func reconcileCRSUpstreamBillingProbeExtra(
|
||||
for _, key := range []string{
|
||||
UpstreamBillingProbeEnabledExtraKey,
|
||||
UpstreamBillingRateSyncEnabledExtraKey,
|
||||
UpstreamBillingGroupSyncEnabledExtraKey,
|
||||
UpstreamBillingProbeExtraKey,
|
||||
OllamaCloudUsageSessionExtraKey,
|
||||
OllamaCloudUsageAutoRefreshExtraKey,
|
||||
@@ -1180,8 +1181,10 @@ func reconcileCRSUpstreamBillingProbeExtra(
|
||||
extra[UpstreamBillingProbeEnabledExtraKey] = enabled
|
||||
probeEnabled, _ = enabled.(bool)
|
||||
}
|
||||
if enabled, ok := existing.Extra[UpstreamBillingRateSyncEnabledExtraKey].(bool); ok {
|
||||
extra[UpstreamBillingRateSyncEnabledExtraKey] = enabled && probeEnabled
|
||||
for _, key := range []string{UpstreamBillingRateSyncEnabledExtraKey, UpstreamBillingGroupSyncEnabledExtraKey} {
|
||||
if enabled, ok := existing.Extra[key].(bool); ok {
|
||||
extra[key] = enabled && probeEnabled
|
||||
}
|
||||
}
|
||||
if reflect.DeepEqual(upstreamBillingProbeIdentity(existing), upstreamBillingProbeIdentity(target)) {
|
||||
if snapshot, ok := existing.Extra[UpstreamBillingProbeExtraKey]; ok {
|
||||
|
||||
@@ -23,15 +23,17 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/google/uuid"
|
||||
"github.com/tidwall/gjson"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
const (
|
||||
// These values live in accounts.extra so PR2 does not require a schema migration.
|
||||
UpstreamBillingProbeExtraKey = "upstream_billing_probe"
|
||||
UpstreamBillingProbeEnabledExtraKey = "upstream_billing_probe_enabled"
|
||||
UpstreamBillingRateSyncEnabledExtraKey = "upstream_billing_rate_sync_enabled"
|
||||
UpstreamBillingProbeExtraKey = "upstream_billing_probe"
|
||||
UpstreamBillingProbeEnabledExtraKey = "upstream_billing_probe_enabled"
|
||||
UpstreamBillingRateSyncEnabledExtraKey = "upstream_billing_rate_sync_enabled"
|
||||
UpstreamBillingGroupSyncEnabledExtraKey = "upstream_billing_group_sync_enabled"
|
||||
|
||||
upstreamBillingProbeDefaultIntervalMinutes = 30
|
||||
upstreamBillingProbeMinIntervalMinutes = 5
|
||||
@@ -70,7 +72,8 @@ const UpstreamBillingProbeMaxBatchSize = upstreamBillingProbeMaxPerCycle
|
||||
const upstreamBillingRateSyncMaxMultiplier = 100.0
|
||||
|
||||
var (
|
||||
ErrUpstreamBillingProbeUnavailable = infraerrors.ServiceUnavailable(
|
||||
ErrUpstreamBillingGroupSyncRequiresProbe = infraerrors.BadRequest("UPSTREAM_BILLING_GROUP_SYNC_REQUIRES_PROBE", "upstream group sync requires upstream billing probe")
|
||||
ErrUpstreamBillingProbeUnavailable = infraerrors.ServiceUnavailable(
|
||||
"UPSTREAM_BILLING_PROBE_UNAVAILABLE", "upstream billing probe is unavailable",
|
||||
)
|
||||
ErrUpstreamBillingProbeAccountInvalid = infraerrors.BadRequest(
|
||||
@@ -258,7 +261,7 @@ type UpstreamBillingProbeService struct {
|
||||
}
|
||||
|
||||
type upstreamBillingProbeSnapshotWriter interface {
|
||||
UpdateUpstreamBillingProbeSnapshot(context.Context, *Account, *UpstreamBillingProbeSnapshot, *float64) error
|
||||
UpdateUpstreamBillingProbeSnapshot(context.Context, *Account, *UpstreamBillingProbeSnapshot, *float64, BillingGroupInfo) error
|
||||
}
|
||||
|
||||
type upstreamBillingProbeDueAccountLister interface {
|
||||
@@ -610,11 +613,11 @@ func (s *UpstreamBillingProbeService) SetAccountEnabled(ctx context.Context, acc
|
||||
updates := map[string]any{UpstreamBillingProbeEnabledExtraKey: enabled}
|
||||
if !enabled {
|
||||
updates[UpstreamBillingRateSyncEnabledExtraKey] = false
|
||||
updates[UpstreamBillingGroupSyncEnabledExtraKey] = false
|
||||
}
|
||||
return s.accountRepo.UpdateExtra(ctx, accountID, updates)
|
||||
}
|
||||
|
||||
// The probe persists rates, while the account form only reads display text.
|
||||
type upstreamBillingReply struct {
|
||||
body []byte
|
||||
status int
|
||||
@@ -732,7 +735,6 @@ func (s *UpstreamBillingProbeService) PreviewGroup(ctx context.Context, account
|
||||
return nil, infraerrors.New(http.StatusBadGateway, "UPSTREAM_GROUP_PREVIEW_FAILED", "Could not read group information from the upstream")
|
||||
}
|
||||
var info struct {
|
||||
BillingGroupInfo
|
||||
Object string `json:"object"`
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
BillingScope string `json:"billing_scope"`
|
||||
@@ -740,12 +742,31 @@ func (s *UpstreamBillingProbeService) PreviewGroup(ctx context.Context, account
|
||||
if json.Unmarshal(reply.body, &info) != nil || info.Object != "sub2api.key_billing" || info.SchemaVersion != 1 || info.BillingScope != "token" {
|
||||
return nil, infraerrors.New(http.StatusBadGateway, "UPSTREAM_GROUP_PREVIEW_INVALID", "Invalid upstream billing response")
|
||||
}
|
||||
return &info.BillingGroupInfo, nil
|
||||
group := upstreamBillingGroupInfo(reply.body)
|
||||
return &group, nil
|
||||
}
|
||||
|
||||
// Treat each optional text field independently so an invalid field cannot block rate updates.
|
||||
func upstreamBillingGroupInfo(body []byte) BillingGroupInfo {
|
||||
text := func(key string) string {
|
||||
value := gjson.GetBytes(body, key)
|
||||
if value.Type != gjson.String || strings.ContainsRune(value.Str, 0) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(value.Str)
|
||||
}
|
||||
name := text("group_name")
|
||||
if len(name) > 100 { // accounts.name uses Ent MaxLen(100).
|
||||
name = ""
|
||||
}
|
||||
return BillingGroupInfo{Name: name, Description: text("group_description")}
|
||||
}
|
||||
|
||||
func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, account *Account, intervalMinutes int) (*UpstreamBillingProbeSnapshot, error) {
|
||||
now := s.currentTime().UTC()
|
||||
reply, err := s.fetchBilling(ctx, account, false, now)
|
||||
groupSync, _ := account.Extra[UpstreamBillingGroupSyncEnabledExtraKey].(bool)
|
||||
includeGroup := groupSync && upstreamBillingProbeEnabled(account)
|
||||
reply, err := s.fetchBilling(ctx, account, includeGroup, now)
|
||||
if errors.Is(err, ErrUpstreamBillingProbeIdentityChanged) {
|
||||
return nil, err
|
||||
}
|
||||
@@ -785,7 +806,11 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac
|
||||
)
|
||||
}
|
||||
}
|
||||
if err := s.updateSnapshot(ctx, account, snapshot, syncRate); err != nil {
|
||||
var group BillingGroupInfo
|
||||
if includeGroup {
|
||||
group = upstreamBillingGroupInfo(reply.body)
|
||||
}
|
||||
if err := s.updateSnapshot(ctx, account, snapshot, syncRate, group); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if syncRate != nil {
|
||||
@@ -837,7 +862,7 @@ func (s *UpstreamBillingProbeService) persistProbeFailure(
|
||||
snapshot.FreshUntil = probeTimePtr(previous.ReceivedAt.Add(2 * time.Duration(intervalMinutes) * time.Minute))
|
||||
}
|
||||
}
|
||||
if err := s.updateSnapshot(ctx, account, snapshot, nil); err != nil {
|
||||
if err := s.updateSnapshot(ctx, account, snapshot, nil, BillingGroupInfo{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return snapshot, nil
|
||||
@@ -848,12 +873,13 @@ func (s *UpstreamBillingProbeService) updateSnapshot(
|
||||
account *Account,
|
||||
snapshot *UpstreamBillingProbeSnapshot,
|
||||
rateMultiplier *float64,
|
||||
group BillingGroupInfo,
|
||||
) error {
|
||||
writer, ok := s.accountRepo.(upstreamBillingProbeSnapshotWriter)
|
||||
if !ok {
|
||||
return ErrUpstreamBillingProbeUnavailable
|
||||
}
|
||||
return writer.UpdateUpstreamBillingProbeSnapshot(ctx, account, snapshot, rateMultiplier)
|
||||
return writer.UpdateUpstreamBillingProbeSnapshot(ctx, account, snapshot, rateMultiplier, group)
|
||||
}
|
||||
|
||||
func parseUpstreamBillingProbeResponse(body []byte) (map[string]any, error) {
|
||||
|
||||
@@ -115,6 +115,7 @@ func (r *upstreamBillingProbeAccountRepo) UpdateUpstreamBillingProbeSnapshot(
|
||||
expected *Account,
|
||||
snapshot *UpstreamBillingProbeSnapshot,
|
||||
rateMultiplier *float64,
|
||||
group BillingGroupInfo,
|
||||
) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
@@ -126,6 +127,12 @@ func (r *upstreamBillingProbeAccountRepo) UpdateUpstreamBillingProbeSnapshot(
|
||||
account.Extra = make(map[string]any)
|
||||
}
|
||||
account.Extra[UpstreamBillingProbeExtraKey] = snapshot
|
||||
if group.Name != "" {
|
||||
account.Name = group.Name
|
||||
}
|
||||
if group.Description != "" {
|
||||
account.Notes = &group.Description
|
||||
}
|
||||
if snapshot.Status == UpstreamBillingProbeStatusOK &&
|
||||
rateMultiplier != nil &&
|
||||
upstreamBillingRateSyncEnabled(account) {
|
||||
@@ -1302,3 +1309,44 @@ func TestUpstreamBillingProbeLeaderLockCoversStaggeredInstancesInCadenceWindow(t
|
||||
require.NoError(t, staggered.RunDue(context.Background()))
|
||||
require.Equal(t, int64(1), upstream.calls.Load(), "a staggered instance must not start a second batch inside the cadence window")
|
||||
}
|
||||
|
||||
func TestUpstreamBillingGroupSyncSharesOneProbeAndPreservesLocalFields(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
groupSync, rateSync bool
|
||||
fields, wantName, wantNotes string
|
||||
wantRate float64
|
||||
}{
|
||||
{"group only", true, false, `"group_name":"Pro","group_description":"shared"`, "Pro", "shared", 1},
|
||||
{"both with blank notes", true, true, `"group_name":"Pro","group_description":" "`, "Pro", "local notes", 0.5},
|
||||
{"invalid name", true, true, `"group_name":12,"group_description":"shared"`, "local", "shared", 0.5},
|
||||
{"old upstream", true, true, `"unrelated":true`, "local", "local notes", 0.5},
|
||||
{"rate only", false, true, `"group_name":"Pro","group_description":"shared"`, "local", "local notes", 0.5},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rate, notes := 1.0, "local notes"
|
||||
account := &Account{
|
||||
ID: 17, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive,
|
||||
Name: "local", Notes: ¬es, RateMultiplier: &rate,
|
||||
Credentials: map[string]any{"api_key": "key", "base_url": "https://upstream.example"},
|
||||
Extra: map[string]any{
|
||||
UpstreamBillingProbeEnabledExtraKey: true,
|
||||
UpstreamBillingGroupSyncEnabledExtraKey: tt.groupSync,
|
||||
UpstreamBillingRateSyncEnabledExtraKey: tt.rateSync,
|
||||
},
|
||||
}
|
||||
body := `{"object":"sub2api.key_billing","schema_version":1,"billing_scope":"token","group_rate_multiplier":0.5,"resolved_rate_multiplier":0.5,"effective_rate_multiplier":0.5,"peak_rate_enabled":false,"observed_at":"2026-07-13T01:00:00Z",` + tt.fields + "}"
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}}
|
||||
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}}
|
||||
svc := newUpstreamBillingProbeTestService(repo, upstream, &upstreamBillingProbeSettingRepo{})
|
||||
snapshot, err := svc.probeScheduledAccount(context.Background(), account.ID, 30)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, UpstreamBillingProbeStatusOK, snapshot.Status)
|
||||
require.Len(t, upstream.requests, 1)
|
||||
require.Equal(t, tt.groupSync, upstream.lastReq.URL.Query().Get("include") == "group")
|
||||
require.Equal(t, tt.wantName, account.Name)
|
||||
require.Equal(t, tt.wantNotes, *account.Notes)
|
||||
require.Equal(t, tt.wantRate, *account.RateMultiplier)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user