新功能(#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
+100
View File
@@ -0,0 +1,100 @@
// Package audit records administrative write actions to the admin_action_log
// table so security/compliance can trace who did what across lottery admin
// endpoints. Every admin CRUD in PR C calls WriteAdminAction inside its own
// transaction; the caller is expected to have already validated permissions.
package audit
import (
"context"
"crypto/sha1"
"encoding/hex"
"fmt"
"strings"
"time"
"gorm.io/gorm"
)
// Action code convention: dot-separated, prefix by domain (e.g.
// "lottery.activity.create", "lottery.prize.delete"). Keep them short and
// stable so downstream analytics can pivot without maintaining a translation
// table.
const (
ActionLotteryActivityCreate = "lottery.activity.create"
ActionLotteryActivityUpdate = "lottery.activity.update"
ActionLotteryActivityDelete = "lottery.activity.delete"
ActionLotteryActivityPublish = "lottery.activity.publish"
ActionLotteryActivityPause = "lottery.activity.pause"
ActionLotteryPrizeCreate = "lottery.prize.create"
ActionLotteryPrizeUpdate = "lottery.prize.update"
ActionLotteryPrizeDelete = "lottery.prize.delete"
ActionLotteryRulesPut = "lottery.activity.rules.put"
ActionLotteryChancesGrant = "lottery.chances.grant"
)
// AdminActionLog is the GORM entity for admin_action_log.
type AdminActionLog struct {
Id int64 `gorm:"primaryKey"`
ActorUserId int64 `gorm:"type:bigint unsigned;not null;comment:操作者 user.id"`
Action string `gorm:"type:varchar(64);not null;comment:动作 code"`
TargetIds string `gorm:"type:varchar(255);not null;default:'';comment:被操作对象 ID"`
RequestHash string `gorm:"type:varchar(64);not null;default:'';comment:请求摘要"`
IP string `gorm:"type:varchar(45);not null;default:'';comment:操作者 IP"`
UserAgent string `gorm:"type:varchar(255);not null;default:'';comment:操作者 UA"`
CreatedAt time.Time `gorm:"<-:create;default:CURRENT_TIMESTAMP;comment:操作时间"`
}
// TableName pins the entity to the migration table name.
func (AdminActionLog) TableName() string { return "admin_action_log" }
// Entry is the pre-hashed convenience input to WriteAdminAction. Callers
// build one with actor + action + payload fields; the writer computes the
// request hash and inserts inside tx.
type Entry struct {
ActorUserId int64
Action string
// TargetIds is stringified list of primary keys touched by this action.
// Free-form: comma-separated ints, JSON array, etc.
TargetIds string
// RequestBody is hashed to produce request_hash. Pass nil if not applicable.
RequestBody []byte
IP string
UserAgent string
}
// WriteAdminAction inserts an admin_action_log row inside the caller's tx.
// The row lives-or-dies with the caller's transaction: a rollback drops the
// audit trail, which is the intended coupling — we don't want to record
// actions that never happened.
func WriteAdminAction(ctx context.Context, tx *gorm.DB, e Entry) error {
if tx == nil {
return fmt.Errorf("audit: WriteAdminAction requires a transaction handle")
}
if e.ActorUserId == 0 || e.Action == "" {
return fmt.Errorf("audit: WriteAdminAction requires ActorUserId and Action")
}
row := AdminActionLog{
ActorUserId: e.ActorUserId,
Action: strings.TrimSpace(e.Action),
TargetIds: e.TargetIds,
RequestHash: hashBody(e.RequestBody),
IP: e.IP,
UserAgent: truncate(e.UserAgent, 255),
}
return tx.WithContext(ctx).Create(&row).Error
}
func hashBody(body []byte) string {
if len(body) == 0 {
return ""
}
sum := sha1.Sum(body)
return hex.EncodeToString(sum[:])
}
func truncate(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max]
}
@@ -0,0 +1,111 @@
package audit
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func newTestDB(t *testing.T) (*gorm.DB, sqlmock.Sqlmock, func()) {
t.Helper()
sqlDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherFunc(func(expected, actual string) error {
if strings.Contains(actual, expected) {
return nil
}
return fmt.Errorf("actual sql %q does not contain %q", actual, expected)
})))
if err != nil {
t.Fatalf("create sqlmock: %v", err)
}
db, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, SkipInitializeWithVersion: true}), &gorm.Config{SkipDefaultTransaction: true})
if err != nil {
_ = sqlDB.Close()
t.Fatalf("open gorm: %v", err)
}
return db, mock, func() { _ = sqlDB.Close() }
}
func TestWriteAdminAction_RequiresTx(t *testing.T) {
err := WriteAdminAction(context.Background(), nil, Entry{ActorUserId: 1, Action: "x"})
if err == nil {
t.Fatalf("expected error on nil tx")
}
}
func TestWriteAdminAction_RequiresActorAndAction(t *testing.T) {
db, _, cleanup := newTestDB(t)
defer cleanup()
if err := WriteAdminAction(context.Background(), db, Entry{Action: "x"}); err == nil {
t.Fatal("expected error when ActorUserId=0")
}
if err := WriteAdminAction(context.Background(), db, Entry{ActorUserId: 1}); err == nil {
t.Fatal("expected error when Action empty")
}
}
func TestWriteAdminAction_InsertsRow(t *testing.T) {
db, mock, cleanup := newTestDB(t)
defer cleanup()
mock.ExpectExec("INSERT INTO `admin_action_log`").
WillReturnResult(sqlmock.NewResult(1, 1))
err := WriteAdminAction(context.Background(), db, Entry{
ActorUserId: 42,
Action: ActionLotteryActivityCreate,
TargetIds: "[1,2,3]",
RequestBody: []byte(`{"title":"test"}`),
IP: "127.0.0.1",
UserAgent: "curl/7.85",
})
if err != nil {
t.Fatalf("WriteAdminAction: %v", err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("expectations: %v", err)
}
}
func TestHashBody(t *testing.T) {
if got := hashBody(nil); got != "" {
t.Fatalf("nil body should hash to empty, got %q", got)
}
if got := hashBody([]byte("")); got != "" {
t.Fatalf("empty body should hash to empty, got %q", got)
}
if got := hashBody([]byte("abc")); len(got) != 40 {
t.Fatalf("expected 40-char sha1 hex, got %q", got)
}
}
func TestTruncate(t *testing.T) {
if got := truncate("hello", 10); got != "hello" {
t.Fatalf("short strings pass through, got %q", got)
}
if got := truncate("hello world", 5); got != "hello" {
t.Fatalf("expected truncation to 5, got %q", got)
}
}
func TestWriteAdminAction_DBError(t *testing.T) {
db, mock, cleanup := newTestDB(t)
defer cleanup()
mock.ExpectExec("INSERT INTO `admin_action_log`").
WillReturnError(errors.New("db down"))
err := WriteAdminAction(context.Background(), db, Entry{
ActorUserId: 1,
Action: "test",
})
if err == nil {
t.Fatal("expected error propagation from DB")
}
}