推进P1后台任务与通知补偿收口
This commit is contained in:
1 parent
3fdd0fe267
commit
25531c05cb
15 files changed
+985
-59
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -78,7 +79,8 @@ func (s *Scheduler) WaitContext(ctx context.Context) error {
|
||||
|
||||
// scan 负责scan相关处理。
|
||||
func (s *Scheduler) scan(ctx context.Context) {
|
||||
s.runDeferredTasks(ctx)
|
||||
// deferredErr 汇总延迟任务状态收口失败,供本轮扫描结束时统一告警。
|
||||
deferredErr := s.runDeferredTasks(ctx)
|
||||
s.center.scanAccountTasks(ctx)
|
||||
if // recovered、err 保存recovered、err,供当前处理流程使用
|
||||
recovered, err := s.center.store.Automation.RecoverDefinitelyUnsentReviewRuns(ctx); err != nil {
|
||||
@@ -86,7 +88,12 @@ func (s *Scheduler) scan(ctx context.Context) {
|
||||
} else if recovered > 0 {
|
||||
s.center.logger.Info("已恢复历史求评价未发送任务,等待安全重试", "count", recovered)
|
||||
}
|
||||
s.runRecoveryTasks(ctx)
|
||||
// recoveryErr 汇总恢复运行状态收口失败,避免数据库写错误只记录日志后丢失。
|
||||
recoveryErr := s.runRecoveryTasks(ctx)
|
||||
if // scanErr 汇总两个自动化扫描阶段的状态收口错误,供统一告警使用。
|
||||
scanErr := errors.Join(deferredErr, recoveryErr); scanErr != nil {
|
||||
s.center.logger.Error("自动化计划任务状态收口失败", "err", scanErr)
|
||||
}
|
||||
// 逐页执行,避免把所有到期订单一次性装入内存。稳定 ID 游标确保本轮有界。
|
||||
afterOrderID := ""
|
||||
// waitingForWS 保存waitingForWS,供当前处理流程使用
|
||||
@@ -150,20 +157,23 @@ func (s *Scheduler) scan(ctx context.Context) {
|
||||
}
|
||||
|
||||
// runRecoveryTasks 负责运行Recovery任务列表相关处理。
|
||||
func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
func (s *Scheduler) runRecoveryTasks(ctx context.Context) error {
|
||||
// resultErr 汇总本轮恢复任务的持久化错误,调用方可据此触发统一告警。
|
||||
var resultErr error
|
||||
// runs、err 保存runs、err,供当前处理流程使用
|
||||
runs, err := s.center.store.Automation.DueRecoveryRuns(ctx, 100)
|
||||
if err != nil {
|
||||
s.center.logger.Warn("扫描失败自动化运行失败", "err", err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
// run 表示当前遍历过程中的运行
|
||||
for _, run := range runs {
|
||||
if run.ActionStarted {
|
||||
// reason 保存原因,供当前处理流程使用
|
||||
reason := "进程在外部动作执行期间中断,发送结果未知,已禁止自动重放"
|
||||
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
// quarantineErr 表示把外部动作结果未知的运行转为人工核对状态时的错误。
|
||||
quarantineErr := s.quarantineRunForReview(ctx, run, reason)
|
||||
resultErr = errors.Join(resultErr, quarantineErr)
|
||||
continue
|
||||
}
|
||||
// task 保存任务,供当前处理流程使用
|
||||
@@ -172,8 +182,9 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
err := json.Unmarshal([]byte(run.RawEventJSON), &task); err != nil || task.AccountID == "" {
|
||||
// reason 保存原因,供当前处理流程使用
|
||||
reason := "历史运行数据无法安全解析,已移入人工检查"
|
||||
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
// quarantineErr 表示历史任务无法解析时写入人工核对状态的错误。
|
||||
quarantineErr := s.quarantineRunForReview(ctx, run, reason)
|
||||
resultErr = errors.Join(resultErr, quarantineErr)
|
||||
continue
|
||||
}
|
||||
// allowed、err 保存allowed、err,供当前处理流程使用
|
||||
@@ -182,6 +193,7 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
if // postponeErr 保存postponeErr,供当前处理流程使用
|
||||
postponeErr := s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, run.AttemptCount, time.Now().UTC().Add(10*time.Minute).Unix()); postponeErr != nil {
|
||||
s.center.logger.Warn("延期自动化恢复任务失败", "run_id", run.ID, "err", postponeErr)
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("延期自动化恢复任务失败: %w", postponeErr))
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -189,7 +201,7 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
rule, err := s.center.store.Automation.Get(ctx, run.RuleID)
|
||||
if err != nil && !errors.Is(err, db.ErrNotFound) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
return errors.Join(resultErr, ctx.Err())
|
||||
}
|
||||
s.center.logger.Warn("读取自动化恢复规则失败,保留任务等待重试", "run_id", run.ID, "rule_id", run.RuleID, "err", err)
|
||||
continue
|
||||
@@ -197,19 +209,26 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
if errors.Is(err, db.ErrNotFound) || rule == nil || !rule.Enabled {
|
||||
// reason 保存原因,供当前处理流程使用
|
||||
reason := "自动化规则不存在或已停用,无法恢复"
|
||||
_ = s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
// quarantineErr 表示规则不可恢复时写入人工核对状态的错误。
|
||||
quarantineErr := s.quarantineRunForReview(ctx, run, reason)
|
||||
resultErr = errors.Join(resultErr, quarantineErr)
|
||||
continue
|
||||
}
|
||||
if recoveryNeedsSender(task, *rule, run.ActionCursor) && !s.center.accountSenderReady(task.AccountID) {
|
||||
if // postponeErr 保存postponeErr,供当前处理流程使用
|
||||
postponeErr := s.center.store.Automation.PostponeRecoveryRun(ctx, run.ID, run.AttemptCount, time.Now().UTC().Add(defaultReviewRequestScanInterval).Unix()); postponeErr != nil {
|
||||
s.center.logger.Warn("等待 WebSocket 时延期自动化任务失败", "run_id", run.ID, "err", postponeErr)
|
||||
resultErr = errors.Join(resultErr, fmt.Errorf("等待 WebSocket 时延期自动化任务失败: %w", postponeErr))
|
||||
}
|
||||
continue
|
||||
}
|
||||
// claimed、claimErr 保存claimed、claimErr,供当前处理流程使用
|
||||
claimed, claimErr := s.center.store.Automation.ClaimRecoveryRun(ctx, run.ID, time.Now().UTC().Add(5*time.Minute).Unix())
|
||||
if claimErr != nil {
|
||||
// claimFailure 表示领取恢复运行的状态写入失败,必须返回而不能被当作并发未领取。
|
||||
claimFailure := fmt.Errorf("领取自动化恢复任务失败: %w", claimErr)
|
||||
resultErr = errors.Join(resultErr, claimFailure)
|
||||
}
|
||||
if claimErr != nil || !claimed {
|
||||
continue
|
||||
}
|
||||
@@ -221,8 +240,26 @@ func (s *Scheduler) runRecoveryTasks(ctx context.Context) {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.center.executeRule(ctx, task, *rule); err != nil && !errors.Is(err, errAutomationDeferred) {
|
||||
s.center.logger.Warn("重试自动化运行失败", "run_id", run.ID, "err", err)
|
||||
resultErr = errors.Join(resultErr, err)
|
||||
}
|
||||
}
|
||||
return resultErr
|
||||
}
|
||||
|
||||
// quarantineRunForReview 将恢复运行置为人工核对并发送运维通知;写入失败时返回统一 needs_review 错误,禁止调用方误认为状态已收口。
|
||||
func (s *Scheduler) quarantineRunForReview(ctx context.Context, run db.AutomationRun, reason string) error {
|
||||
// quarantineErr 表示人工核对状态写入失败;失败时数据库中的原状态仍可能允许下一轮恢复。
|
||||
quarantineErr := s.center.store.Automation.QuarantineRun(ctx, run.ID, run.AttemptCount, reason)
|
||||
s.center.notifyRunNeedsReview(run, reason)
|
||||
if quarantineErr == nil {
|
||||
return nil
|
||||
}
|
||||
s.center.logger.Error("保存自动化恢复运行人工核对状态失败", "run_id", run.ID, "err", quarantineErr)
|
||||
return errors.Join(
|
||||
errAutomationNeedsReview,
|
||||
errAutomationQuarantine,
|
||||
fmt.Errorf("保存自动化恢复运行人工核对状态失败: %w", quarantineErr),
|
||||
)
|
||||
}
|
||||
|
||||
// recoveryNeedsSender 负责recoveryNeedsSender相关处理。
|
||||
@@ -244,12 +281,14 @@ func recoveryNeedsSender(task Task, rule db.AutomationRule, cursor int) bool {
|
||||
}
|
||||
|
||||
// runDeferredTasks 负责运行Deferred任务列表相关处理。
|
||||
func (s *Scheduler) runDeferredTasks(ctx context.Context) {
|
||||
func (s *Scheduler) runDeferredTasks(ctx context.Context) error {
|
||||
// resultErr 汇总延迟任务最终状态写入失败,避免领取成功后状态异常被静默吞掉。
|
||||
var resultErr error
|
||||
// tasks、err 保存tasks、err,供当前处理流程使用
|
||||
tasks, err := s.center.store.Automation.ClaimDueDeferredTasks(ctx, 100)
|
||||
if err != nil {
|
||||
s.center.logger.Warn("扫描暂停期间自动化事件失败", "err", err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
// pending 表示当前遍历过程中的pending
|
||||
for _, pending := range tasks {
|
||||
@@ -257,7 +296,16 @@ func (s *Scheduler) runDeferredTasks(ctx context.Context) {
|
||||
var task Task
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := json.Unmarshal([]byte(pending.TaskJSON), &task); err != nil {
|
||||
_ = s.center.store.Automation.FinishDeferredTask(ctx, pending.ID, pending.ClaimVersion, false, "解析任务失败: "+err.Error())
|
||||
// finishErr 表示解析失败后写入延迟任务重试或死信状态时的错误。
|
||||
finishErr := s.center.store.Automation.FinishDeferredTask(ctx, pending.ID, pending.ClaimVersion, false, "解析任务失败: "+err.Error())
|
||||
if finishErr != nil {
|
||||
s.center.logger.Error("保存解析失败的暂停事件状态失败", "task_id", pending.ID, "err", finishErr)
|
||||
resultErr = errors.Join(
|
||||
resultErr,
|
||||
errAutomationNeedsReview,
|
||||
fmt.Errorf("保存解析失败的暂停事件状态失败: %w", finishErr),
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if task.Raw == nil {
|
||||
@@ -273,8 +321,10 @@ func (s *Scheduler) runDeferredTasks(ctx context.Context) {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.center.store.Automation.FinishDeferredTask(ctx, pending.ID, pending.ClaimVersion, runErr == nil, errorString(runErr)); err != nil {
|
||||
s.center.logger.Warn("保存暂停事件重放结果失败", "task_id", pending.ID, "err", err)
|
||||
resultErr = errors.Join(resultErr, errAutomationNeedsReview, runErr, fmt.Errorf("保存暂停事件重放结果失败: %w", err))
|
||||
}
|
||||
}
|
||||
return resultErr
|
||||
}
|
||||
|
||||
// errorString 负责错误String相关处理。
|
||||
|
||||
@@ -2,9 +2,11 @@ package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -50,6 +52,149 @@ func TestParseReviewRuleConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSchedulerQuarantineSuccess 验证恢复任务成功隔离时返回 nil,并把运行状态写成 needs_review。
|
||||
func TestSchedulerQuarantineSuccess(t *testing.T) {
|
||||
// t 提供测试失败定位、临时目录和清理注册能力。
|
||||
_ = t
|
||||
// store 是本测试使用的 SQLite 自动化存储。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是恢复任务共用的数据库上下文。
|
||||
ctx := context.Background()
|
||||
// runID 是已执行外部动作且租约过期的运行主键。
|
||||
runID := seedExpiredRecoveryRun(t, store, ctx, "success")
|
||||
// scheduler 负责扫描并隔离过期恢复运行。
|
||||
scheduler := &Scheduler{center: New(store, testSenderProvider{sender: &testSender{}}, nil)}
|
||||
// runErr 保存本轮状态收口结果,成功隔离时不应产生错误。
|
||||
runErr := scheduler.runRecoveryTasks(ctx)
|
||||
if runErr != nil {
|
||||
t.Fatalf("隔离成功不应返回错误: %v", runErr)
|
||||
}
|
||||
// run 保存隔离后的运行记录,用于确认人工核对状态已落库。
|
||||
run, getErr := store.Automation.GetRun(ctx, runID)
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if run.Status != "needs_review" {
|
||||
t.Fatalf("status=%q want needs_review", run.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSchedulerQuarantineWriteFailureUsesJoinedNeedsReviewError 验证隔离写失败不会被吞掉,并保留 needs_review 与 quarantine 错误哨兵。
|
||||
func TestSchedulerQuarantineWriteFailureUsesJoinedNeedsReviewError(t *testing.T) {
|
||||
// t 提供测试失败定位、临时目录和清理注册能力。
|
||||
_ = t
|
||||
// store 是本测试使用的 SQLite 自动化存储。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是恢复任务共用的数据库上下文。
|
||||
ctx := context.Background()
|
||||
// runID 确保数据库中存在一条待隔离的过期运行。
|
||||
_ = seedExpiredRecoveryRun(t, store, ctx, "write-failure")
|
||||
// triggerErr 表示阻止人工核对状态写入的数据库触发器创建错误。
|
||||
if _, triggerErr := store.DB.ExecContext(ctx, `CREATE TRIGGER reject_scheduler_quarantine
|
||||
BEFORE UPDATE OF status ON automation_runs
|
||||
WHEN NEW.status='needs_review'
|
||||
BEGIN SELECT RAISE(ABORT, 'forced scheduler quarantine failure'); END`); triggerErr != nil {
|
||||
t.Fatal(triggerErr)
|
||||
}
|
||||
// scheduler 负责扫描并返回隔离写失败。
|
||||
scheduler := &Scheduler{center: New(store, testSenderProvider{sender: &testSender{}}, nil)}
|
||||
// runErr 保存统一收口错误,必须同时包含人工核对和隔离失败哨兵。
|
||||
runErr := scheduler.runRecoveryTasks(ctx)
|
||||
if runErr == nil || !errors.Is(runErr, errAutomationNeedsReview) || !errors.Is(runErr, errAutomationQuarantine) {
|
||||
t.Fatalf("runErr=%v want joined needs_review/quarantine error", runErr)
|
||||
}
|
||||
if !strings.Contains(runErr.Error(), "保存自动化恢复运行人工核对状态失败") {
|
||||
t.Fatalf("runErr=%v 缺少隔离写失败上下文", runErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSchedulerDeferredFinishWriteFailureUsesNeedsReviewError 验证非法延迟任务的最终状态写失败会返回人工核对错误。
|
||||
func TestSchedulerDeferredFinishWriteFailureUsesNeedsReviewError(t *testing.T) {
|
||||
// t 提供测试失败定位、临时目录和清理注册能力。
|
||||
_ = t
|
||||
// store 是本测试使用的 SQLite 自动化存储。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是延迟任务共用的数据库上下文。
|
||||
ctx := context.Background()
|
||||
// insertErr 表示写入故意非法延迟任务时的数据库错误。
|
||||
if _, insertErr := store.DB.ExecContext(ctx, `INSERT INTO automation_pending_tasks
|
||||
(task_key,cookie_id,trigger_type,task_json,due_at,status,attempt_count,lease_expires_at,error_message)
|
||||
VALUES ('cid:scheduler-bad','cid',?,'{"broken',0,'pending',0,0,'')`, TriggerBuyerReviewed); insertErr != nil {
|
||||
t.Fatal(insertErr)
|
||||
}
|
||||
// triggerErr 表示阻止非法任务进入重试或死信状态的数据库触发器创建错误。
|
||||
if _, triggerErr := store.DB.ExecContext(ctx, `CREATE TRIGGER reject_scheduler_deferred_finish
|
||||
BEFORE UPDATE OF status ON automation_pending_tasks
|
||||
WHEN NEW.status IN ('pending','dead_letter')
|
||||
BEGIN SELECT RAISE(ABORT, 'forced scheduler deferred finish failure'); END`); triggerErr != nil {
|
||||
t.Fatal(triggerErr)
|
||||
}
|
||||
// scheduler 负责扫描并返回延迟任务状态写失败。
|
||||
scheduler := &Scheduler{center: New(store, testSenderProvider{sender: &testSender{}}, nil)}
|
||||
// runErr 保存统一收口错误,避免状态写失败被当作已处理。
|
||||
runErr := scheduler.runDeferredTasks(ctx)
|
||||
if runErr == nil || !errors.Is(runErr, errAutomationNeedsReview) {
|
||||
t.Fatalf("runErr=%v want needs_review error", runErr)
|
||||
}
|
||||
if !strings.Contains(runErr.Error(), "保存解析失败的暂停事件状态失败") {
|
||||
t.Fatalf("runErr=%v 缺少延迟任务状态写失败上下文", runErr)
|
||||
}
|
||||
}
|
||||
|
||||
// seedExpiredRecoveryRun 创建一条外部动作已开始且租约已过期的恢复运行,供调度器状态收口测试复用。
|
||||
func seedExpiredRecoveryRun(t *testing.T, store *db.Store, ctx context.Context, suffix string) int64 {
|
||||
// t 提供测试失败定位和临时资源辅助能力。
|
||||
_ = t
|
||||
// store 是待写入恢复运行的自动化数据库存储。
|
||||
_ = store
|
||||
// ctx 约束本次恢复运行构造过程中的数据库操作。
|
||||
_ = ctx
|
||||
// suffix 区分同一测试数据库内的运行规则和触发键,避免测试数据冲突。
|
||||
_ = suffix
|
||||
t.Helper()
|
||||
// admin 是创建自动化规则所需的管理员用户。
|
||||
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// ruleID 是测试恢复运行引用的自动化规则主键。
|
||||
ruleID, ruleErr := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "scheduler-" + suffix, TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "must-not-repeat", Enabled: true}},
|
||||
})
|
||||
if ruleErr != nil {
|
||||
t.Fatal(ruleErr)
|
||||
}
|
||||
// task 是恢复运行中保存的无敏感事件快照。
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerBuyerReviewed, OrderID: "scheduler-" + suffix, ChatID: "chat", BuyerID: "buyer"}
|
||||
// raw 保存可被恢复逻辑解析的任务 JSON。
|
||||
raw, marshalErr := json.Marshal(task)
|
||||
if marshalErr != nil {
|
||||
t.Fatal(marshalErr)
|
||||
}
|
||||
// runID 是新建自动化运行的数据库主键。
|
||||
runID, started, startErr := store.Automation.TryStartRun(ctx, db.AutomationRun{
|
||||
RuleID: ruleID, CookieID: "cid", OrderID: task.OrderID, TriggerType: task.TriggerType,
|
||||
TriggerKey: "scheduler:" + suffix, RawEventJSON: string(raw), LeaseExpiresAt: time.Now().Add(time.Minute).Unix(),
|
||||
})
|
||||
if startErr != nil || !started {
|
||||
t.Fatalf("start=%v err=%v", started, startErr)
|
||||
}
|
||||
// actionStarted 表示恢复运行已进入外部动作检查点。
|
||||
actionStarted, actionErr := store.Automation.StartRunAction(ctx, runID, 1, 0, time.Now().Add(-time.Minute).Unix())
|
||||
if actionErr != nil || !actionStarted {
|
||||
t.Fatalf("start action=%v err=%v", actionStarted, actionErr)
|
||||
}
|
||||
// updateErr 表示把租约置为过期以便调度器选中运行时的数据库错误。
|
||||
if _, updateErr := store.DB.ExecContext(ctx, `UPDATE automation_runs SET lease_expires_at=0 WHERE id=?`, runID); updateErr != nil {
|
||||
t.Fatal(updateErr)
|
||||
}
|
||||
return runID
|
||||
}
|
||||
|
||||
// TestIntFromAny float64/int/string 三类来源 + 无效类型返回 0。
|
||||
func TestIntFromAny(t *testing.T) {
|
||||
// cases 保存cases,供当前处理流程使用
|
||||
|
||||
Reference in new issue
Block a user