新功能(#3): 抽奖 Stage 1 收官 — 用户 API + 后台 CRUD + 集成

Closes HIF-3

Stage 1 完整闭环 PR C:用户 API + 后台 CRUD + 抽奖事务服务 + 审计 + QA curl。合并后 Stage 1 可交测试。

架构师 review R1(rulecaps depth≤8/nodes≤64/bytes≤8KB)+ R2(InviteHook source_ref 加 order: 前缀)已全部落地。

- 迁移 02158_admin_action_log:后台写操作审计
- xerr 100xxx 段:抽奖错误码(NotEligible/NoChances/ActivityEnded/RateLimited/NotClaimable/InternalError/RuleTooDeep/RuleTooMany/RuleTooLarge)
- feature flag config.Lottery.Enable 默认 false,合并后线上零副作用
- draw service:feature flag → rate limit → pre-tx reads → nonce dedupe → Consume → Pick → 乐观扣库存 → 双快照 → Dispatch → finalize
- 用户 API 4 个:GET /config、POST /draw、GET /records、POST /claim(Stage 1 返回 100010)
- 后台 CRUD:活动 / 奖品 / rules PUT(rulecaps gate)/ chances/grant
- audit.WriteAdminAction:与调用方 tx 同生共死,SHA1 body 摘要
- QA 脚本:qa/lottery/stage1_curl.sh 全链路 curl

测试覆盖:model 76.5% / draw 69% / handler 68.3% / hook 91.9% / rulecaps 87.8% / audit 100%
100 并发抢库存 + 10000 次概率分布 e2e 推 QA 环境(sqlmock 无法忠实模拟 InnoDB 行锁)
CI 全绿:构建/Vet/测试 + golangci-lint
This commit is contained in:
2026-07-08 22:33:18 -07:00
committed by GitHub
parent a46fb83054
commit ce3babcc33
27 changed files with 3599 additions and 18 deletions
+112
View File
@@ -0,0 +1,112 @@
package rulecaps
import (
"encoding/json"
"errors"
"fmt"
"github.com/perfect-panel/server/internal/model/lottery"
)
// 抽奖门槛规则树的固定上限。恶意 admin 或误配可以让 PUT rules 的 JSON 递归
// 爆炸,评估时爆栈;这些常量给"合理配置"预留了充足空间,同时挡住 blob。
const (
// MaxDepth 是嵌套 AND/OR 允许的最大深度(根算 1 层)。
MaxDepth = 8
// MaxNodes 是整树里叶子 + 聚合节点总数上限。
MaxNodes = 64
// MaxBytes 是原始 JSON 字节数上限(8KB)。
MaxBytes = 8 * 1024
)
// ErrRuleTreeTooDeep 表示 AND/OR 嵌套超过 MaxDepth。
var ErrRuleTreeTooDeep = errors.New("rule tree exceeds max depth")
// ErrRuleTreeTooManyNodes 表示节点总数超过 MaxNodes。
var ErrRuleTreeTooManyNodes = errors.New("rule tree exceeds max node count")
// ErrRuleTreeTooLarge 表示 JSON payload 超过 MaxBytes。
var ErrRuleTreeTooLarge = errors.New("rule tree JSON exceeds max byte size")
// ValidateEligibilityJSON 是 PUT /activities/{id}/rules 收到 eligibility JSON
// 时的准入闸门。三个上限任一超限 → 返回带上下文的错误,caller 直接 400。
// 空 JSON、"{}"、`null` 都视为合法(表示"无门槛")。
func ValidateEligibilityJSON(raw []byte) error {
if len(raw) > MaxBytes {
return fmt.Errorf("%w: %d bytes > %d limit", ErrRuleTreeTooLarge, len(raw), MaxBytes)
}
if len(raw) == 0 {
return nil
}
// 允许 null / "{}" 表示无门槛。
trimmed := trimJSONWhitespace(raw)
if len(trimmed) == 0 || string(trimmed) == "null" || string(trimmed) == "{}" {
return nil
}
var tree lottery.EligibilityRule
if err := json.Unmarshal(raw, &tree); err != nil {
return fmt.Errorf("invalid eligibility JSON: %w", err)
}
return validateRule(&tree, 1)
}
// validateRule 递归检查一棵规则树;depth 是当前节点所在层(根 = 1)。
// 用共享计数器(返回值)而不是外部 counter 是为了让递归签名保持无副作用。
func validateRule(node *lottery.EligibilityRule, depth int) error {
if node == nil {
return nil
}
if depth > MaxDepth {
return fmt.Errorf("%w: got depth %d, max %d", ErrRuleTreeTooDeep, depth, MaxDepth)
}
count, err := countAndValidate(node, depth)
if err != nil {
return err
}
if count > MaxNodes {
return fmt.Errorf("%w: got %d nodes, max %d", ErrRuleTreeTooManyNodes, count, MaxNodes)
}
return nil
}
// countAndValidate 深度优先遍历,一次递归同时统计节点数并做深度检查。
// 返回 count 是子树总节点数(含当前节点);err 表明遍历中已经超限。
func countAndValidate(node *lottery.EligibilityRule, depth int) (int, error) {
if node == nil {
return 0, nil
}
if depth > MaxDepth {
return 0, fmt.Errorf("%w: got depth %d, max %d", ErrRuleTreeTooDeep, depth, MaxDepth)
}
total := 1
for _, child := range node.Children {
sub, err := countAndValidate(child, depth+1)
if err != nil {
return 0, err
}
total += sub
// 提前退出:命中节点数上限就不要继续 walk 剩余分支。
if total > MaxNodes {
return 0, fmt.Errorf("%w: got at least %d nodes, max %d", ErrRuleTreeTooManyNodes, total, MaxNodes)
}
}
return total, nil
}
// trimJSONWhitespace 剥掉前后 JSON 空白,用于识别"实质空"的 payload。
func trimJSONWhitespace(raw []byte) []byte {
i, j := 0, len(raw)
for i < j && isJSONWhitespace(raw[i]) {
i++
}
for j > i && isJSONWhitespace(raw[j-1]) {
j--
}
return raw[i:j]
}
func isJSONWhitespace(b byte) bool {
return b == ' ' || b == '\t' || b == '\n' || b == '\r'
}
@@ -0,0 +1,127 @@
package rulecaps
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/perfect-panel/server/internal/model/lottery"
)
func TestValidateEligibilityJSON_AcceptsEmpty(t *testing.T) {
cases := [][]byte{
nil,
[]byte(""),
[]byte("{}"),
[]byte("null"),
[]byte(" \n \t "),
}
for _, c := range cases {
if err := ValidateEligibilityJSON(c); err != nil {
t.Fatalf("expected accept for %q, got %v", string(c), err)
}
}
}
func TestValidateEligibilityJSON_RejectsOversizePayload(t *testing.T) {
blob := make([]byte, MaxBytes+1)
for i := range blob {
blob[i] = 'a'
}
err := ValidateEligibilityJSON(blob)
if !errors.Is(err, ErrRuleTreeTooLarge) {
t.Fatalf("expected ErrRuleTreeTooLarge, got %v", err)
}
// user-facing message should name the limit
if !strings.Contains(err.Error(), "8192") {
t.Fatalf("expected message to mention 8192 byte limit, got %q", err.Error())
}
}
func TestValidateEligibilityJSON_RejectsBadJSON(t *testing.T) {
err := ValidateEligibilityJSON([]byte(`{bad`))
if err == nil {
t.Fatalf("expected error on invalid JSON")
}
}
// buildDeepTree 构造 depth 层单链嵌套(每层一个 OR 聚合)。root 为第 1 层。
func buildDeepTree(depth int) *lottery.EligibilityRule {
root := &lottery.EligibilityRule{Op: "OR", Children: []*lottery.EligibilityRule{{Type: "has_subscription"}}}
current := root
for i := 2; i < depth; i++ {
next := &lottery.EligibilityRule{Op: "OR", Children: []*lottery.EligibilityRule{{Type: "has_subscription"}}}
current.Children = []*lottery.EligibilityRule{next}
current = next
}
return root
}
func TestValidateEligibilityJSON_RejectsDepthOverLimit(t *testing.T) {
tree := buildDeepTree(MaxDepth + 1) // depth 9 with defaults
raw, err := json.Marshal(tree)
if err != nil {
t.Fatalf("marshal: %v", err)
}
err = ValidateEligibilityJSON(raw)
if !errors.Is(err, ErrRuleTreeTooDeep) {
t.Fatalf("expected ErrRuleTreeTooDeep, got %v", err)
}
}
func TestValidateEligibilityJSON_AcceptsMaxDepth(t *testing.T) {
tree := buildDeepTree(MaxDepth)
raw, _ := json.Marshal(tree)
if err := ValidateEligibilityJSON(raw); err != nil {
t.Fatalf("depth=MaxDepth must be accepted, got %v", err)
}
}
// buildWideTree 构造根节点 + N 个叶子,总节点数 = 1 + N。
func buildWideTree(leaves int) *lottery.EligibilityRule {
root := &lottery.EligibilityRule{Op: "AND"}
for i := 0; i < leaves; i++ {
root.Children = append(root.Children, &lottery.EligibilityRule{Type: "has_subscription"})
}
return root
}
func TestValidateEligibilityJSON_RejectsNodeCountOverLimit(t *testing.T) {
// 65 nodes total = 1 root + 64 leaves > MaxNodes
tree := buildWideTree(MaxNodes)
raw, _ := json.Marshal(tree)
err := ValidateEligibilityJSON(raw)
if !errors.Is(err, ErrRuleTreeTooManyNodes) {
t.Fatalf("expected ErrRuleTreeTooManyNodes, got %v", err)
}
}
func TestValidateEligibilityJSON_AcceptsAtNodeLimit(t *testing.T) {
// 64 nodes = 1 root + 63 leaves
tree := buildWideTree(MaxNodes - 1)
raw, _ := json.Marshal(tree)
if err := ValidateEligibilityJSON(raw); err != nil {
t.Fatalf("nodes=MaxNodes must be accepted, got %v", err)
}
}
func TestValidateEligibilityJSON_AcceptsRealisticTree(t *testing.T) {
// Typical activity: (has_subscription AND invite_count>=3) OR user_tag in {vip}
raw := []byte(`{
"op": "OR",
"children": [
{
"op": "AND",
"children": [
{"type": "has_subscription", "params": {"min_days_remaining": 7}},
{"type": "invite_count", "params": {"min": 3}}
]
},
{"type": "user_tag", "params": {"tags": ["vip"]}}
]
}`)
if err := ValidateEligibilityJSON(raw); err != nil {
t.Fatalf("realistic tree should be accepted, got %v", err)
}
}