feat(续期): 启用定时静默续期与失败告警
默认每四小时执行 API Cookie 续期,账号间错峰一分钟;记录全部续期结果,并在同一账号连续三次失败时发送续期告警。
This commit is contained in:
1 parent
090802e25d
commit
cef2ca92c4
4 files changed
+98
-10
No files matched your search
+1
-1
@@ -161,7 +161,7 @@ func main() {
|
|||||||
logger.Error("启动账号引擎失败", "err", err)
|
logger.Error("启动账号引擎失败", "err", err)
|
||||||
}
|
}
|
||||||
go automation.NewScheduler(autoCenter).Run(ctx)
|
go automation.NewScheduler(autoCenter).Run(ctx)
|
||||||
go renewal.NewScheduler(store, mgr, ap, logger).Run(ctx)
|
go renewal.NewScheduler(store, mgr, ap, logger, notifier).Run(ctx)
|
||||||
|
|
||||||
// 3) HTTP 服务。
|
// 3) HTTP 服务。
|
||||||
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||||
|
|||||||
@@ -261,6 +261,29 @@ func (r *RenewalStore) AddAPICookieRenewLog(ctx context.Context, log RenewalLog)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RecentAPICookieRenewStatuses 返回账号最近的 API Cookie 续期状态,最新记录在前。
|
||||||
|
func (r *RenewalStore) RecentAPICookieRenewStatuses(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_api_cookie_renew_log
|
||||||
|
WHERE cookie_id=? ORDER BY id DESC LIMIT ?`, cookieID, limit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
statuses := make([]string, 0, limit)
|
||||||
|
for rows.Next() {
|
||||||
|
var status string
|
||||||
|
if err := rows.Scan(&status); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
statuses = append(statuses, status)
|
||||||
|
}
|
||||||
|
return statuses, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
// CleanupLogs deletes renewal logs older than retentionDays. Non-positive values skip cleanup.
|
// CleanupLogs deletes renewal logs older than retentionDays. Non-positive values skip cleanup.
|
||||||
func (r *RenewalStore) CleanupLogs(ctx context.Context, retentionDays int) error {
|
func (r *RenewalStore) CleanupLogs(ctx context.Context, retentionDays int) error {
|
||||||
if retentionDays <= 0 {
|
if retentionDays <= 0 {
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ import (
|
|||||||
const (
|
const (
|
||||||
loginRenewInterval = 600 * time.Second
|
loginRenewInterval = 600 * time.Second
|
||||||
cookiesRefreshInterval = 600 * time.Second
|
cookiesRefreshInterval = 600 * time.Second
|
||||||
apiCookieRenewInterval = 3600 * time.Second
|
apiCookieRenewInterval = 4 * time.Hour
|
||||||
accountRequestInterval = time.Second
|
accountRequestInterval = time.Minute
|
||||||
sessionExpiredCooldown = 300 * time.Second
|
sessionExpiredCooldown = 300 * time.Second
|
||||||
passwordLoginCooldown = 300 * time.Second
|
passwordLoginCooldown = 300 * time.Second
|
||||||
passwordErrorCooldown = 5 * time.Hour
|
passwordErrorCooldown = 5 * time.Hour
|
||||||
@@ -56,12 +56,22 @@ type Scheduler struct {
|
|||||||
mtop *mtop.ClientImpl
|
mtop *mtop.ClientImpl
|
||||||
api apirenew.Service
|
api apirenew.Service
|
||||||
cooldown *CooldownManager
|
cooldown *CooldownManager
|
||||||
|
notifier RenewalNotifier
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRefresher, logger *slog.Logger) *Scheduler {
|
type RenewalNotifier interface {
|
||||||
|
NotifyAccountEvent(cookieID, eventType, level, title, body string)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewScheduler 的最后一个参数可选,用于发送连续续期失败告警,保持旧调用方兼容。
|
||||||
|
func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRefresher, logger *slog.Logger, notifiers ...RenewalNotifier) *Scheduler {
|
||||||
if logger == nil {
|
if logger == nil {
|
||||||
logger = slog.Default()
|
logger = slog.Default()
|
||||||
}
|
}
|
||||||
|
var notifier RenewalNotifier
|
||||||
|
if len(notifiers) > 0 {
|
||||||
|
notifier = notifiers[0]
|
||||||
|
}
|
||||||
return &Scheduler{
|
return &Scheduler{
|
||||||
store: store,
|
store: store,
|
||||||
starter: starter,
|
starter: starter,
|
||||||
@@ -70,6 +80,7 @@ func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRef
|
|||||||
mtop: mtop.NewClient(),
|
mtop: mtop.NewClient(),
|
||||||
api: apirenew.Service{},
|
api: apirenew.Service{},
|
||||||
cooldown: GlobalCooldown,
|
cooldown: GlobalCooldown,
|
||||||
|
notifier: notifier,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,9 +89,9 @@ func (s *Scheduler) Run(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
||||||
// 官网静默插件只在页面/账号运行时启动时执行,不做每小时轮询。保留
|
// 官网静默插件在账号启动时执行,并由此任务按保守频率持续检查;闲鱼
|
||||||
// 调度器入口供显式兼容配置使用,但默认关闭。
|
// 下发的 sdkSilent 疲劳窗口仍会在请求前阻止重复续期。
|
||||||
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, false, apiCookieRenewInterval, s.executeAPICookieRenew)
|
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, true, apiCookieRenewInterval, s.executeAPICookieRenew)
|
||||||
// 兼容原 cookies_refresh 配置名,但执行同一套 Go HTTP auto-login
|
// 兼容原 cookies_refresh 配置名,但执行同一套 Go HTTP auto-login
|
||||||
// 协议;Chromium 不参与普通 Cookie 续期。
|
// 协议;Chromium 不参与普通 Cookie 续期。
|
||||||
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeAPICookieRenew)
|
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeAPICookieRenew)
|
||||||
@@ -399,7 +410,28 @@ func (s *Scheduler) addLoginLog(ctx context.Context, batchID, cookieID, status,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Scheduler) addAPILog(ctx context.Context, log db.RenewalLog) {
|
func (s *Scheduler) addAPILog(ctx context.Context, log db.RenewalLog) {
|
||||||
_ = s.store.Renewal.AddAPICookieRenewLog(ctx, log)
|
if err := s.store.Renewal.AddAPICookieRenewLog(ctx, log); err != nil {
|
||||||
|
s.logger.Warn("记录 API Cookie 续期日志失败", "account", log.CookieID, "status", log.Status, "err", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if s.notifier == nil || log.Status != "failed" || s.store == nil || s.store.Renewal == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
statuses, err := s.store.Renewal.RecentAPICookieRenewStatuses(ctx, log.CookieID, 4)
|
||||||
|
if err != nil || len(statuses) < 3 || statuses[0] != "failed" || statuses[1] != "failed" || statuses[2] != "failed" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(statuses) >= 4 && statuses[3] == "failed" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reason := strings.TrimSpace(log.ErrorMessage)
|
||||||
|
if reason == "" {
|
||||||
|
reason = strings.TrimSpace(log.Message)
|
||||||
|
}
|
||||||
|
if reason == "" {
|
||||||
|
reason = "未知错误"
|
||||||
|
}
|
||||||
|
s.notifier.NotifyAccountEvent(log.CookieID, "token_renewal", "warn", "闲鱼 Cookie 自动续期连续失败", fmt.Sprintf("账号 %s 的 API 自动续期已连续失败 3 次,最近错误:%s", log.CookieID, reason))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Scheduler) cleanupExpiredLogs(ctx context.Context) {
|
func (s *Scheduler) cleanupExpiredLogs(ctx context.Context) {
|
||||||
|
|||||||
@@ -52,6 +52,18 @@ type schedulerFakePasswordRefresher struct {
|
|||||||
calls atomic.Int32
|
calls atomic.Int32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type schedulerFakeNotifier struct {
|
||||||
|
calls atomic.Int32
|
||||||
|
title string
|
||||||
|
message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *schedulerFakeNotifier) NotifyAccountEvent(_ string, _ string, _ string, title, body string) {
|
||||||
|
f.calls.Add(1)
|
||||||
|
f.title = title
|
||||||
|
f.message = body
|
||||||
|
}
|
||||||
|
|
||||||
func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, _ string) bool {
|
func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, _ string) bool {
|
||||||
f.calls.Add(1)
|
f.calls.Add(1)
|
||||||
return true
|
return true
|
||||||
@@ -121,8 +133,8 @@ func TestSchedulerIntervalsAligned(t *testing.T) {
|
|||||||
if cookiesRefreshInterval != 10*time.Minute {
|
if cookiesRefreshInterval != 10*time.Minute {
|
||||||
t.Fatalf("cookiesRefreshInterval=%s want 10m", cookiesRefreshInterval)
|
t.Fatalf("cookiesRefreshInterval=%s want 10m", cookiesRefreshInterval)
|
||||||
}
|
}
|
||||||
if apiCookieRenewInterval != time.Hour {
|
if apiCookieRenewInterval != 4*time.Hour {
|
||||||
t.Fatalf("apiCookieRenewInterval=%s want 1h", apiCookieRenewInterval)
|
t.Fatalf("apiCookieRenewInterval=%s want 4h", apiCookieRenewInterval)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,6 +155,27 @@ func TestSchedulerDefaultsMatchUpstreamConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAPICookieRenewFailureNotifiesOnlyAtThirdConsecutiveFailure(t *testing.T) {
|
||||||
|
store, cleanup := newSchedulerTestStore(t)
|
||||||
|
defer cleanup()
|
||||||
|
notifier := &schedulerFakeNotifier{}
|
||||||
|
s := NewScheduler(store, nil, nil, nil, notifier)
|
||||||
|
ctx := context.Background()
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
s.addAPILog(ctx, db.RenewalLog{BatchID: "batch", CookieID: "cid-failure", Status: "failed", ErrorMessage: "接口超时"})
|
||||||
|
}
|
||||||
|
if notifier.calls.Load() != 1 {
|
||||||
|
t.Fatalf("连续三次失败应通知 1 次,实际 %d", notifier.calls.Load())
|
||||||
|
}
|
||||||
|
if notifier.title == "" || !strings.Contains(notifier.message, "连续失败 3 次") {
|
||||||
|
t.Fatalf("通知内容异常: title=%q body=%q", notifier.title, notifier.message)
|
||||||
|
}
|
||||||
|
s.addAPILog(ctx, db.RenewalLog{BatchID: "batch", CookieID: "cid-failure", Status: "failed", ErrorMessage: "接口超时"})
|
||||||
|
if notifier.calls.Load() != 1 {
|
||||||
|
t.Fatalf("连续第四次失败不应重复通知,实际 %d", notifier.calls.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
|
func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
|
||||||
store, cleanup := newSchedulerTestStore(t)
|
store, cleanup := newSchedulerTestStore(t)
|
||||||
defer cleanup()
|
defer cleanup()
|
||||||
|
|||||||
Reference in new issue
Block a user