阶段十:完成 Go Cmd Tools 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 05:40:01 +08:00
1 parent 393c45a1e3
commit ea1f2ec430
25 files changed
+694 -4281

No files matched your search

+50 -10
View File
@@ -23,11 +23,15 @@ import (
"xianyu-go/internal/db"
)
// main 负责main相关处理。
func main() {
// cleanup 保存cleanup,供当前处理流程使用
var cleanup func() error
// fail 保存fail,供当前处理流程使用
fail := func(format string, args ...any) {
if cleanup != nil {
if err := cleanup(); err != nil {
if // err 保存err,供当前处理流程使用
err := cleanup(); err != nil {
fmt.Printf("⚠️ 清理验证数据失败: %v\n", err)
}
}
@@ -39,11 +43,14 @@ func main() {
fmt.Println("用法: dbverify <database-url>")
os.Exit(1)
}
// url 保存地址,供当前处理流程使用
url := os.Args[1]
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
fmt.Printf("连接 %s ...\n", maskURL(url))
// database、dialect、err 保存database、dialect、err,供当前处理流程使用
database, dialect, err := db.Open(ctx, url)
if err != nil {
fail("❌ Open 失败: %v\n", err)
@@ -51,32 +58,43 @@ func main() {
defer database.Close()
fmt.Printf("✅ 迁移成功,方言=%s\n", dialect)
// store 保存store,供当前处理流程使用
store := db.NewStore(database, dialect)
// 1) 创建用户(用唯一用户名,避免在已有数据的库上因 admin 重名而失败)。
ids := newVerifyIDs(time.Now().UnixNano())
// username 保存username,供当前处理流程使用
username := ids.username
// accountID 保存账号ID,供当前处理流程使用
accountID := ids.accountID
// orderID 保存订单ID,供当前处理流程使用
orderID := ids.orderID
// itemID 保存商品ID,供当前处理流程使用
itemID := ids.itemID
// buyerID 保存买家ID,供当前处理流程使用
buyerID := ids.buyerID
cleanup = func() error {
// cleanupCtx、cleanupCancel 保存cleanupCtx、cleanup取消,供当前处理流程使用
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cleanupCancel()
return cleanupVerifyData(cleanupCtx, store, ids)
}
// password、err 保存password、err,供当前处理流程使用
password, err := newVerifyPassword()
if err != nil {
fail("❌ 生成验证密码失败: %v\n", err)
}
// ok、err 保存ok、err,供当前处理流程使用
ok, err := store.Users.Create(ctx, username, username+"@test.local", password)
if err != nil || !ok {
fail("❌ 创建用户失败: err=%v ok=%v\n", err, ok)
}
// adminUser、err 保存adminUser、err,供当前处理流程使用
adminUser, err := store.Users.GetByUsername(ctx, username)
if err != nil {
fail("❌ 查询验证用户失败: %v\n", err)
}
// userID 保存用户ID,供当前处理流程使用
userID := adminUser.ID
fmt.Printf("✅ 创建验证用户 %s (id=%d)\n", username, userID)
@@ -84,13 +102,15 @@ func main() {
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_1;", userID); err != nil {
fail("❌ 保存 cookie 失败: %v\n", err)
}
if err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.SetStatus(ctx, accountID, false); err != nil {
fail("❌ 禁用验证账号失败: %v\n", err)
}
// 再 Save 一次验证 upsert
if err := store.Cookies.Save(ctx, accountID, "unb=123; _m_h5_tk=tk_2;", userID); err != nil {
fail("❌ 二次保存 cookie 失败: %v\n", err)
}
// v 保存v,供当前处理流程使用
v, _ := store.Cookies.GetValue(ctx, accountID)
fmt.Printf("✅ cookie upsert 成功,value=%s\n", v)
@@ -98,7 +118,8 @@ func main() {
if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil {
fail("❌ 系统设置 Set 失败: %v\n", err)
}
if err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Settings.Set(ctx, "theme_color", "green"); err != nil {
fail("❌ 系统设置二次 Set 失败: %v\n", err)
}
fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)")
@@ -123,7 +144,8 @@ func main() {
}); err != nil {
fail("❌ 商品 Upsert 失败: %v\n", err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
if // err 保存err,供当前处理流程使用
err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: accountID, ItemID: itemID, ItemTitle: "更新后商品", ItemPrice: "29.90",
}); err != nil {
fail("❌ 商品二次 Upsert 失败: %v\n", err)
@@ -153,7 +175,8 @@ func main() {
if err != nil {
fail("❌ 创建通知渠道失败: %v\n", err)
}
if err := store.Notifications.SetBindings(ctx, accountID, []int64{chID}); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Notifications.SetBindings(ctx, accountID, []int64{chID}); err != nil {
fail("❌ 绑定通知渠道失败: %v\n", err)
}
fmt.Printf("✅ 通知渠道 + 绑定 OK (channel=%d)\n", chID)
@@ -166,6 +189,7 @@ func main() {
if err != nil {
fail("❌ 创建自动化规则失败: %v\n", err)
}
// runID、started、err 保存运行ID、started、err,供当前处理流程使用
runID, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: accountID, TriggerType: "order_paid", TriggerKey: orderID, Status: "running",
})
@@ -184,7 +208,8 @@ func main() {
}
fmt.Printf("✅ 自动化规则 + 防重 OK (rule=%d run=%d)\n", ruleID, runID)
if err := cleanup(); err != nil {
if // err 保存err,供当前处理流程使用
err := cleanup(); err != nil {
fmt.Printf("❌ 清理验证数据失败: %v\n", err)
os.Exit(1)
}
@@ -193,12 +218,15 @@ func main() {
fmt.Println("\n🎉 全部验证通过")
}
// maskURL 负责maskURL相关处理。
func maskURL(url string) string {
// 只显示 scheme 和 host,把 scheme 后到首个 '@' 之间的凭证替换为 ***。
for _, p := range []string{"mysql://", "postgres://", "postgresql://"} {
if len(url) > len(p) && url[:len(p)] == p {
// rest 保存rest,供当前处理流程使用
rest := url[len(p):]
if at := strings.Index(rest, "@"); at >= 0 {
if // at 保存at,供当前处理流程使用
at := strings.Index(rest, "@"); at >= 0 {
return p + "***@" + rest[at+1:]
}
return url
@@ -207,6 +235,7 @@ func maskURL(url string) string {
return url
}
// verifyIDs 保存verifyIDs,供当前处理流程使用
type verifyIDs struct {
username string
accountID string
@@ -215,7 +244,9 @@ type verifyIDs struct {
buyerID string
}
// newVerifyIDs 负责newVerifyIDs相关处理。
func newVerifyIDs(n int64) verifyIDs {
// suffix 保存suffix,供当前处理流程使用
suffix := fmt.Sprintf("%d", n)
return verifyIDs{
username: "verify_" + suffix,
@@ -226,19 +257,26 @@ func newVerifyIDs(n int64) verifyIDs {
}
}
// newVerifyPassword 负责newVerify密码相关处理。
func newVerifyPassword() (string, error) {
// b 保存b,供当前处理流程使用
var b [24]byte
if _, err := rand.Read(b[:]); err != nil {
if // err 保存err,供当前处理流程使用
_, err := rand.Read(b[:]); err != nil {
return "", err
}
return "verify_" + hex.EncodeToString(b[:]), nil
}
// cleanupVerifyData 负责cleanupVerify数据相关处理。
func cleanupVerifyData(ctx context.Context, store *db.Store, ids verifyIDs) error {
// userID 保存用户ID,供当前处理流程使用
userID := int64(0)
if user, err := store.Users.GetByUsername(ctx, ids.username); err == nil {
if // user、err 保存user、err,供当前处理流程使用
user, err := store.Users.GetByUsername(ctx, ids.username); err == nil {
userID = user.ID
}
// queries 保存queries,供当前处理流程使用
queries := []struct {
query string
args []any
@@ -256,8 +294,10 @@ func cleanupVerifyData(ctx context.Context, store *db.Store, ids verifyIDs) erro
{`DELETE FROM sessions WHERE user_id=?`, []any{userID}},
{`DELETE FROM users WHERE username=? AND email=?`, []any{ids.username, ids.username + "@test.local"}},
}
// q 表示当前遍历过程中的q
for _, q := range queries {
if _, err := store.DB.ExecContext(ctx, q.query, q.args...); err != nil {
if // err 保存err,供当前处理流程使用
_, err := store.DB.ExecContext(ctx, q.query, q.args...); err != nil {
return err
}
}
+47 -11
View File
@@ -11,6 +11,7 @@ import (
// TestMaskURL 验证带凭证的数据库 URL 脱敏:保留 scheme + host,密码替换为 ***。
func TestMaskURL(t *testing.T) {
// cases 保存cases,供当前处理流程使用
cases := map[string]string{
"mysql://user:secret@tcp(host:3306)/db?x=1": "mysql://***@tcp(host:3306)/db?x=1",
"postgres://user:pass@host:5432/db": "postgres://***@host:5432/db",
@@ -18,15 +19,20 @@ func TestMaskURL(t *testing.T) {
"sqlite://data/x.db": "sqlite://data/x.db", // 无密码,原样
"/local/path.db": "/local/path.db", // 非 URL,原样
}
// in、want 表示当前遍历过程中的in、want
for in, want := range cases {
if got := maskURL(in); got != want {
if // got 保存got,供当前处理流程使用
got := maskURL(in); got != want {
t.Errorf("maskURL(%q) = %q; want %q", in, got, want)
}
}
}
// TestNewVerifyIDsAreUniqueForPersistentRuns 负责TestNewVerifyIDsAreUniqueForPersistent运行记录相关处理。
func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
// ids 保存ids,供当前处理流程使用
ids := newVerifyIDs(12345)
// want 保存want,供当前处理流程使用
want := map[string]string{
"username": "verify_12345",
"accountID": "acc_12345",
@@ -34,6 +40,7 @@ func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
"itemID": "item_12345",
"buyerID": "buyer_12345",
}
// got 保存got,供当前处理流程使用
got := map[string]string{
"username": ids.username,
"accountID": ids.accountID,
@@ -41,6 +48,7 @@ func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
"itemID": ids.itemID,
"buyerID": ids.buyerID,
}
// key、wantValue 表示当前遍历过程中的key、want值
for key, wantValue := range want {
if got[key] != wantValue {
t.Fatalf("%s=%q want %q", key, got[key], wantValue)
@@ -51,11 +59,14 @@ func TestNewVerifyIDsAreUniqueForPersistentRuns(t *testing.T) {
}
}
// TestNewVerifyPasswordIsNotFixedDefault 负责TestNewVerify密码IsNotFixedDefault相关处理。
func TestNewVerifyPasswordIsNotFixedDefault(t *testing.T) {
// first、err 保存first、err,供当前处理流程使用
first, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword: %v", err)
}
// second、err 保存second、err,供当前处理流程使用
second, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword second: %v", err)
@@ -68,24 +79,32 @@ func TestNewVerifyPasswordIsNotFixedDefault(t *testing.T) {
}
}
// TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled 负责TestCleanupVerify数据RemovesRowsAndVerify数据IsDisabled相关处理。
func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// database、dialect、err 保存database、dialect、err,供当前处理流程使用
database, dialect, err := db.Open(ctx, filepath.Join(t.TempDir(), "verify.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
defer database.Close()
// store 保存store,供当前处理流程使用
store := db.NewStore(database, dialect)
// ids 保存ids,供当前处理流程使用
ids := newVerifyIDs(987654321)
// password、err 保存password、err,供当前处理流程使用
password, err := newVerifyPassword()
if err != nil {
t.Fatalf("newVerifyPassword: %v", err)
}
// ok、err 保存ok、err,供当前处理流程使用
ok, err := store.Users.Create(ctx, ids.username, ids.username+"@test.local", password)
if err != nil || !ok {
t.Fatalf("Create user: ok=%v err=%v", ok, err)
}
// user、err 保存user、err,供当前处理流程使用
user, err := store.Users.GetByUsername(ctx, ids.username)
if err != nil {
t.Fatalf("GetByUsername: %v", err)
@@ -93,41 +112,51 @@ func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
if user.IsAdmin {
t.Fatal("dbverify 创建的验证用户不应是管理员")
}
if err := store.Cookies.Save(ctx, ids.accountID, "unb=123; _m_h5_tk=tk_1;", user.ID); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(ctx, ids.accountID, "unb=123; _m_h5_tk=tk_1;", user.ID); err != nil {
t.Fatalf("Save cookie: %v", err)
}
if err := store.Cookies.SetStatus(ctx, ids.accountID, false); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Cookies.SetStatus(ctx, ids.accountID, false); err != nil {
t.Fatalf("SetStatus false: %v", err)
}
if store.Cookies.GetStatus(ctx, ids.accountID) {
t.Fatal("dbverify 验证账号应默认禁用,避免被服务启动")
}
if err := store.Orders.Upsert(ctx, ids.orderID, db.OrderUpsertOpts{ItemID: ids.itemID, BuyerID: ids.buyerID, CookieID: ids.accountID}); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Orders.Upsert(ctx, ids.orderID, db.OrderUpsertOpts{ItemID: ids.itemID, BuyerID: ids.buyerID, CookieID: ids.accountID}); err != nil {
t.Fatalf("Orders.Upsert: %v", err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: ids.accountID, ItemID: ids.itemID, ItemTitle: "测试商品"}); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: ids.accountID, ItemID: ids.itemID, ItemTitle: "测试商品"}); err != nil {
t.Fatalf("Items.Upsert: %v", err)
}
// cardID、err 保存卡密ID、err,供当前处理流程使用
cardID, err := store.Cards.Create(ctx, &db.CardFull{Name: "测试卡组", Type: "data", DataContent: "card", Enabled: true, UserID: user.ID})
if err != nil || cardID == 0 {
t.Fatalf("Cards.Create: id=%d err=%v", cardID, err)
}
// channelID、err 保存渠道ID、err,供当前处理流程使用
channelID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{
Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: false, UserID: user.ID,
})
if err != nil {
t.Fatalf("CreateChannel: %v", err)
}
// channelEnabled 保存渠道启用状态,供当前处理流程使用
var channelEnabled int
if err := store.DB.QueryRowContext(ctx, `SELECT enabled FROM notification_channels WHERE id=?`, channelID).Scan(&channelEnabled); err != nil {
if // err 保存err,供当前处理流程使用
err := store.DB.QueryRowContext(ctx, `SELECT enabled FROM notification_channels WHERE id=?`, channelID).Scan(&channelEnabled); err != nil {
t.Fatalf("query channel enabled: %v", err)
}
if channelEnabled != 0 {
t.Fatal("dbverify 验证通知渠道应默认禁用")
}
if err := store.Notifications.SetBindings(ctx, ids.accountID, []int64{channelID}); err != nil {
if // err 保存err,供当前处理流程使用
err := store.Notifications.SetBindings(ctx, ids.accountID, []int64{channelID}); err != nil {
t.Fatalf("SetBindings: %v", err)
}
// ruleID、err 保存规则ID、err,供当前处理流程使用
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{
UserID: user.ID, CookieID: ids.accountID, ItemID: ids.itemID, Name: "付款发货",
TriggerType: "order_paid", Enabled: false, Priority: 100,
@@ -135,22 +164,28 @@ func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
if err != nil {
t.Fatalf("Automation.Create: %v", err)
}
if _, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
if // started、err 保存started、err,供当前处理流程使用
_, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{
RuleID: ruleID, CookieID: ids.accountID, TriggerType: "order_paid", TriggerKey: ids.orderID, Status: "running",
}); err != nil || !started {
t.Fatalf("TryStartRun: started=%v err=%v", started, err)
}
if err := cleanupVerifyData(ctx, store, ids); err != nil {
if // err 保存err,供当前处理流程使用
err := cleanupVerifyData(ctx, store, ids); err != nil {
t.Fatalf("cleanupVerifyData: %v", err)
}
if _, err := store.Users.GetByUsername(ctx, ids.username); !errors.Is(err, db.ErrNotFound) {
if // err 保存err,供当前处理流程使用
_, err := store.Users.GetByUsername(ctx, ids.username); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("验证用户应被清理,err=%v", err)
}
if _, err := store.Cookies.GetValue(ctx, ids.accountID); !errors.Is(err, db.ErrNotFound) {
if // err 保存err,供当前处理流程使用
_, err := store.Cookies.GetValue(ctx, ids.accountID); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("验证账号应被清理,err=%v", err)
}
// count 保存数量,供当前处理流程使用
var count int
// name、query 表示当前遍历过程中的name、query
for name, query := range map[string]string{
"automation_runs": `SELECT COUNT(*) FROM automation_runs WHERE cookie_id=? OR trigger_key=?`,
"automation_rules": `SELECT COUNT(*) FROM automation_rules WHERE cookie_id=? OR item_id=?`,
@@ -158,6 +193,7 @@ func TestCleanupVerifyDataRemovesRowsAndVerifyDataIsDisabled(t *testing.T) {
"orders": `SELECT COUNT(*) FROM orders WHERE cookie_id=? OR order_id=?`,
"items": `SELECT COUNT(*) FROM item_info WHERE cookie_id=? OR item_id=?`,
} {
// err 保存err,供当前处理流程使用
var err error
switch name {
case "automation_runs", "orders":