diff --git a/cmd/server/main.go b/cmd/server/main.go index a182c04..8c76fd2 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -161,7 +161,7 @@ func main() { logger.Error("启动账号引擎失败", "err", err) } 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 服务。 srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier) diff --git a/internal/db/renewal.go b/internal/db/renewal.go index 5e9abd6..e449a03 100644 --- a/internal/db/renewal.go +++ b/internal/db/renewal.go @@ -261,6 +261,29 @@ func (r *RenewalStore) AddAPICookieRenewLog(ctx context.Context, log RenewalLog) 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. func (r *RenewalStore) CleanupLogs(ctx context.Context, retentionDays int) error { if retentionDays <= 0 { diff --git a/internal/renewal/scheduler.go b/internal/renewal/scheduler.go index 7a26081..721470f 100644 --- a/internal/renewal/scheduler.go +++ b/internal/renewal/scheduler.go @@ -20,8 +20,8 @@ import ( const ( loginRenewInterval = 600 * time.Second cookiesRefreshInterval = 600 * time.Second - apiCookieRenewInterval = 3600 * time.Second - accountRequestInterval = time.Second + apiCookieRenewInterval = 4 * time.Hour + accountRequestInterval = time.Minute sessionExpiredCooldown = 300 * time.Second passwordLoginCooldown = 300 * time.Second passwordErrorCooldown = 5 * time.Hour @@ -56,12 +56,22 @@ type Scheduler struct { mtop *mtop.ClientImpl api apirenew.Service 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 { logger = slog.Default() } + var notifier RenewalNotifier + if len(notifiers) > 0 { + notifier = notifiers[0] + } return &Scheduler{ store: store, starter: starter, @@ -70,6 +80,7 @@ func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRef mtop: mtop.NewClient(), api: apirenew.Service{}, cooldown: GlobalCooldown, + notifier: notifier, } } @@ -78,9 +89,9 @@ func (s *Scheduler) Run(ctx context.Context) { return } go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew) - // 官网静默插件只在页面/账号运行时启动时执行,不做每小时轮询。保留 - // 调度器入口供显式兼容配置使用,但默认关闭。 - go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, false, apiCookieRenewInterval, s.executeAPICookieRenew) + // 官网静默插件在账号启动时执行,并由此任务按保守频率持续检查;闲鱼 + // 下发的 sdkSilent 疲劳窗口仍会在请求前阻止重复续期。 + go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, true, apiCookieRenewInterval, s.executeAPICookieRenew) // 兼容原 cookies_refresh 配置名,但执行同一套 Go HTTP auto-login // 协议;Chromium 不参与普通 Cookie 续期。 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) { - _ = 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) { diff --git a/internal/renewal/scheduler_test.go b/internal/renewal/scheduler_test.go index 6b8343a..34724ba 100644 --- a/internal/renewal/scheduler_test.go +++ b/internal/renewal/scheduler_test.go @@ -52,6 +52,18 @@ type schedulerFakePasswordRefresher struct { 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 { f.calls.Add(1) return true @@ -121,8 +133,8 @@ func TestSchedulerIntervalsAligned(t *testing.T) { if cookiesRefreshInterval != 10*time.Minute { t.Fatalf("cookiesRefreshInterval=%s want 10m", cookiesRefreshInterval) } - if apiCookieRenewInterval != time.Hour { - t.Fatalf("apiCookieRenewInterval=%s want 1h", apiCookieRenewInterval) + if apiCookieRenewInterval != 4*time.Hour { + 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) { store, cleanup := newSchedulerTestStore(t) defer cleanup()