mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-03 07:46:21 +00:00
fix(billing-probe): govern the automatic account rate write-back
- 自动写回值域治理与留痕:上游声明值必须 > 0 且 <= 100 才写回。0 会让
accountCost 恒为 0(账号总额/日/周配额与成本告警全部静默失效),极大值可
一次打爆配额并污染成本报表;越界时保持原倍率、记 WARN,探测快照照常记 ok。
写回成功时记结构化 slog(account_id / 旧值 / 新值 / source),并在快照中
新增 synced_rate_multiplier 记录本次写回值——后台任务裸 SQL 不产生
audit_logs,这两处是唯一可追溯来源。管理员手工设 0 不受影响。
- 写回改用 resolved_rate_multiplier(不含高峰的基准倍率):effective 含探测
那一刻的高峰系数,写回会把一个探测周期的峰值/谷值冻结进静态列,而展示与
调度用 upstreamBillingRateAt 按当前时间重算高峰,两者会持续不一致。
- 倍率解析失败不再污染公共探测路径:账号级值域/精度只在该账号已开启同步、
真要写回时才有影响;未开同步的账号照常记 ok 快照,不累计 failure_count、
不进入指数退避。
- 单账号编辑补 service 层守卫:同步开启时拒绝手工倍率(新增
UPSTREAM_BILLING_RATE_SYNC_CONFLICT,与批量路径同族),此前只有前端
disabled 挡人,直接 PUT /admin/accounts/{id} 可写入并活到下次成功探测。
判断的是本次请求生效后的状态,"关同步 + 改倍率"同请求仍然放行。
- 修正开关反推方向:不再由 rate_sync=true 推出 probe=true,否则一条"同步开、
探测键缺失"的僵尸记录会在任意一次无关编辑时静默打开周期性外呼;改为探测
关闭/缺失一律把同步归零。
- 删除死代码 UpdateWithUpstreamBillingProbeEnabled(PR 删接口后生产已无调用
方),其回滚测试改为直接覆盖生产路径 UpdateWithAccountBillingSettings。
upstreamBillingRateSyncEnabled 不再是只服务测试的假门控,现为写回前置过滤,
SQL CAS 仍是权威门控,两侧均加注释说明分工。
- en/zh 文案补充:同步的是不含高峰的基准倍率;开启同步会连带打开自动探测。
This commit is contained in:
1 parent
b0f5007f04
commit
0b6b4ea956
9 files changed
+421
-45
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
"net/http"
|
||||
@@ -46,7 +47,6 @@ const (
|
||||
// upstreamBillingProbeMaxPerCycle 个名额。
|
||||
upstreamBillingProbeUnsupportedDelayFactor = 8
|
||||
upstreamBillingProbeAccountRateScale = 10000.0
|
||||
upstreamBillingProbeAccountRateMax = 999999.9999
|
||||
upstreamBillingProbeLeaderLockKey = "upstream:billing:probe:leader"
|
||||
upstreamBillingProbeLeaderLockTTL = 2 * time.Minute
|
||||
)
|
||||
@@ -54,6 +54,21 @@ const (
|
||||
// UpstreamBillingProbeMaxBatchSize limits one manual batch and one runner cycle.
|
||||
const UpstreamBillingProbeMaxBatchSize = upstreamBillingProbeMaxPerCycle
|
||||
|
||||
// upstreamBillingRateSyncMaxMultiplier bounds the value the automatic
|
||||
// write-back may push into accounts.rate_multiplier.
|
||||
//
|
||||
// No other code path bounds that column from above — admins may type any
|
||||
// non-negative number and the only ceiling is the DECIMAL(10,4) column itself
|
||||
// (999999.9999). That ceiling is meaningless as a guard: rate_multiplier
|
||||
// scales the per-request account cost that feeds quota_used, so a single
|
||||
// declared 999999 would exhaust any account quota on the first request and
|
||||
// poison cost reporting. 100 is picked as a deliberately generous bound: it is
|
||||
// two orders of magnitude above the 1.0 default and far above any plausible
|
||||
// upstream resale markup, so no legitimate declaration is rejected while an
|
||||
// absurd or hostile one cannot reach the quota control plane unattended.
|
||||
// It only constrains the automatic path; manual edits keep their old range.
|
||||
const upstreamBillingRateSyncMaxMultiplier = 100.0
|
||||
|
||||
var (
|
||||
ErrUpstreamBillingProbeUnavailable = infraerrors.ServiceUnavailable(
|
||||
"UPSTREAM_BILLING_PROBE_UNAVAILABLE", "upstream billing probe is unavailable",
|
||||
@@ -68,6 +83,10 @@ var (
|
||||
"UPSTREAM_BILLING_RATE_SYNC_BULK_CONFLICT",
|
||||
"account rate multiplier cannot be changed in bulk while upstream billing rate sync is enabled",
|
||||
)
|
||||
ErrUpstreamBillingRateSyncConflict = infraerrors.Conflict(
|
||||
"UPSTREAM_BILLING_RATE_SYNC_CONFLICT",
|
||||
"account rate multiplier cannot be changed while upstream billing rate sync is enabled",
|
||||
)
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -94,6 +113,12 @@ type UpstreamBillingProbeSnapshot struct {
|
||||
FailureCount int `json:"failure_count,omitempty"`
|
||||
HTTPStatus int `json:"http_status,omitempty"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
// SyncedRateMultiplier records the value this probe wrote into
|
||||
// accounts.rate_multiplier. It is only set when the account opted into rate
|
||||
// sync and the declared value passed the write-back range check, so the
|
||||
// stored snapshot always answers "did this probe move the account rate, and
|
||||
// to what" without a separate history table.
|
||||
SyncedRateMultiplier *float64 `json:"synced_rate_multiplier,omitempty"`
|
||||
}
|
||||
|
||||
// UpstreamBillingProbeResult is returned by manual probe endpoints.
|
||||
@@ -644,10 +669,6 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac
|
||||
if err != nil {
|
||||
return s.persistProbeFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "invalid_response", retryAfter(resp.Header, now))
|
||||
}
|
||||
rateMultiplier, ok := upstreamBillingProbeAccountRate(data)
|
||||
if !ok {
|
||||
return s.persistProbeFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "invalid_response", retryAfter(resp.Header, now))
|
||||
}
|
||||
snapshot := &UpstreamBillingProbeSnapshot{
|
||||
Status: UpstreamBillingProbeStatusOK,
|
||||
Data: data,
|
||||
@@ -657,9 +678,39 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac
|
||||
NextProbeAt: now.Add(nextProbeDelay(intervalMinutes, 0)),
|
||||
HTTPStatus: resp.StatusCode,
|
||||
}
|
||||
if err := s.updateSnapshot(ctx, account, snapshot, &rateMultiplier); err != nil {
|
||||
// 账号级值域与精度只在真要写回时才有影响:只观察上游声明、未开启同步的
|
||||
// 账号不因声明值不适配 accounts.rate_multiplier 而被记成探测失败并进入
|
||||
// 指数退避——探测本身成功了,原始声明照常存进快照供展示。
|
||||
var syncRate *float64
|
||||
previousRate := account.BillingRateMultiplier()
|
||||
if upstreamBillingRateSyncEnabled(account) {
|
||||
if value, valid := upstreamBillingProbeSyncRate(data); valid {
|
||||
syncRate = &value
|
||||
snapshot.SyncedRateMultiplier = &value
|
||||
} else {
|
||||
declared, _ := resolveAccountExtraNumber(data, "resolved_rate_multiplier")
|
||||
slog.Warn("upstream_billing_rate_sync_rejected",
|
||||
"source", "upstream_billing_probe",
|
||||
"account_id", account.ID,
|
||||
"declared_resolved_rate_multiplier", declared,
|
||||
"max_rate_multiplier", upstreamBillingRateSyncMaxMultiplier,
|
||||
"current_rate_multiplier", previousRate,
|
||||
)
|
||||
}
|
||||
}
|
||||
if err := s.updateSnapshot(ctx, account, snapshot, syncRate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if syncRate != nil {
|
||||
// 写回是后台任务的裸 SQL,不经过管理端路由,因此不会产生 audit_logs 行。
|
||||
// old_rate_multiplier 是本次探测开始时读到的值(写回的 CAS 不比对该列)。
|
||||
slog.Info("upstream_billing_rate_sync_applied",
|
||||
"source", "upstream_billing_probe",
|
||||
"account_id", account.ID,
|
||||
"old_rate_multiplier", previousRate,
|
||||
"new_rate_multiplier", *syncRate,
|
||||
)
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
@@ -817,16 +868,32 @@ func upstreamBillingRateAt(data map[string]any, now time.Time) (float64, bool) {
|
||||
return base, true
|
||||
}
|
||||
|
||||
// upstreamBillingProbeAccountRate converts the declared effective multiplier
|
||||
// to the precision supported by accounts.rate_multiplier (DECIMAL(10,4)).
|
||||
func upstreamBillingProbeAccountRate(data map[string]any) (float64, bool) {
|
||||
value, ok := resolveAccountExtraNumber(data, "effective_rate_multiplier")
|
||||
if !ok || value < 0 || value > upstreamBillingProbeAccountRateMax ||
|
||||
math.IsNaN(value) || math.IsInf(value, 0) {
|
||||
// upstreamBillingProbeSyncRate converts the declared multiplier into the value
|
||||
// the automatic write-back may store in accounts.rate_multiplier, at the
|
||||
// precision that column supports (DECIMAL(10,4)).
|
||||
//
|
||||
// It reads resolved_rate_multiplier, not effective_rate_multiplier: the
|
||||
// effective value folds in the peak coefficient that happened to apply at the
|
||||
// instant of the probe, so writing it would freeze one probe cycle's peak (or
|
||||
// off-peak) factor into a static column, while display and scheduling
|
||||
// recompute the peak factor for the current time through upstreamBillingRateAt.
|
||||
//
|
||||
// The accepted range is deliberately narrower than the column:
|
||||
// - 0 is rejected. accountCost multiplies the request cost by this value, so
|
||||
// an upstream-declared 0 would stop quota_used from ever growing and every
|
||||
// admin-configured account quota and cost alert would silently stop
|
||||
// working. Admins may still set 0 by hand; only the automatic path refuses.
|
||||
// - anything above upstreamBillingRateSyncMaxMultiplier is rejected.
|
||||
//
|
||||
// A rejected declaration leaves the current multiplier untouched; the probe
|
||||
// still records an OK snapshot carrying the raw declaration for display.
|
||||
func upstreamBillingProbeSyncRate(data map[string]any) (float64, bool) {
|
||||
value, ok := resolveAccountExtraNumber(data, "resolved_rate_multiplier")
|
||||
if !ok || math.IsNaN(value) || math.IsInf(value, 0) {
|
||||
return 0, false
|
||||
}
|
||||
rounded := math.Round(value*upstreamBillingProbeAccountRateScale) / upstreamBillingProbeAccountRateScale
|
||||
if value > 0 && rounded == 0 {
|
||||
if rounded <= 0 || rounded > upstreamBillingRateSyncMaxMultiplier {
|
||||
return 0, false
|
||||
}
|
||||
return rounded, true
|
||||
@@ -973,6 +1040,10 @@ func upstreamBillingProbeEnabled(account *Account) bool {
|
||||
return ok && enabled
|
||||
}
|
||||
|
||||
// upstreamBillingRateSyncEnabled is the probe-side pre-filter deciding whether
|
||||
// a rate is even proposed for write-back. It is a necessary condition, not the
|
||||
// authority: the repository CAS re-checks both switches against the row it
|
||||
// updates, so a switch flipped between load and write can never sneak a rate in.
|
||||
func upstreamBillingRateSyncEnabled(account *Account) bool {
|
||||
if account == nil || account.Extra == nil {
|
||||
return false
|
||||
|
||||
Reference in new issue
Block a user