Files
pangolin/server/internal/store/codes_lib_migrate_test.go
T
wangjia a62a2b1797
ci-pangolin / Lint — shellcheck (pull_request) Successful in 11s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (pull_request) Successful in 25s
ci-pangolin / Cleartext Scan — Android 禁明文 (pull_request) Successful in 19s
ci-pangolin / OpenAPI Sync Check (pull_request) Successful in 41s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (pull_request) Successful in 20s
ci-pangolin / Codegen Drift — token 生成物未漂移 (pull_request) Successful in 4s
ci-pangolin / DS-flow — 原型/跨端同源/代码色单源闸 (pull_request) Successful in 5s
ci-pangolin / Go — build + test (pull_request) Failing after 14s
ci-pangolin / E2E Smoke — L4 进程级端到端 (pull_request) Failing after 11s
ci-pangolin / Go — integration (mysql/redis testcontainers) (pull_request) Failing after 4m44s
ci-pangolin / Golden — 视觉回归 (全量:components/auth/desktop/tablet) (pull_request) Failing after 20s
ci-pangolin / Flutter — analyze + test (pull_request) Failing after 11m55s
fix(server/pay): promo 限购 settle 侧幂等复查 + 000027 部分唯一索引(TOCTOU)
CreateOrder 下单时的 HasPaidPurchase 只是裸 SELECT 无锁,并发/多挂起单可绕过
promo SKU「每账号限购一次」。两层修:
① webhook.go settle 在锁行、开通前对 item.Promo 的 SKU 复查一次(排除本单),
   命中说明另一笔同 user+SKU 订单已抢先 settle,跳过发放(不二次 +N 天)、
   仍 ack(否则 pay 无限重投)。新增 store.HasPaidPurchaseExcludingTx /
   MarkDuplicatePromoTx——重复单标记 canceled 而非 paid,避免自撞下面的
   唯一索引、也避免整笔 500 触发死循环重投。
② migration 000027(sqlite):部分唯一索引 ux_pay_promo_paid ON
   pay_purchases(user_id, sku) WHERE status='paid' AND sku='pro_month_promo',
   兜底防止任何路径把同一用户的 promo 单二次写成 paid。mysql 8 不支持部分
   索引,000027 mysql 侧是 no-op 占位(仅对齐编号),该场景 mysql 只靠①的
   应用层复查兜底——两库防线强度不同,已在迁移文件与代码注释中记录。

副作用:新增迁移把 sqlite 迁移顶点从 26 推到 27,同步更新
internal/store/sqlite_migrate_test.go 的版本断言,以及
internal/store/codes_lib_migrate_test.go 手动 Steps(-1) 序列(补一步跳过
000027,才能精确落在 000022 边界,这条测试是硬编码步数的)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 15:53:56 +08:00

183 lines
6.9 KiB
Go

