可靠性与数据一致性:为 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 包通过,失败现状随本次既有工作区一并提交。
270 lines
9.3 KiB
Go
270 lines
9.3 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// RenewalAccount 是续期调度所需的账号视图。
|
|
type RenewalAccount struct {
|
|
ID string
|
|
Value string
|
|
UserID int64
|
|
Enabled bool
|
|
DisableReason string
|
|
Username string
|
|
Password string
|
|
ShowBrowser bool
|
|
MetadataJSON string
|
|
LastRefreshAt int64
|
|
}
|
|
|
|
// CookieRefreshSchedule 对应 cookie_refresh_schedules。
|
|
type CookieRefreshSchedule struct {
|
|
CookieID string
|
|
ExpireAt int64
|
|
Disabled bool
|
|
ConsecutiveFailures int
|
|
LastError string
|
|
LastStatus string
|
|
LastErrorMessage string
|
|
LastRefreshAt int64
|
|
}
|
|
|
|
// RenewalLog 是三类续期任务日志的通用写入模型。
|
|
type RenewalLog struct {
|
|
BatchID string
|
|
CookieID string
|
|
Status string
|
|
Message string
|
|
ErrorMessage string
|
|
UpdatedCookieNames []string
|
|
UpdatedCookieCount int
|
|
ResponseContent string
|
|
StepDetails string
|
|
RenewMethod string
|
|
DurationMS int64
|
|
RequestCount int
|
|
NextExpireAt int64
|
|
}
|
|
|
|
// RenewalStore 保存续期任务计划与日志。
|
|
type RenewalStore struct {
|
|
DB *sql.DB
|
|
Dialect Dialect
|
|
}
|
|
|
|
// AllRenewalAccounts 返回所有账号,包含启用状态;浏览器 cookie 续期会用到禁用账号。
|
|
func (c *Cookies) AllRenewalAccounts(ctx context.Context) ([]RenewalAccount, error) {
|
|
rows, err := c.DB.QueryContext(ctx,
|
|
`SELECT c.id, c.value, c.user_id, COALESCE(cs.enabled, 1), COALESCE(cs.disable_reason,''),
|
|
COALESCE(c.username,''), COALESCE(c.password,''), COALESCE(c.show_browser,0),
|
|
COALESCE(c.metadata_json,''), COALESCE(c.last_refresh_at,0)
|
|
FROM cookies c
|
|
LEFT JOIN cookie_status cs ON cs.cookie_id = c.id
|
|
ORDER BY c.id`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
return scanRenewalAccounts(rows)
|
|
}
|
|
|
|
// ActiveRenewalAccounts 返回启用账号,用于 WS/API 续期类任务。
|
|
func (c *Cookies) ActiveRenewalAccounts(ctx context.Context) ([]RenewalAccount, error) {
|
|
rows, err := c.DB.QueryContext(ctx,
|
|
`SELECT c.id, c.value, c.user_id, COALESCE(cs.enabled, 1), COALESCE(cs.disable_reason,''),
|
|
COALESCE(c.username,''), COALESCE(c.password,''), COALESCE(c.show_browser,0),
|
|
COALESCE(c.metadata_json,''), COALESCE(c.last_refresh_at,0)
|
|
FROM cookies c
|
|
LEFT JOIN cookie_status cs ON cs.cookie_id = c.id
|
|
WHERE COALESCE(cs.enabled, 1) <> 0
|
|
ORDER BY c.id`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
return scanRenewalAccounts(rows)
|
|
}
|
|
|
|
func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
|
|
var out []RenewalAccount
|
|
for rows.Next() {
|
|
var a RenewalAccount
|
|
var enabled, showBrowser int
|
|
if err := rows.Scan(&a.ID, &a.Value, &a.UserID, &enabled, &a.DisableReason, &a.Username, &a.Password, &showBrowser, &a.MetadataJSON, &a.LastRefreshAt); err != nil {
|
|
return nil, err
|
|
}
|
|
a.Enabled = enabled != 0
|
|
a.ShowBrowser = showBrowser != 0
|
|
out = append(out, a)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// UpdateRenewalCookie 保存续期后的 Cookie,同时写入浏览器快照和最后续期时间。
|
|
func (c *Cookies) UpdateRenewalCookie(ctx context.Context, cookieID, cookieValue, metadataJSON string, lastRefreshAt int64) error {
|
|
if lastRefreshAt <= 0 {
|
|
lastRefreshAt = time.Now().Unix()
|
|
}
|
|
_, err := c.DB.ExecContext(ctx,
|
|
`UPDATE cookies
|
|
SET value=?, metadata_json=?, last_refresh_at=?, updated_at=CURRENT_TIMESTAMP
|
|
WHERE id=?`,
|
|
cookieValue, metadataJSON, lastRefreshAt, cookieID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetCookieRefreshSchedule 读取浏览器 Cookie 续期计划。
|
|
func (r *RenewalStore) GetCookieRefreshSchedule(ctx context.Context, cookieID string) (*CookieRefreshSchedule, error) {
|
|
var s CookieRefreshSchedule
|
|
var disabled int
|
|
err := r.DB.QueryRowContext(ctx,
|
|
`SELECT cookie_id, expire_at, disabled, consecutive_failures, COALESCE(last_error,''),
|
|
COALESCE(last_status,''), COALESCE(last_error_message,''), COALESCE(last_refresh_at,0)
|
|
FROM cookie_refresh_schedules WHERE cookie_id=?`, cookieID).
|
|
Scan(&s.CookieID, &s.ExpireAt, &disabled, &s.ConsecutiveFailures, &s.LastError,
|
|
&s.LastStatus, &s.LastErrorMessage, &s.LastRefreshAt)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
s.Disabled = disabled != 0
|
|
return &s, nil
|
|
}
|
|
|
|
// UpsertCookieRefreshSchedule 写入浏览器 Cookie 续期计划。
|
|
func (r *RenewalStore) UpsertCookieRefreshSchedule(ctx context.Context, s CookieRefreshSchedule) error {
|
|
disabled := 0
|
|
if s.Disabled {
|
|
disabled = 1
|
|
}
|
|
_, err := r.DB.ExecContext(ctx,
|
|
`INSERT INTO cookie_refresh_schedules
|
|
(cookie_id, expire_at, disabled, consecutive_failures, last_error,
|
|
last_status, last_error_message, last_refresh_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`+
|
|
dialectUpsert(r.Dialect, []string{"cookie_id"}, map[string]string{
|
|
"expire_at": "EXCLUDED.expire_at",
|
|
"disabled": "EXCLUDED.disabled",
|
|
"consecutive_failures": "EXCLUDED.consecutive_failures",
|
|
"last_error": "EXCLUDED.last_error",
|
|
"last_status": "EXCLUDED.last_status",
|
|
"last_error_message": "EXCLUDED.last_error_message",
|
|
"last_refresh_at": "EXCLUDED.last_refresh_at",
|
|
"updated_at": "CURRENT_TIMESTAMP",
|
|
}),
|
|
s.CookieID, s.ExpireAt, disabled, s.ConsecutiveFailures, s.LastError,
|
|
s.LastStatus, s.LastErrorMessage, s.LastRefreshAt)
|
|
return err
|
|
}
|
|
|
|
// AddBrowserCookieRenewLog 记录浏览器 Cookie 续期日志。
|
|
func (r *RenewalStore) AddBrowserCookieRenewLog(ctx context.Context, log RenewalLog) error {
|
|
if log.UpdatedCookieCount == 0 {
|
|
log.UpdatedCookieCount = len(log.UpdatedCookieNames)
|
|
}
|
|
_, err := r.DB.ExecContext(ctx,
|
|
`INSERT INTO scheduled_cookies_refresh_log
|
|
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
|
updated_cookie_count, next_expire_at, step_details, renew_method, duration_ms,
|
|
request_count, response_content, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
|
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
|
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.NextExpireAt,
|
|
log.StepDetails, log.RenewMethod, log.DurationMS, log.RequestCount, log.ResponseContent)
|
|
return err
|
|
}
|
|
|
|
// AddLoginRenewLog 记录 login_renew 任务日志。
|
|
func (r *RenewalStore) AddLoginRenewLog(ctx context.Context, log RenewalLog) error {
|
|
if log.UpdatedCookieCount == 0 {
|
|
log.UpdatedCookieCount = len(log.UpdatedCookieNames)
|
|
}
|
|
_, err := r.DB.ExecContext(ctx,
|
|
`INSERT INTO scheduled_login_renew_log
|
|
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
|
updated_cookie_count, step_details, renew_method, duration_ms, request_count,
|
|
response_content, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
|
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
|
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.StepDetails,
|
|
log.RenewMethod, log.DurationMS, log.RequestCount, log.ResponseContent)
|
|
return err
|
|
}
|
|
|
|
// AddAPICookieRenewLog 记录 api_cookie_renew 任务日志。
|
|
func (r *RenewalStore) AddAPICookieRenewLog(ctx context.Context, log RenewalLog) error {
|
|
if log.UpdatedCookieCount == 0 {
|
|
log.UpdatedCookieCount = len(log.UpdatedCookieNames)
|
|
}
|
|
_, err := r.DB.ExecContext(ctx,
|
|
`INSERT INTO scheduled_api_cookie_renew_log
|
|
(batch_id, cookie_id, status, message, error_message, updated_cookie_names,
|
|
updated_cookie_count, response_content, step_details, renew_method, duration_ms,
|
|
request_count, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
|
|
log.BatchID, log.CookieID, log.Status, log.Message, firstNonEmpty(log.ErrorMessage, log.Message),
|
|
strings.Join(log.UpdatedCookieNames, ","), log.UpdatedCookieCount, log.ResponseContent,
|
|
log.StepDetails, log.RenewMethod, log.DurationMS, log.RequestCount)
|
|
return err
|
|
}
|
|
|
|
// CleanupLogs deletes renewal logs older than retentionDays. Non-positive values skip cleanup.
|
|
func (r *RenewalStore) CleanupLogs(ctx context.Context, retentionDays int) error {
|
|
if retentionDays <= 0 {
|
|
return nil
|
|
}
|
|
cutoff := time.Now().AddDate(0, 0, -retentionDays)
|
|
for _, table := range []string{
|
|
"scheduled_cookies_refresh_log",
|
|
"scheduled_login_renew_log",
|
|
"scheduled_api_cookie_renew_log",
|
|
} {
|
|
if _, err := r.DB.ExecContext(ctx, `DELETE FROM `+table+` WHERE created_at < ?`, cutoff); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RecentBrowserCookieRenewStatuses 返回最近 limit 条浏览器续期日志状态。
|
|
func (r *RenewalStore) RecentBrowserCookieRenewStatuses(ctx context.Context, cookieID string, limit int) ([]string, error) {
|
|
if limit <= 0 {
|
|
return nil, nil
|
|
}
|
|
rows, err := r.DB.QueryContext(ctx,
|
|
`SELECT status FROM scheduled_cookies_refresh_log
|
|
WHERE cookie_id=? ORDER BY id DESC LIMIT ?`, cookieID, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var statuses []string
|
|
for rows.Next() {
|
|
var status string
|
|
if err := rows.Scan(&status); err != nil {
|
|
return nil, err
|
|
}
|
|
statuses = append(statuses, status)
|
|
}
|
|
return statuses, rows.Err()
|
|
}
|
|
|
|
func firstNonEmpty(values ...string) string {
|
|
for _, v := range values {
|
|
if strings.TrimSpace(v) != "" {
|
|
return v
|
|
}
|
|
}
|
|
return ""
|
|
}
|