可靠性与数据一致性:为 SQLite、MySQL、PostgreSQL 增加 00017 至 00021 迁移,引入账号暂停时间、默认回复和批量铺货租约、自动化运行恢复、延迟任务、动作检查点与通知 outbox。补强订单、卡密发货、Cookie、批量铺货和自动化任务的原子认领、幂等更新、并发控制、失败分类、重试与进程重启恢复,并扩展跨方言覆盖。 登录与风控恢复:完善扫码、密码登录、Cookie 续期、MTOP token、UA 与 WebSocket 生命周期;加入账号级持久化浏览器目录、Playwright 主引擎和直接 Chromium/CDP 备用引擎、严格的新 x5sec 成功判定、失败控件恢复及真实浏览器集成测试。增加可配置远程滑块服务,在明确失败、链接过期和服务不可用场景中保持既定的本地回退语义。 安全与配置:通过 XIANYU_DATA_KEY 为 Cookie、登录密码、设备与访问令牌、AI/SMTP 密钥及通知配置提供 AES-256-GCM 落库加密和历史明文升级。新增出站网络目标分级、防 DNS rebinding、登录限流、HTTP 客户端超时与 SMTP 目标校验;管理员配置的 AI 服务允许可信内网地址,非可信 Webhook 和远程资源继续限制为公网目标。 自动化与通知:为发货、评价赠送、邀评和回复动作增加断点、租约、延迟执行及人工继续/重试/取消入口;通知改为 outbox 驱动的可恢复投递。同步完善账号运行态、暂停状态、续期冷却、告警审计和异常查询接口。 前端体验:新增风控验证面板、方形二维码、账号运行态合并、暂停状态保护、自动化异常处置、批量铺货状态选择、订单导入结果和最新请求门禁。完善订单搜索与导入、规则编辑、批次恢复、通知与设置页面,并为请求取消、超时、陈旧响应和主要状态转换补充 Vitest 覆盖。 测试与部署:扩展三库功能编排、SQLite 一致性备份、数据卷持久化、浏览器集成镜像、前端类型检查和构建资产分包;功能测试覆盖健康检查、订单、铺货、自动化异常、账号暂停、关键词和系统设置。更新 README 中数据密钥、可信 AI 地址和测试端口说明。 验证结果:go vet ./...、go build ./cmd/server、gofmt 检查、npm run typecheck、npm test(17 个文件、95 个用例)及 npm run build 通过。go test ./... 未完全通过:internal/adapter 仍有 2 个密码续期用例失败,internal/renewal 仍有 4 个浏览器续期调度用例失败;其余 Go 包通过,失败现状随本次既有工作区一并提交。
186 lines
5.9 KiB
Go
186 lines
5.9 KiB
Go
// Package db 提供数据库连接管理与迁移。
|
||
//
|
||
// 支持三种数据库,由连接 URL 的 scheme 决定:
|
||
// - sqlite://<path> 纯 Go modernc.org/sqlite,WAL + foreign_keys(默认,本地开发)
|
||
// - mysql://<dsn> go-sql-driver/mysql(生产/Docker 外置数据库)
|
||
// - postgres://<dsn> jackc/pgx(生产/Docker 外置数据库)
|
||
//
|
||
// 迁移用 goose 嵌入式执行,按方言分目录:migrations/{sqlite,mysql,postgres}。
|
||
// 00001 初始 schema 已把历史上运行时 ALTER TABLE 的列补齐到 CREATE TABLE,
|
||
// 并修复 schema 不一致(如 orders.system_shipped 原 CREATE 缺失却被引用)。
|
||
package db
|
||
|
||
import (
|
||
"context"
|
||
"database/sql"
|
||
"embed"
|
||
"fmt"
|
||
"strings"
|
||
"time"
|
||
|
||
_ "github.com/go-sql-driver/mysql"
|
||
_ "github.com/jackc/pgx/v5/stdlib"
|
||
"github.com/pressly/goose/v3"
|
||
_ "modernc.org/sqlite"
|
||
)
|
||
|
||
//go:embed migrations/sqlite/*.sql migrations/mysql/*.sql migrations/postgres/*.sql
|
||
var migrationsFS embed.FS
|
||
|
||
// Dialect 标识数据库方言。
|
||
type Dialect string
|
||
|
||
const (
|
||
DialectSQLite Dialect = "sqlite"
|
||
DialectMySQL Dialect = "mysql"
|
||
DialectPostgres Dialect = "postgres"
|
||
)
|
||
|
||
// driverName 内部 driver 名(传给 sql.Open)。
|
||
type driverName string
|
||
|
||
const (
|
||
driverSQLite driverName = "sqlite"
|
||
driverMySQL driverName = "mysql"
|
||
// driverPgx 走 pgx_compat driver(见 pgx_compat.go),把 ? 占位符重写成 $N。
|
||
driverPgx driverName = pgxCompatDriverName
|
||
)
|
||
|
||
// Open 打开/创建数据库并执行迁移。dbURL 形如:
|
||
//
|
||
// sqlite://data/xianyu_data.db
|
||
// mysql://user:pass@tcp(host:3306)/dbname?parseTime=true&loc=Local
|
||
// postgres://user:pass@host:5432/dbname?sslmode=disable
|
||
//
|
||
// 为向后兼容,传入的 dbURL 若不含 "://",则按 SQLite 文件路径处理。
|
||
func Open(ctx context.Context, dbURL string) (*sql.DB, Dialect, error) {
|
||
driver, dialect, dsn, err := parseDBURL(dbURL)
|
||
if err != nil {
|
||
return nil, "", err
|
||
}
|
||
db, err := sql.Open(string(driver), dsn)
|
||
if err != nil {
|
||
return nil, "", fmt.Errorf("打开数据库: %w", err)
|
||
}
|
||
|
||
// 连接池参数按 driver 调整:SQLite 写串行,单写多读;MySQL/PG 可多写并发。
|
||
switch driver {
|
||
case driverSQLite:
|
||
db.SetMaxOpenConns(8)
|
||
db.SetMaxIdleConns(4)
|
||
default:
|
||
db.SetMaxOpenConns(25)
|
||
db.SetMaxIdleConns(10)
|
||
}
|
||
db.SetConnMaxLifetime(time.Hour)
|
||
|
||
if err := db.PingContext(ctx); err != nil {
|
||
_ = db.Close()
|
||
return nil, "", fmt.Errorf("ping 数据库: %w", err)
|
||
}
|
||
|
||
if err := Migrate(ctx, db, dialect); err != nil {
|
||
_ = db.Close()
|
||
return nil, "", err
|
||
}
|
||
return db, dialect, nil
|
||
}
|
||
|
||
// parseDBURL 解析连接 URL,返回内部 driver 名、方言、DSN。
|
||
func parseDBURL(raw string) (driverName, Dialect, string, error) {
|
||
raw = strings.TrimSpace(raw)
|
||
if raw == "" {
|
||
return "", "", "", fmt.Errorf("数据库连接为空")
|
||
}
|
||
// 向后兼容:不含 scheme 视为 SQLite 文件路径。
|
||
if !strings.Contains(raw, "://") {
|
||
dsn := sqliteDSN(raw)
|
||
return driverSQLite, DialectSQLite, dsn, nil
|
||
}
|
||
idx := strings.Index(raw, "://")
|
||
scheme := raw[:idx]
|
||
rest := raw[idx+3:]
|
||
switch scheme {
|
||
case "sqlite", "sqlite3":
|
||
return driverSQLite, DialectSQLite, sqliteDSN(rest), nil
|
||
case "mysql":
|
||
// MySQL DSN: user:pass@tcp(host:port)/db?params(无 scheme)
|
||
// goose 多语句迁移需要 multiStatements=true,缺失会静默只执行首条语句。
|
||
return driverMySQL, DialectMySQL, mysqlDSN(rest), nil
|
||
case "postgres", "postgresql", "pgx":
|
||
// pgx 接受完整 postgres:// URL;也接受 libpq key=value DSN。
|
||
// 只有明确的 key=value 形式才去掉伪 scheme;URL 即便省略用户名也必须保留 scheme。
|
||
if strings.Contains(rest, "=") && !strings.Contains(rest, "/") {
|
||
return driverPgx, DialectPostgres, rest, nil
|
||
}
|
||
return driverPgx, DialectPostgres, scheme + "://" + rest, nil
|
||
default:
|
||
return "", "", "", fmt.Errorf("不支持的数据库 scheme: %s(支持 sqlite/mysql/postgres)", scheme)
|
||
}
|
||
}
|
||
|
||
// sqliteDSN 构造 SQLite DSN,开启 WAL/foreign_keys/busy_timeout/synchronous。
|
||
func sqliteDSN(path string) string {
|
||
return fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)", path)
|
||
}
|
||
|
||
// mysqlDSN 强制启用应用依赖的两个连接选项:
|
||
// - multiStatements:goose 多语句迁移需要,缺失会静默只执行首条语句;
|
||
// - clientFoundRows:RowsAffected 返回匹配行数,使“保存未变化内容”的语义与 SQLite/Postgres 一致。
|
||
//
|
||
// 其余参数原样保留。不强制 parseTime——本仓库时间列按 string/int64 扫描。
|
||
func mysqlDSN(dsn string) string {
|
||
dsn = forceMySQLBoolParam(dsn, "multiStatements")
|
||
return forceMySQLBoolParam(dsn, "clientFoundRows")
|
||
}
|
||
|
||
func forceMySQLBoolParam(dsn, key string) string {
|
||
base, rawQuery, hasQuery := strings.Cut(dsn, "?")
|
||
parts := make([]string, 0, 4)
|
||
found := false
|
||
if hasQuery {
|
||
for _, part := range strings.Split(rawQuery, "&") {
|
||
if part == "" {
|
||
continue
|
||
}
|
||
name, _, _ := strings.Cut(part, "=")
|
||
if name == key {
|
||
if !found {
|
||
parts = append(parts, key+"=true")
|
||
found = true
|
||
}
|
||
continue
|
||
}
|
||
parts = append(parts, part)
|
||
}
|
||
}
|
||
if !found {
|
||
parts = append(parts, key+"=true")
|
||
}
|
||
return base + "?" + strings.Join(parts, "&")
|
||
}
|
||
|
||
// Migrate 执行嵌入式 goose 迁移,按方言选择子目录。
|
||
func Migrate(ctx context.Context, db *sql.DB, dialect Dialect) error {
|
||
var gooseDialect string
|
||
var subdir string
|
||
switch dialect {
|
||
case DialectSQLite:
|
||
gooseDialect, subdir = "sqlite3", "sqlite"
|
||
case DialectMySQL:
|
||
gooseDialect, subdir = "mysql", "mysql"
|
||
case DialectPostgres:
|
||
gooseDialect, subdir = "postgres", "postgres"
|
||
default:
|
||
return fmt.Errorf("未知方言: %s", dialect)
|
||
}
|
||
if err := goose.SetDialect(gooseDialect); err != nil {
|
||
return fmt.Errorf("设置 goose dialect: %w", err)
|
||
}
|
||
goose.SetBaseFS(migrationsFS)
|
||
if err := goose.Up(db, "migrations/"+subdir); err != nil {
|
||
return fmt.Errorf("执行迁移: %w", err)
|
||
}
|
||
return nil
|
||
}
|