Merge pull request #3568 from DaydreamCoding/fix/auth-signup-grok-platform-quota

fix(auth-signup): 平台配额快照脱离注册事务 + grok 补入 CHECK 约束
This commit is contained in:
Wesley Liddick
2026-06-30 13:37:54 +08:00
committed by GitHub
5 changed files with 100 additions and 1 deletions
+17
View File
@@ -0,0 +1,17 @@
package ent
import "context"
// WithoutTx 返回一个剥离了所附 *Tx 的 ctx 副本,使调用方可以在基础 client
// (autocommit)上执行 best-effort、非关键的副作用,而不加入——也就不会毒化——
// 外层事务。
//
// Postgres 语义:事务内任一语句失败即把整个事务标记为 aborted,后续语句全部被拒,
// 直到 ROLLBACK。因此对 fail-open 的副作用(如注册时的默认平台配额快照)必须做事务
// 隔离,否则一条无关紧要的写入失败会连累调用方的关键事务。
func WithoutTx(ctx context.Context) context.Context {
if TxFromContext(ctx) == nil {
return ctx
}
return context.WithValue(ctx, txCtxKey{}, (*Tx)(nil))
}
@@ -72,6 +72,32 @@ func TestUserPlatformQuotaRepository_BulkInsertInitial_Empty(t *testing.T) {
require.NoError(t, repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{}))
}
// TestUserPlatformQuotaRepository_BulkInsertInitial_GrokAllowed 回归迁移 157:
// grok 平台必须能写入 user_platform_quotas(CHECK 约束已含 grok)。
// 历史 bug:grok 不在约束内 → 注册写默认配额违约 → 注册事务 aborted → 自助注册 500/404。
func TestUserPlatformQuotaRepository_BulkInsertInitial_GrokAllowed(t *testing.T) {
ctx := context.Background()
tx := testEntTx(t)
txCtx := dbent.NewTxContext(ctx, tx)
client := tx.Client()
userID := mustCreateUserForQuota(t, client)
repo := NewUserPlatformQuotaRepository(client)
daily := 9.0
records := []UserPlatformQuotaRecord{
{UserID: userID, Platform: "grok", DailyLimitUSD: &daily},
}
require.NoError(t, repo.BulkInsertInitial(txCtx, records),
"grok 平台应可写入(迁移 157 后 CHECK 约束已含 grok)")
rec, err := repo.GetByUserPlatform(txCtx, userID, "grok")
require.NoError(t, err)
require.NotNil(t, rec, "grok 配额行应已写入")
require.NotNil(t, rec.DailyLimitUSD)
require.InDelta(t, 9.0, *rec.DailyLimitUSD, 1e-9)
}
func TestUserPlatformQuotaRepository_GetByUserPlatform(t *testing.T) {
ctx := context.Background()
tx := testEntTx(t)
+5
View File
@@ -1665,6 +1665,11 @@ func (s *AuthService) snapshotPlatformQuotaDefaults(ctx context.Context, userID
if s.userPlatformQuotaRepo == nil || plan == nil || len(plan.PlatformQuotas) == 0 {
return nil
}
// 平台配额快照是 best-effort(fail-open):必须脱离调用方事务执行。
// 否则某平台违反 user_platform_quotas 的 CHECK 约束(如尚未进约束的新平台)会让
// 整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认配额快照"放大成
// "整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。
ctx = dbent.WithoutTx(ctx)
records := make([]UserPlatformQuotaRecord, 0, len(plan.PlatformQuotas))
for platform, q := range plan.PlatformQuotas {
rec := UserPlatformQuotaRecord{
@@ -7,19 +7,23 @@ import (
"fmt"
"testing"
"time"
dbent "github.com/Wei-Shaw/sub2api/ent"
)
// fakeInsertRecorder 记录 BulkInsertInitial 调用,实现 UserPlatformQuotaRepository port。
type fakeInsertRecorder struct {
records []UserPlatformQuotaRecord
err error
lastCtx context.Context // 捕获最后一次 BulkInsertInitial 收到的 ctx(用于断言事务隔离)
}
func (f *fakeInsertRecorder) GetByUserPlatform(_ context.Context, _ int64, _ string) (*UserPlatformQuotaRecord, error) {
return nil, nil
}
func (f *fakeInsertRecorder) BulkInsertInitial(_ context.Context, recs []UserPlatformQuotaRecord) error {
func (f *fakeInsertRecorder) BulkInsertInitial(ctx context.Context, recs []UserPlatformQuotaRecord) error {
f.lastCtx = ctx
if f.err != nil {
return f.err
}
@@ -77,6 +81,37 @@ func TestSnapshotPlatformQuotaDefaults_PassesToRepoBulkInsert(t *testing.T) {
}
}
// TestSnapshotPlatformQuotaDefaults_DetachesCallerTransaction 锁定 fix① 不变量:
// 平台配额快照是 best-effort,必须脱离调用方事务执行——这样它失败(例如某平台
// 违反 user_platform_quotas 的 CHECK 约束)也不会把调用方的注册主事务标记为 aborted。
// 历史 bug:snapshot 在 OAuth pending handler 的 binding tx 中执行,grok 违约毒化整个
// 事务 → consumePendingOAuthBrowserSessionTx 撞 "transaction aborted" → 500 → 清 cookie → 404。
func TestSnapshotPlatformQuotaDefaults_DetachesCallerTransaction(t *testing.T) {
fakeRepo := &fakeInsertRecorder{}
s := &AuthService{userPlatformQuotaRepo: fakeRepo}
five := 5.0
plan := &signupGrantPlan{
PlatformQuotas: map[string]*DefaultPlatformQuotaSetting{
"anthropic": {DailyLimitUSD: &five},
},
}
// 模拟调用方(OAuth pending handler)在事务 ctx 中调用快照
txCtx := dbent.NewTxContext(context.Background(), &dbent.Tx{})
if err := s.snapshotPlatformQuotaDefaults(txCtx, 999, plan); err != nil {
t.Fatalf("snapshot should not error (fail-open): %v", err)
}
if fakeRepo.lastCtx == nil {
t.Fatal("expected BulkInsertInitial to be called")
}
if dbent.TxFromContext(fakeRepo.lastCtx) != nil {
t.Error("快照必须脱离调用方事务执行(best-effort,失败不得毒化注册事务),但 repo 收到了仍携带事务的 ctx")
}
}
func TestSnapshotPlatformQuotaDefaults_NilPlanIsNoop(t *testing.T) {
fakeRepo := &fakeInsertRecorder{}
s := &AuthService{userPlatformQuotaRepo: fakeRepo}
@@ -0,0 +1,16 @@
-- 把 grok 平台加入 user_platform_quotas.platform 的 CHECK 约束。
--
-- 背景:grok 自 2026-06 起进入默认平台配额(default_platform_quotas /
-- auth_source_default_*_platform_quotas),但 142 建表时的 CHECK 仅允许
-- anthropic/openai/gemini/antigravity。自助注册时 snapshotPlatformQuotaDefaults
-- 会写入 grok 默认配额行 → 违反 CHECK → 整个注册事务被标记 aborted →
-- OAuth pending 路径 consume 会话时撞 "transaction aborted" → 500 → 清 cookie → 404。
--
-- 修复:把约束与代码平台列表(internal/domain/constants.go 的 PlatformGrok)对齐。
-- DROP ... IF EXISTS 保证可重入;新约束是旧约束的超集,存量行(仅 4 平台)瞬时校验通过。
ALTER TABLE user_platform_quotas
DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;
ALTER TABLE user_platform_quotas
ADD CONSTRAINT user_platform_quotas_platform_check
CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok'));