package store_test
import (
"context"
"database/sql"
"testing"
"github.com/golang-migrate/migrate/v4"
migratesqlite "github.com/golang-migrate/migrate/v4/database/sqlite"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/wangjia/pangolin/server/internal/config"
"github.com/wangjia/pangolin/server/internal/store"
"github.com/wangjia/pangolin/server/migrations"
)
// TestApplyCodesLibMigrations verifies the shared codes library's tables are
// created on top of a fully-migrated pangolin sqlite DB (post-000022, the
// legacy tables are renamed away so the lib's `codes` table name is free).
func TestApplyCodesLibMigrations(t *testing.T) {
ctx := context.Background()
db, err := store.Open(&config.Config{Driver: "sqlite", DSN: ":memory:"})
if err != nil {
t.Fatalf("open: %v", err)
}
defer db.Close()
if err := store.MigrateUp(db, "sqlite"); err != nil {
t.Fatalf("MigrateUp: %v", err)
}
if err := store.ApplyCodesLibMigrations(ctx, db, "sqlite"); err != nil {
t.Fatalf("ApplyCodesLibMigrations: %v", err)
}
// 幂等:重复调用不报错(库自带 codes_schema_migrations 追踪表)。
if err := store.ApplyCodesLibMigrations(ctx, db, "sqlite"); err != nil {
t.Fatalf("ApplyCodesLibMigrations 2nd: %v", err)
}
for _, tbl := range []string{"codes", "codes_batches", "codes_audit_log", "codes_schema_migrations"} {
var name string
if err := db.QueryRow(
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, tbl,
).Scan(&name); err != nil {
t.Errorf("lib table %q missing: %v", tbl, err)
}
}
}
// newSQLiteStepper builds a golang-migrate instance identical to the one
// internal/store.MigrateUp/MigrateDown use internally (same embedded FS,
// same sqlite driver), except it exposes Steps() so the test can land
// exactly on the 000022 boundary instead of only being able to invoke a
// full up-to-latest / down-to-zero round trip like the public API does.
// Mirrors internal/store/migrate.go's newMigrator — kept in the test
// because that constructor is unexported.
func newSQLiteStepper(t *testing.T, database *sql.DB) *migrate.Migrate {
t.Helper()
src, err := iofs.New(migrations.SQLiteFS, "sqlite")
if err != nil {
t.Fatalf("iofs source: %v", err)
}
drv, err := migratesqlite.WithInstance(database, &migratesqlite.Config{})
if err != nil {
t.Fatalf("sqlite driver: %v", err)
}
m, err := migrate.NewWithInstance("iofs", src, "sqlite", drv)
if err != nil {
t.Fatalf("new migrator: %v", err)
}
return m
}
// TestCodesLibMigrateRoundTrip exercises the real wired path end-to-end:
// MigrateUp -> ApplyCodesLibMigrations -> step 000022 back down -> assert
// legacy restored/lib gone -> step back up -> ApplyCodesLibMigrations again
// -> finally the full `store.MigrateDown` (== cmd/migrate's "down" command)
// all the way to version 0, which is the exact call the reviewer reported
// as failing hard.
//
// Reproduces the reviewer-found collision: 000022's down does
// legacy_codes -> codes renames, but the codes-lib's own `codes` table
// (created by ApplyCodesLibMigrations, untracked by golang-migrate) is
// still sitting there, so the rename used to fail with "table already
// exists" (sqlite) / "ALTER TABLE ... table already exists" (mysql
// RENAME TABLE semantics). 000022's down script must DROP the lib-owned
// tables before renaming legacy_* back.
func TestCodesLibMigrateRoundTrip(t *testing.T) {
ctx := context.Background()
db, err := store.Open(&config.Config{Driver: "sqlite", DSN: ":memory:"})
if err != nil {
t.Fatalf("open: %v", err)
}
defer db.Close()
// 1. Up + wire in the codes-lib's own tables (the real cmd/migrate up path).
if err := store.MigrateUp(db, "sqlite"); err != nil {
t.Fatalf("MigrateUp: %v", err)
}
if err := store.ApplyCodesLibMigrations(ctx, db, "sqlite"); err != nil {
t.Fatalf("ApplyCodesLibMigrations: %v", err)
}
// 2. Step exactly 000022 back down (21 <- 22). This is the precise seam
// the reviewer's repro hit: the lib's `codes` table collides with the
// name 000022's down script renames legacy_codes back to.
m := newSQLiteStepper(t, db)
// 000027 (pay_promo_paid_unique), 000026 (notices), 000025
// (user_device_limit_override), 000024 (invite_rewards) and 000023
// (pay_purchases/source-enum) now sit on top of 000022
// (codes_lib_legacy_rename) and are unrelated to this collision — step
// them back down first so we land exactly on the 000022 boundary the
// test targets.
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000027 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000026 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000025 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000024 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000023 down: %v", err)
}
if err := m.Steps(-1); err != nil {
t.Fatalf("step 000022 down: %v (this is the reviewer-reported collision — "+
"000022 down must DROP the codes-lib tables before renaming legacy_* back)", err)
}
// 3. Legacy tables restored to their original pangolin names/shape;
// lib-owned tables gone.
for _, tbl := range []string{"codes", "code_batches"} {
var name string
if err := db.QueryRow(
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, tbl,
).Scan(&name); err != nil {
t.Errorf("legacy table %q not restored: %v", tbl, err)
}
}
// Original pangolin `codes` shape (plan_id/duration_days), not the
// codes-lib shape (entitlement_kind/entitlement_payload).
if _, err := db.Exec(`SELECT plan_id, duration_days, redeemed_by FROM codes LIMIT 0`); err != nil {
t.Errorf("codes table not restored to pangolin shape: %v", err)
}
for _, tbl := range []string{"codes_batches", "codes_audit_log", "codes_schema_migrations"} {
var name string
err := db.QueryRow(
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, tbl,
).Scan(&name)
if err == nil {
t.Errorf("lib table %q should have been dropped by the 000022 down step, still present", tbl)
} else if err != sql.ErrNoRows {
t.Errorf("checking lib table %q gone: %v", tbl, err)
}
}
// 4. Step 000022 back up + reapply the lib migrations: idempotent, must
// stay green.
if err := m.Steps(1); err != nil {
t.Fatalf("step 000022 up (2nd round-trip): %v", err)
}
if err := store.ApplyCodesLibMigrations(ctx, db, "sqlite"); err != nil {
t.Fatalf("ApplyCodesLibMigrations (2nd round-trip): %v", err)
}
// 5. Finally, the exact call the reviewer reported as failing hard:
// `cmd/migrate down` == store.MigrateDown, a full rollback to version 0.
// Must succeed cleanly (no "table already exists").
if err := store.MigrateDown(db, "sqlite"); err != nil {
t.Fatalf("store.MigrateDown (full, == cmd/migrate down): %v", err)
}
v, _, err := store.MigrateVersion(db, "sqlite")
if err != nil {
t.Fatalf("MigrateVersion after full down: %v", err)
}
if v != 0 {
t.Errorf("version after full MigrateDown = %d, want 0", v)
}
}