修复 WS Token 主动轮换与自动化任务恢复

根据服务端过期时间提前轮换 WS Token,并对缺失期限使用保守刷新窗口。

Token 获取瞬时失败时保持账号运行并在过期前持续重试;统一 Cookie、WS 恢复后的自动化唤醒和安全动作游标重试。

修复多实例恢复租约覆盖、规则查询误隔离及人工核对状态落库错误,并等待自动化调度器、续期 watcher 和批量发布恢复任务优雅退出。

补充 SQLite、PostgreSQL 17、生命周期和竞态回归测试。
This commit is contained in:
Christ committed 2026-08-05 14:50:39 +08:00
1 parent 9c742f5e7f
commit bdc64c68f6
24 files changed
+1080 -110

No files matched your search

+27 -12
View File
@@ -12,6 +12,9 @@ import (
var ErrAutomationRunActive = errors.New("规则仍有待处理的自动化运行")
// SafeRetryErrorPrefix 标记当前动作明确没有产生外部副作用,可以从动作游标安全恢复。
const SafeRetryErrorPrefix = "[safe_retry]"
// AutomationRules 管理自动化规则、动作和执行记录。
//
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
@@ -442,7 +445,8 @@ func (a *AutomationRules) reclaimRun(ctx context.Context, ruleID int64, triggerK
attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
WHERE rule_id=? AND trigger_key=?
AND ((status='running' AND action_started=0 AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`,
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`,
leaseExpiresAt, ruleID, triggerKey, now, now)
if err != nil {
return 0, false, err
@@ -536,20 +540,25 @@ func (a *AutomationRules) QuarantineRunResult(ctx context.Context, runID int64,
}
// PostponeRecoveryRun 把暂时不能执行的账号移到恢复队列尾部,避免固定的前 100 条饿死后续任务。
func (a *AutomationRules) PostponeRecoveryRun(ctx context.Context, runID, retryAt int64) error {
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
func (a *AutomationRules) PostponeRecoveryRun(ctx context.Context, runID int64, attempt int, retryAt int64) error {
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
SET lease_expires_at=CASE WHEN status='running' THEN ? ELSE lease_expires_at END,
next_retry_at=CASE WHEN status='failed' THEN ? ELSE next_retry_at END,
updated_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('running','failed')`, retryAt, retryAt, runID)
return err
updated_at=CURRENT_TIMESTAMP
WHERE id=? AND attempt_count=? AND action_started=0 AND status IN ('running','failed')`, retryAt, retryAt, runID, attempt)
if err != nil {
return err
}
return requireAutomationRunOwner(res)
}
func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpiresAt int64) (bool, error) {
now := time.Now().UTC().Unix()
res, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
SET status='running',error_message='',lease_expires_at=?,next_retry_at=0,attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?))`, leaseExpiresAt, runID, now, now)
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND attempt_count<3 AND next_retry_at<=?
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`, leaseExpiresAt, runID, now, now)
if err != nil {
return false, err
}
@@ -560,7 +569,7 @@ func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpi
// FinishRun 标记执行完成或失败。
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, attempt int, status string, sentCount int, errMsg string) error {
nextRetryAt := int64(0)
if status == "failed" && sentCount == 0 {
if status == "failed" && (sentCount == 0 || strings.HasPrefix(errMsg, SafeRetryErrorPrefix)) {
nextRetryAt = time.Now().UTC().Add(time.Minute).Unix()
}
res, err := a.DB.ExecContext(ctx, `
@@ -596,7 +605,8 @@ SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigg
status,sent_count,error_message,raw_event_json,lease_expires_at,attempt_count,next_retry_at,action_cursor,action_started
FROM automation_runs
WHERE (status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
OR (status='failed' AND sent_count=0 AND attempt_count<3 AND next_retry_at<=?)
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
AND (sent_count=0 OR error_message LIKE '[safe_retry]%'))
ORDER BY updated_at,id LIMIT ?`, now, now, limit)
if err != nil {
return nil, err
@@ -875,14 +885,19 @@ func (a *AutomationRules) WakeCredentialBlocked(ctx context.Context, cookieID st
SET due_at=0,updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND status='pending'
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%')`, cookieID); err != nil {
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, cookieID); err != nil {
return err
}
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
SET next_retry_at=0,updated_at=CURRENT_TIMESTAMP
WHERE cookie_id=? AND status='failed' AND sent_count=0 AND action_started=0
WHERE cookie_id=? AND status='failed' AND action_started=0
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%')`, cookieID)
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
OR error_message LIKE '%消息连接%' OR error_message LIKE '%账号未在线%')`, cookieID)
return err
}
+41 -1
View File
@@ -504,6 +504,37 @@ func TestAutomationRunAttemptFencesStaleWorker(t *testing.T) {
}
}
func TestPostponeRecoveryRunCannotOverwriteNewOwnerLease(t *testing.T) {
s, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
uid, cid := seedAccount(t, s)
ruleID, _ := s.Automation.Create(ctx, makeAutomationRule(cid, uid, "item", "paid", true, 0))
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cid, TriggerType: "paid", TriggerKey: "postpone-fence"})
if err != nil || !started {
t.Fatalf("start run: id=%d started=%v err=%v", runID, started, err)
}
stale, err := s.Automation.GetRun(ctx, runID)
if err != nil {
t.Fatal(err)
}
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=0 WHERE id=?`, runID); err != nil {
t.Fatal(err)
}
newLease := time.Now().UTC().Add(5 * time.Minute).Unix()
claimed, err := s.Automation.ClaimRecoveryRun(ctx, runID, newLease)
if err != nil || !claimed {
t.Fatalf("claim=%v err=%v", claimed, err)
}
if err := s.Automation.PostponeRecoveryRun(ctx, runID, stale.AttemptCount, time.Now().UTC().Add(time.Minute).Unix()); !errors.Is(err, ErrAutomationRunLeaseLost) {
t.Fatalf("stale postpone err=%v want lease lost", err)
}
current, err := s.Automation.GetRun(ctx, runID)
if err != nil || current.LeaseExpiresAt != newLease {
t.Fatalf("new owner lease was overwritten: run=%+v err=%v", current, err)
}
}
// TestValidJSON validJSON 的非法 JSON 兜底为 {}。
func TestValidJSON(t *testing.T) {
if got := validJSON(""); got != "{}" {
@@ -562,7 +593,7 @@ func TestAutomationIssuesCanBeListedAndResolved(t *testing.T) {
if run.Status != "running" || run.ActionStarted || run.ActionCursor != 1 {
t.Fatalf("resolved run=%+v", run)
}
if err := s.Automation.PostponeRecoveryRun(ctx, runID, 4102444800); err != nil {
if err := s.Automation.PostponeRecoveryRun(ctx, runID, run.AttemptCount, 4102444800); err != nil {
t.Fatal(err)
}
due, err := s.Automation.DueRecoveryRuns(ctx, 10)
@@ -681,6 +712,15 @@ func TestDeferredRetryBackoffAndCredentialWake(t *testing.T) {
if err := s.Automation.WakeCredentialBlocked(ctx, cid); err != nil {
t.Fatal(err)
}
if err := s.Automation.DeferTask(ctx, DeferredAutomationTask{TaskKey: "ws-wake", CookieID: cid, TriggerType: "buyer_reviewed", TaskJSON: `{}`, DueAt: before + 3600, ErrorMessage: "当前没有可用 WebSocket 连接"}); err != nil {
t.Fatal(err)
}
if err := s.Automation.WakeCredentialBlocked(ctx, cid); err != nil {
t.Fatal(err)
}
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='ws-wake'`).Scan(&dueAt); err != nil || dueAt != 0 {
t.Fatalf("WS 恢复必须立即唤醒任务: due_at=%d err=%v", dueAt, err)
}
if err := s.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE id=?`, claimed[0].ID).Scan(&dueAt); err != nil || dueAt != 0 {
t.Fatalf("wake due_at=%d err=%v", dueAt, err)
}
+68
View File
@@ -639,6 +639,74 @@ func TestMultiDB_DeferredAutomationCredentialWake(t *testing.T) {
}
}
func TestMultiDB_AutomationSafeCheckpointRetry(t *testing.T) {
for _, tg := range allTestTargets(t) {
t.Run(tg.name, func(t *testing.T) {
defer tg.cleanup()
ctx := context.Background()
s := tg.store
suffix := fmt.Sprintf("%d", atomic.AddUint64(&multidbCounter, 1))
username := tg.name + "_checkpoint_user_" + suffix
if ok, err := s.Users.Create(ctx, username, username+"@e.com", "pw"); err != nil || !ok {
t.Fatalf("create user: ok=%v err=%v", ok, err)
}
user, _ := s.Users.GetByUsername(ctx, username)
cookieID := tg.name + "_checkpoint_cookie_" + suffix
if err := s.Cookies.Save(ctx, cookieID, "cv", user.ID); err != nil {
t.Fatal(err)
}
ruleID, err := s.Automation.Create(ctx, AutomationRuleInput{
UserID: user.ID, CookieID: cookieID, Name: "checkpoint", TriggerType: "order_paid", Enabled: true,
Actions: []AutomationActionInput{{ActionType: "send_text", Enabled: true}},
})
if err != nil {
t.Fatal(err)
}
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{
RuleID: ruleID, CookieID: cookieID, OrderID: "order-" + suffix,
TriggerType: "order_paid", TriggerKey: "order_paid:order-" + suffix, RawEventJSON: `{}`,
})
if err != nil || !started {
t.Fatalf("start run: started=%v err=%v", started, err)
}
if ok, err := s.Automation.StartRunAction(ctx, runID, 1, 0, time.Now().Add(time.Minute).Unix()); err != nil || !ok {
t.Fatalf("start first action: ok=%v err=%v", ok, err)
}
if err := s.Automation.AdvanceRunAction(ctx, runID, 1, 0, 1); err != nil {
t.Fatal(err)
}
if ok, err := s.Automation.StartRunAction(ctx, runID, 1, 1, time.Now().Add(time.Minute).Unix()); err != nil || !ok {
t.Fatalf("start second action: ok=%v err=%v", ok, err)
}
if err := s.Automation.AbortRunAction(ctx, runID, 1, 1); err != nil {
t.Fatal(err)
}
if err := s.Automation.FinishRun(ctx, runID, 1, "failed", 1, SafeRetryErrorPrefix+"session expired"); err != nil {
t.Fatal(err)
}
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE id=?`, runID); err != nil {
t.Fatal(err)
}
due, err := s.Automation.DueRecoveryRuns(ctx, 10)
if err != nil || len(due) != 1 || due[0].ID != runID || due[0].ActionCursor != 1 || due[0].SentCount != 1 {
t.Fatalf("due=%+v err=%v", due, err)
}
newLease := time.Now().Add(5 * time.Minute).Unix()
claimed, err := s.Automation.ClaimRecoveryRun(ctx, runID, newLease)
if err != nil || !claimed {
t.Fatalf("claim safe checkpoint: claimed=%v err=%v", claimed, err)
}
if err := s.Automation.PostponeRecoveryRun(ctx, runID, due[0].AttemptCount, time.Now().Add(time.Minute).Unix()); !errors.Is(err, ErrAutomationRunLeaseLost) {
t.Fatalf("stale postpone err=%v want lease lost", err)
}
current, err := s.Automation.GetRun(ctx, runID)
if err != nil || current.LeaseExpiresAt != newLease {
t.Fatalf("claimed lease overwritten: run=%+v err=%v", current, err)
}
})
}
}
// TestMultiDB_Notifications 验证通知渠道创建 + 账号绑定读写。
func TestMultiDB_Notifications(t *testing.T) {
for _, tg := range allTestTargets(t) {