推进P1批量发布Engine生命周期与账号任务收口
This commit is contained in:
1 parent
e53177ccd1
commit
417723d2c0
12 files changed
+918
-190
No files matched your search
@@ -791,6 +791,9 @@ npm --prefix frontend run build
|
||||
| 2026-08-15 | P1 账号资料刷新应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `internal/application/account` 的非敏感账号摘要、资料刷新 Port 和结果模型;资料刷新 handler 通过用户+账号联合查询完成归属校验,Server 只在既有账号适配边界转换 `db.CookieDetail` 与平台调用;删除旧的 Server 资料刷新双实现,新增应用服务构造、归属失败和平台失败测试,架构门禁、中文注释门禁和 Server 回归通过。账号登录凭证写入、扫码和其他账号操作仍待迁移 |
|
||||
| 2026-08-15 | P1 浏览器实例生命周期 CloseContext 切片 | 已完成本切片 | Browser Manager 增加活动调用登记、关闭 fencing、幂等 `CloseContext(ctx)` 和 `ErrManagerClosed`;`newPage`、初始化、二维码刷新及持久化续期上下文均在创建/释放时登记,关闭超时返回明确错误且可用更长 Context 重试,不创建游离关闭 goroutine;新增等待、超时重试和空管理器测试,浏览器全量及聚焦 race 通过。Playwright 底层同步 Close 无法被 Context 中断,Engine/账号其他任务仍待统一清单治理 |
|
||||
| 2026-08-15 | P1 自动化外部成功结果 quarantine 切片 | 已完成本切片 | 统一 automation run 在外部消息已发送但 `FinishRun` 落库失败时立即写入 `needs_review` quarantine 结果并返回 `errAutomationNeedsReview`,避免租约自然重放造成重复外部动作;quarantine 写入失败与 FinishRun 失败使用 `errors.Join` 返回,通知只发送一次;新增双重失败回归,automation 全量和 race 通过。账号任务等旁路仍有忽略 FinishRun/Mark* 错误,后续需继续盘点 |
|
||||
| 2026-08-15 | P1 商品批量发布应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `items.BatchRunner`、批次/明细模型、租约/取消/中断/收口 Port 和测试;批量 worker 的逐行 claim、失败分类、租约续期和上传清理从 Server 迁入应用层,Server 仅保留既有批量平台单行适配与数据库转换,未扩大新的临时低层白名单;批量 HTTP/应用回归、架构门禁和中文注释门禁通过。单行平台适配、商品同步及其他领域 Port 仍待治理 |
|
||||
| 2026-08-15 | P1 Engine 内部任务生命周期切片 | 已完成本切片 | Engine 迟到 API 续期 watcher 纳入账号生命周期 `beginTask/finishTask`,继承账号运行 Context,StopContext 会等待其退出;WS recorder 关闭等待改为 Context-aware,未启动 recorder 不误报超时,停止超时后可重试;新增任务超时/重试和迟到 watcher 回归,Engine 全量测试、聚焦 race 和中文注释门禁通过。其他 Engine 网络/浏览器任务仍需统一清单审计 |
|
||||
| 2026-08-15 | P1 账号自动化动作错误收口切片 | 已完成本切片 | 自动评价/擦亮任务不再吞 Cookie、FinishRun、MarkRateScan/MarkPolished 错误;外部动作成功但本地状态失败会写 `needs_review` 并返回 `errAutomationNeedsReview`,隔离写入失败使用 `errors.Join` 保留双重原因;新增单失败、双失败和日期写入失败回归,automation 全量测试通过。账号任务其他动作和通知旁路仍待盘点 |
|
||||
|
||||
### 11.2 执行纠偏审计(2026-08-15)
|
||||
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
package items
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrBatchLeaseLost 表示当前 worker 已不再拥有批次或明细租约。
|
||||
var ErrBatchLeaseLost = errors.New("批量任务租约已失效")
|
||||
|
||||
// BatchRow 是批量发布 worker 使用的纯业务明细,不暴露数据库行类型。
|
||||
type BatchRow struct {
|
||||
// ID 是批量明细行的持久化标识。
|
||||
ID int64
|
||||
// BatchID 是所属批次标识。
|
||||
BatchID string
|
||||
// CookieID 是执行发布的账号标识。
|
||||
CookieID string
|
||||
// Title 是商品标题。
|
||||
Title string
|
||||
// Description 是商品描述。
|
||||
Description string
|
||||
// Price 是用户输入的价格文本。
|
||||
Price string
|
||||
// OriginalPrice 是用户输入的原价文本。
|
||||
OriginalPrice string
|
||||
// Quantity 是商品库存数量。
|
||||
Quantity int
|
||||
// PostageMode 是邮费模式。
|
||||
PostageMode string
|
||||
// Postage 是用户输入的邮费文本。
|
||||
Postage string
|
||||
// ImagesJSON 是当前商品图片列表的 JSON。
|
||||
ImagesJSON string
|
||||
// CategoryJSON 是默认类目配置的 JSON。
|
||||
CategoryJSON string
|
||||
// AutomationJSON 是发布后自动化配置的 JSON。
|
||||
AutomationJSON string
|
||||
// RawJSON 是平台发布成功后保存的原始结果 JSON。
|
||||
RawJSON string
|
||||
// ItemID 是已知的平台商品标识;重试已远端成功的行时会复用它。
|
||||
ItemID string
|
||||
// ItemURL 是已知的平台商品地址。
|
||||
ItemURL string
|
||||
}
|
||||
|
||||
// BatchInfo 是批量发布状态收口所需的非敏感批次信息。
|
||||
type BatchInfo struct {
|
||||
// ID 是批次标识。
|
||||
ID string
|
||||
// UserID 是批次所属用户标识。
|
||||
UserID int64
|
||||
// Status 是当前批次状态。
|
||||
Status string
|
||||
// WorkerToken 是当前租约令牌。
|
||||
WorkerToken string
|
||||
// UploadDir 是批次上传文件的受控目录。
|
||||
UploadDir string
|
||||
// LocationJSON 是批次统一发货地配置的 JSON。
|
||||
LocationJSON string
|
||||
}
|
||||
|
||||
// BatchRepository 是批量发布 worker 所需的最小持久化端口。
|
||||
type BatchRepository interface {
|
||||
// PendingRows 查询当前批次中可处理的明细。
|
||||
PendingRows(context.Context, string, bool) ([]BatchRow, error)
|
||||
// RenewBatchLease 为当前 worker 延长批次租约。
|
||||
RenewBatchLease(context.Context, string, string, int64) (bool, error)
|
||||
// GetBatch 查询批次状态及其所属用户。
|
||||
GetBatch(context.Context, int64, string) (BatchInfo, error)
|
||||
// ClaimRow 抢占单条明细的处理租约。
|
||||
ClaimRow(context.Context, int64, string) (bool, error)
|
||||
// BatchStatus 读取批次状态用于分类失败原因。
|
||||
BatchStatus(context.Context, string) (string, error)
|
||||
// MarkClaimedRowFailed 保存当前 worker 处理失败的明细。
|
||||
MarkClaimedRowFailed(context.Context, int64, string, string, string) (bool, error)
|
||||
// RecountBatch 重算批次成功和失败统计。
|
||||
RecountBatch(context.Context, string) error
|
||||
// FinalizeBatch 尝试收口正常完成的批次。
|
||||
FinalizeBatch(context.Context, string, string) (string, bool, error)
|
||||
// FinalizeCanceled 收口已取消的批次。
|
||||
FinalizeCanceled(context.Context, string, string) (bool, error)
|
||||
// FinalizeInterrupted 收口被中断或超时的批次。
|
||||
FinalizeInterrupted(context.Context, string, string, string) (string, bool, error)
|
||||
// DeleteUpload 清理已完成批次的上传文件及其数据库记录。
|
||||
DeleteUpload(context.Context, string, string) error
|
||||
}
|
||||
|
||||
// BatchPublisher 执行单条商品发布;平台、凭证和自动化细节由适配器负责。
|
||||
type BatchPublisher interface {
|
||||
// PublishRow 发布一条批量商品并完成本地结果落库。
|
||||
PublishRow(context.Context, int64, BatchRow, string) error
|
||||
}
|
||||
|
||||
// FailureClassifier 将发布错误转换为用户可见消息和稳定失败分类。
|
||||
type FailureClassifier func(error, string) (string, string)
|
||||
|
||||
// BatchRunOptions 是 worker 生命周期与平台错误策略的可测试配置。
|
||||
type BatchRunOptions struct {
|
||||
// LeaseDuration 是每次续租所使用的租约时长。
|
||||
LeaseDuration time.Duration
|
||||
// JobDelay 根据已处理行下标返回下一行前的等待时长。
|
||||
JobDelay func(int) time.Duration
|
||||
// Wait 在等待行间隔期间响应 Context 取消。
|
||||
Wait func(context.Context, time.Duration) error
|
||||
// IsSessionExpired 判断错误是否要求立即中断剩余明细。
|
||||
IsSessionExpired func(error) bool
|
||||
// ClassifyFailure 生成失败明细的消息和分类。
|
||||
ClassifyFailure FailureClassifier
|
||||
}
|
||||
|
||||
// BatchRunner 编排批量发布 worker,不依赖 HTTP、数据库或平台 DTO。
|
||||
type BatchRunner struct {
|
||||
// repository 保存批次租约与状态。
|
||||
repository BatchRepository
|
||||
// publisher 执行单条商品发布适配。
|
||||
publisher BatchPublisher
|
||||
// options 保存时间、失败分类和取消策略。
|
||||
options BatchRunOptions
|
||||
}
|
||||
|
||||
// NewBatchRunner 创建批量发布 worker 编排器并校验必需端口。
|
||||
func NewBatchRunner(repository BatchRepository, publisher BatchPublisher, options BatchRunOptions) (*BatchRunner, error) {
|
||||
if repository == nil {
|
||||
return nil, errors.New("批量发布仓储端口不能为空")
|
||||
}
|
||||
if publisher == nil {
|
||||
return nil, errors.New("批量发布平台端口不能为空")
|
||||
}
|
||||
if options.LeaseDuration <= 0 {
|
||||
options.LeaseDuration = 5 * time.Minute
|
||||
}
|
||||
if options.JobDelay == nil {
|
||||
options.JobDelay = func(index int) time.Duration { return time.Duration(10+index%21) * time.Second }
|
||||
}
|
||||
if options.Wait == nil {
|
||||
options.Wait = waitWithContext
|
||||
}
|
||||
if options.IsSessionExpired == nil {
|
||||
options.IsSessionExpired = func(error) bool { return false }
|
||||
}
|
||||
if options.ClassifyFailure == nil {
|
||||
options.ClassifyFailure = defaultFailureClassifier
|
||||
}
|
||||
return &BatchRunner{repository: repository, publisher: publisher, options: options}, nil
|
||||
}
|
||||
|
||||
// Run 执行一个批次的租约续期、逐行发布、失败记录和最终状态收口。
|
||||
func (runner *BatchRunner) Run(ctx context.Context, userID int64, batchID, workerToken string, failedOnly bool) error {
|
||||
// rows 保存本次 worker 读取到的待处理明细。
|
||||
rows, err := runner.repository.PendingRows(ctx, batchID, failedOnly)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
}
|
||||
return err
|
||||
}
|
||||
// rowIndex 表示当前明细在 worker 队列中的下标;row 保存待发布商品明细。
|
||||
for rowIndex, row := range rows {
|
||||
if ctx.Err() != nil {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return ctx.Err()
|
||||
}
|
||||
// leaseCtx、leaseCancel 限制状态写入等待时间,避免 worker 退出时继续阻塞。
|
||||
leaseCtx, leaseCancel := statusContext(ctx)
|
||||
// leaseErr 保存批次续租或租约失效错误。
|
||||
leaseErr := runner.renewLease(leaseCtx, batchID, workerToken)
|
||||
leaseCancel()
|
||||
if leaseErr != nil {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return leaseErr
|
||||
}
|
||||
// batch 保存租约校验后的批次快照。
|
||||
batch, batchErr := runner.repository.GetBatch(ctx, userID, batchID)
|
||||
if batchErr != nil || batch.Status != "running" || batch.WorkerToken != workerToken {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return ErrBatchLeaseLost
|
||||
}
|
||||
// claimed 表示当前 worker 是否抢到这条明细。
|
||||
claimed, claimErr := runner.repository.ClaimRow(ctx, row.ID, workerToken)
|
||||
if claimErr != nil {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return claimErr
|
||||
}
|
||||
if !claimed {
|
||||
continue
|
||||
}
|
||||
// rowErr 保存当前商品发布及本地结果落库错误。
|
||||
if rowErr := runner.publisher.PublishRow(ctx, userID, row, workerToken); rowErr != nil {
|
||||
// status 保存失败分类所需的批次状态。
|
||||
status, _ := runner.repository.BatchStatus(ctx, batchID)
|
||||
// message、failureKind 保存用户可见失败信息和稳定分类。
|
||||
message, failureKind := runner.options.ClassifyFailure(rowErr, status)
|
||||
// marked、markErr 保存失败状态是否成功写入及其错误。
|
||||
marked, markErr := runner.repository.MarkClaimedRowFailed(ctx, row.ID, workerToken, message, failureKind)
|
||||
if markErr != nil || !marked {
|
||||
return fmt.Errorf("保存批量发布失败状态失败: %w", firstNonNil(markErr, ErrBatchLeaseLost))
|
||||
}
|
||||
if runner.options.IsSessionExpired(rowErr) {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return rowErr
|
||||
}
|
||||
}
|
||||
// recountErr 保存批次统计重算错误。
|
||||
if recountErr := runner.repository.RecountBatch(ctx, batchID); recountErr != nil {
|
||||
return recountErr
|
||||
}
|
||||
if rowIndex < len(rows)-1 {
|
||||
// waitErr 保存行间隔等待期间的取消错误。
|
||||
if waitErr := runner.options.Wait(ctx, runner.options.JobDelay(rowIndex)); waitErr != nil {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return waitErr
|
||||
}
|
||||
}
|
||||
}
|
||||
runner.finish(ctx, userID, batchID, workerToken)
|
||||
return nil
|
||||
}
|
||||
|
||||
// renewLease 续租批次并将失去租约转换为统一应用错误。
|
||||
func (runner *BatchRunner) renewLease(ctx context.Context, batchID, workerToken string) error {
|
||||
// renewed 表示数据库是否仍认可当前 worker 的租约。
|
||||
renewed, err := runner.repository.RenewBatchLease(ctx, batchID, workerToken, time.Now().UTC().Add(runner.options.LeaseDuration).Unix())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !renewed {
|
||||
return ErrBatchLeaseLost
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// finishInterrupted 在 worker 取消、超时或租约丢失后收口批次状态。
|
||||
func (runner *BatchRunner) finishInterrupted(ctx context.Context, userID int64, batchID, workerToken string) {
|
||||
// statusCtx、statusCancel 为状态收口提供独立的短超时。
|
||||
statusCtx, statusCancel := statusContext(ctx)
|
||||
defer statusCancel()
|
||||
// batch、err 保存收口前的批次状态。
|
||||
batch, err := runner.repository.GetBatch(statusCtx, userID, batchID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if batch.Status == "canceling" && batch.WorkerToken == workerToken {
|
||||
_, _ = runner.repository.FinalizeCanceled(statusCtx, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
if batch.Status == "canceled" {
|
||||
return
|
||||
}
|
||||
_, _, _ = runner.repository.FinalizeInterrupted(statusCtx, batchID, workerToken, "任务超时或已中断")
|
||||
}
|
||||
|
||||
// finish 收口正常完成或取消中的批次,并清理已完成批次的上传文件。
|
||||
func (runner *BatchRunner) finish(ctx context.Context, userID int64, batchID, workerToken string) {
|
||||
// statusCtx、statusCancel 为最终状态写入提供独立的短超时。
|
||||
statusCtx, statusCancel := statusContext(ctx)
|
||||
defer statusCancel()
|
||||
// batch、err 保存最终收口前的批次状态。
|
||||
batch, err := runner.repository.GetBatch(statusCtx, userID, batchID)
|
||||
if err != nil || batch.WorkerToken != workerToken || batch.Status == "canceled" {
|
||||
return
|
||||
}
|
||||
if batch.Status == "canceling" {
|
||||
_, _ = runner.repository.FinalizeCanceled(statusCtx, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
// finalStatus、finished、finishErr 保存数据库收口结果。
|
||||
finalStatus, finished, finishErr := runner.repository.FinalizeBatch(statusCtx, batchID, workerToken)
|
||||
if finishErr == nil && finished && finalStatus == "completed" && strings.TrimSpace(batch.UploadDir) != "" {
|
||||
_ = runner.repository.DeleteUpload(statusCtx, batch.ID, batch.UploadDir)
|
||||
}
|
||||
}
|
||||
|
||||
// statusContext 将状态写入限制在五秒内,同时在父 Context 已取消时保证可收口。
|
||||
func statusContext(parent context.Context) (context.Context, context.CancelFunc) {
|
||||
if parent != nil && parent.Err() == nil {
|
||||
return context.WithTimeout(parent, 5*time.Second)
|
||||
}
|
||||
return context.WithTimeout(context.Background(), 5*time.Second)
|
||||
}
|
||||
|
||||
// waitWithContext 按指定时长等待并响应 worker 取消。
|
||||
func waitWithContext(ctx context.Context, delay time.Duration) error {
|
||||
if delay <= 0 {
|
||||
return nil
|
||||
}
|
||||
// timer 保存当前行间隔定时器,必须在返回前停止或自然释放。
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// defaultFailureClassifier 提供平台无关的基础失败分类,平台适配器可注入更精确策略。
|
||||
func defaultFailureClassifier(err error, batchStatus string) (string, string) {
|
||||
// message 保存错误文本;取消状态只向用户展示取消结果。
|
||||
message := err.Error()
|
||||
if batchStatus == "canceled" || batchStatus == "canceling" {
|
||||
return "任务已取消", "publish"
|
||||
}
|
||||
return message, "publish"
|
||||
}
|
||||
|
||||
// firstNonNil 返回第一个非空错误,避免租约丢失时丢失更准确的数据库错误。
|
||||
func firstNonNil(err, fallback error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package items
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// batchRunnerRepository 是批量 worker 的内存仓储替身,用于记录状态写入顺序。
|
||||
type batchRunnerRepository struct {
|
||||
// rows 保存待处理明细。
|
||||
rows []BatchRow
|
||||
// batch 保存当前批次快照。
|
||||
batch BatchInfo
|
||||
// failed 保存失败明细的消息和分类。
|
||||
failed map[int64]string
|
||||
// finalized 保存最终状态收口次数。
|
||||
finalized int
|
||||
}
|
||||
|
||||
// PendingRows 返回预置的批量明细。
|
||||
func (r *batchRunnerRepository) PendingRows(_ context.Context, _ string, _ bool) ([]BatchRow, error) {
|
||||
return r.rows, nil
|
||||
}
|
||||
|
||||
// RenewBatchLease 保持内存批次租约有效。
|
||||
func (r *batchRunnerRepository) RenewBatchLease(_ context.Context, _, _ string, _ int64) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// GetBatch 返回当前批次快照。
|
||||
func (r *batchRunnerRepository) GetBatch(_ context.Context, _ int64, _ string) (BatchInfo, error) {
|
||||
return r.batch, nil
|
||||
}
|
||||
|
||||
// ClaimRow 始终允许测试 worker 抢占明细。
|
||||
func (r *batchRunnerRepository) ClaimRow(_ context.Context, _ int64, _ string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// BatchStatus 返回当前批次状态。
|
||||
func (r *batchRunnerRepository) BatchStatus(_ context.Context, _ string) (string, error) {
|
||||
return r.batch.Status, nil
|
||||
}
|
||||
|
||||
// MarkClaimedRowFailed 记录失败消息。
|
||||
func (r *batchRunnerRepository) MarkClaimedRowFailed(_ context.Context, rowID int64, _, message, _ string) (bool, error) {
|
||||
if r.failed == nil {
|
||||
r.failed = make(map[int64]string)
|
||||
}
|
||||
r.failed[rowID] = message
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// RecountBatch 表示测试仓储已完成统计重算。
|
||||
func (r *batchRunnerRepository) RecountBatch(_ context.Context, _ string) error { return nil }
|
||||
|
||||
// FinalizeBatch 记录正常收口并返回完成状态。
|
||||
func (r *batchRunnerRepository) FinalizeBatch(_ context.Context, _, _ string) (string, bool, error) {
|
||||
r.finalized++
|
||||
return "completed", true, nil
|
||||
}
|
||||
|
||||
// FinalizeCanceled 记录取消收口。
|
||||
func (r *batchRunnerRepository) FinalizeCanceled(_ context.Context, _, _ string) (bool, error) {
|
||||
r.finalized++
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// FinalizeInterrupted 记录中断收口。
|
||||
func (r *batchRunnerRepository) FinalizeInterrupted(_ context.Context, _, _, _ string) (string, bool, error) {
|
||||
r.finalized++
|
||||
return "failed", true, nil
|
||||
}
|
||||
|
||||
// DeleteUpload 记录上传目录清理调用。
|
||||
func (r *batchRunnerRepository) DeleteUpload(_ context.Context, _, _ string) error { return nil }
|
||||
|
||||
// batchRunnerPublisher 是可控的单行发布替身。
|
||||
type batchRunnerPublisher struct {
|
||||
// err 保存发布失败错误。
|
||||
err error
|
||||
// calls 统计发布调用次数。
|
||||
calls int
|
||||
}
|
||||
|
||||
// PublishRow 返回预置错误并统计调用次数。
|
||||
func (p *batchRunnerPublisher) PublishRow(_ context.Context, _ int64, _ BatchRow, _ string) error {
|
||||
p.calls++
|
||||
return p.err
|
||||
}
|
||||
|
||||
// TestBatchRunnerMarksFailureAndFinalizes 验证失败行记录与批次最终收口。
|
||||
func TestBatchRunnerMarksFailureAndFinalizes(t *testing.T) {
|
||||
// repository 保存批次状态和失败行。
|
||||
repository := &batchRunnerRepository{rows: []BatchRow{{ID: 1, BatchID: "batch-1"}}, batch: BatchInfo{ID: "batch-1", UserID: 7, Status: "running", WorkerToken: "worker"}}
|
||||
// publisher 模拟平台发布失败。
|
||||
publisher := &batchRunnerPublisher{err: errors.New("平台拒绝发布")}
|
||||
// runner 是使用零等待策略构造的应用 worker。
|
||||
// err 保存应用 worker 构造失败原因。
|
||||
runner, err := NewBatchRunner(repository, publisher, BatchRunOptions{Wait: func(context.Context, time.Duration) error { return nil }})
|
||||
if err != nil {
|
||||
t.Fatalf("构造 worker 失败: %v", err)
|
||||
}
|
||||
// err 保存 worker 运行失败原因。
|
||||
if err := runner.Run(context.Background(), 7, "batch-1", "worker", false); err != nil {
|
||||
t.Fatalf("运行 worker 失败: %v", err)
|
||||
}
|
||||
if publisher.calls != 1 || repository.failed[1] != "平台拒绝发布" || repository.finalized != 1 {
|
||||
t.Fatalf("worker 状态异常: calls=%d failed=%v finalized=%d", publisher.calls, repository.failed, repository.finalized)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBatchRunnerStopsOnCancellation 验证取消 Context 会触发中断收口且不发布后续明细。
|
||||
func TestBatchRunnerStopsOnCancellation(t *testing.T) {
|
||||
// repository 保存两条待处理明细和运行状态。
|
||||
repository := &batchRunnerRepository{rows: []BatchRow{{ID: 1, BatchID: "batch-2"}, {ID: 2, BatchID: "batch-2"}}, batch: BatchInfo{ID: "batch-2", UserID: 7, Status: "running", WorkerToken: "worker"}}
|
||||
// publisher 在首行发布时取消 Context。
|
||||
publisher := &batchRunnerPublisher{}
|
||||
// ctx、cancel 控制 worker 取消生命周期。
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
publisher.err = context.Canceled
|
||||
// runner 使用会返回取消错误的等待替身,避免测试等待真实间隔。
|
||||
runner, err := NewBatchRunner(repository, publisher, BatchRunOptions{Wait: func(context.Context, time.Duration) error { cancel(); return context.Canceled }, IsSessionExpired: func(error) bool { return true }})
|
||||
if err != nil {
|
||||
t.Fatalf("构造 worker 失败: %v", err)
|
||||
}
|
||||
// runErr 保存 worker 因取消 Context 返回的错误。
|
||||
if runErr := runner.Run(ctx, 7, "batch-2", "worker", false); !errors.Is(runErr, context.Canceled) {
|
||||
t.Fatalf("取消错误=%v", runErr)
|
||||
}
|
||||
if publisher.calls != 1 || repository.finalized != 1 {
|
||||
t.Fatalf("取消收口异常: calls=%d finalized=%d", publisher.calls, repository.finalized)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package automation
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -220,6 +221,45 @@ func (c *accountTaskCoordinator) accountCredentialFingerprint(ctx context.Contex
|
||||
return fmt.Sprintf("%x", sum[:]), nil
|
||||
}
|
||||
|
||||
// finishAccountTaskRun 保存账号任务的最终状态;首次写入失败时立即隔离运行记录,避免外部动作已经成功却被下一轮重复执行。
|
||||
// 返回值会同时保留首次写入和隔离写入的错误,调用方可据此告警并阻止自动重放。
|
||||
func (c *accountTaskCoordinator) finishAccountTaskRun(ctx context.Context, runKey, status string, success, failed int, message string, nextRetryAt int64) error {
|
||||
// finishErr 表示尝试写入预期运行状态时的数据库错误。
|
||||
finishErr := c.repository.FinishRun(ctx, runKey, status, success, failed, message, nextRetryAt)
|
||||
if finishErr == nil {
|
||||
return nil
|
||||
}
|
||||
// quarantineMessage 说明外部动作结果已经产生但本地状态未能正常收口,禁止系统自动重放。
|
||||
quarantineMessage := fmt.Sprintf("账号任务外部动作结果可能已执行,但运行状态保存失败,请人工核对,禁止自动重放: %v", finishErr)
|
||||
// quarantineErr 表示把运行记录转为人工核对状态时的数据库错误。
|
||||
quarantineErr := c.repository.FinishRun(ctx, runKey, "needs_review", success, failed, quarantineMessage, 0)
|
||||
if quarantineErr != nil {
|
||||
return errors.Join(
|
||||
errAutomationNeedsReview,
|
||||
fmt.Errorf("保存账号任务运行结果失败: %w", finishErr),
|
||||
fmt.Errorf("保存账号任务人工核对状态失败: %w", quarantineErr),
|
||||
)
|
||||
}
|
||||
return errors.Join(errAutomationNeedsReview, fmt.Errorf("保存账号任务运行结果失败: %w", finishErr))
|
||||
}
|
||||
|
||||
// quarantineAccountTaskRun 将外部动作结果未知的账号任务运行记录隔离到人工核对状态。
|
||||
// 当隔离写入再次失败时,返回值会保留原始原因和第二次数据库错误。
|
||||
func (c *accountTaskCoordinator) quarantineAccountTaskRun(ctx context.Context, runKey string, success, failed int, reason error) error {
|
||||
// quarantineMessage 将本地持久化故障转换为运维可识别的人工核对原因。
|
||||
quarantineMessage := fmt.Sprintf("账号任务外部动作结果未知,请人工核对,禁止自动重放: %v", reason)
|
||||
// quarantineErr 表示写入人工核对状态时的数据库错误。
|
||||
quarantineErr := c.repository.FinishRun(ctx, runKey, "needs_review", success, failed, quarantineMessage, 0)
|
||||
if quarantineErr != nil {
|
||||
return errors.Join(
|
||||
errAutomationNeedsReview,
|
||||
fmt.Errorf("账号任务本地持久化失败: %w", reason),
|
||||
fmt.Errorf("保存账号任务人工核对状态失败: %w", quarantineErr),
|
||||
)
|
||||
}
|
||||
return errors.Join(errAutomationNeedsReview, fmt.Errorf("账号任务本地持久化失败: %w", reason))
|
||||
}
|
||||
|
||||
// runAutoRate 执行自动评价任务,并在明确的单值 Cookie 查询边界内调用平台 API。
|
||||
func (c *accountTaskCoordinator) runAutoRate(ctx context.Context, settings db.AccountTaskSettings) (AccountTaskSummary, error) {
|
||||
// summary 保存summary,供当前处理流程使用
|
||||
@@ -243,7 +283,12 @@ func (c *accountTaskCoordinator) runAutoRate(ctx context.Context, settings db.Ac
|
||||
if err != nil {
|
||||
return summary, err
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, pending.UpdatedCookies)
|
||||
// updatedCookies 保存扫描接口返回的最新 Cookie;cookieErr 表示同步该 Cookie 时的持久化错误。
|
||||
updatedCookies, cookieErr := c.persistTaskCookies(ctx, settings.CookieID, current, pending.UpdatedCookies)
|
||||
if cookieErr != nil {
|
||||
return summary, cookieErr
|
||||
}
|
||||
current = updatedCookies
|
||||
orders = append(orders, pending.Orders...)
|
||||
if len(pending.Orders) < 50 {
|
||||
break
|
||||
@@ -272,18 +317,35 @@ func (c *accountTaskCoordinator) runAutoRate(ctx context.Context, settings db.Ac
|
||||
if result != nil && result.Message != "" {
|
||||
message = result.Message
|
||||
}
|
||||
_ = c.repository.FinishRun(ctx, runKey, "failed", 0, 1, message, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
// finishErr 保存失败结果的落库错误;失败时隔离运行记录,避免错误状态不明导致重放。
|
||||
finishErr := c.finishAccountTaskRun(ctx, runKey, "failed", 0, 1, message, time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
if finishErr != nil {
|
||||
return summary, errors.Join(rateErr, finishErr)
|
||||
}
|
||||
summary.Failed++
|
||||
if mtop.IsSessionExpiredErr(rateErr) {
|
||||
return summary, rateErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
_ = c.repository.FinishRun(ctx, runKey, "success", 1, 0, "", 0)
|
||||
// updatedCookies 保存评价接口返回的最新 Cookie;cookieErr 表示动作成功后同步 Cookie 的落库错误。
|
||||
updatedCookies, cookieErr := c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
if cookieErr != nil {
|
||||
return summary, c.quarantineAccountTaskRun(ctx, runKey, summary.Success+1, summary.Failed, cookieErr)
|
||||
}
|
||||
current = updatedCookies
|
||||
// finishErr 保存评价成功结果的落库错误;失败时会把运行记录隔离为人工核对。
|
||||
finishErr := c.finishAccountTaskRun(ctx, runKey, "success", 1, 0, "", 0)
|
||||
if finishErr != nil {
|
||||
return summary, finishErr
|
||||
}
|
||||
summary.Success++
|
||||
}
|
||||
_ = c.repository.MarkRateScan(ctx, settings.CookieID, time.Now().UTC().Unix())
|
||||
// markErr 表示自动评价扫描时间写入失败;不能静默忽略,否则调度状态会永久滞后。
|
||||
markErr := c.repository.MarkRateScan(ctx, settings.CookieID, time.Now().UTC().Unix())
|
||||
if markErr != nil {
|
||||
return summary, fmt.Errorf("保存自动评价扫描时间: %w", markErr)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
@@ -319,17 +381,19 @@ func (c *accountTaskCoordinator) runAutoPolish(ctx context.Context, settings db.
|
||||
// cookies、err 保存cookies、err,供当前处理流程使用
|
||||
cookies, err := c.repository.GetValue(ctx, settings.CookieID)
|
||||
if err != nil {
|
||||
_ = c.repository.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
return summary, err
|
||||
return summary, errors.Join(err, c.finishAccountTaskRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix()))
|
||||
}
|
||||
// items、err 保存items、err,供当前处理流程使用
|
||||
items, err := c.client().FetchAllItems(ctx, cookies, polishItemPageSize, polishItemMaxPages)
|
||||
if err != nil {
|
||||
_ = c.repository.FinishRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix())
|
||||
return summary, err
|
||||
return summary, errors.Join(err, c.finishAccountTaskRun(ctx, runKey, "failed", 0, 1, err.Error(), time.Now().UTC().Add(10*time.Minute).Unix()))
|
||||
}
|
||||
// current 保存current,供当前处理流程使用
|
||||
current := c.persistTaskCookies(ctx, settings.CookieID, cookies, items.UpdatedCookies)
|
||||
// current 保存擦亮接口返回前可继续使用的最新 Cookie。
|
||||
current, cookieErr := c.persistTaskCookies(ctx, settings.CookieID, cookies, items.UpdatedCookies)
|
||||
if cookieErr != nil {
|
||||
return summary, errors.Join(cookieErr, c.quarantineAccountTaskRun(ctx, runKey, 0, 0, cookieErr))
|
||||
}
|
||||
summary.Found = len(items.Items)
|
||||
// lastError 保存last错误,供当前处理流程使用
|
||||
var lastError string
|
||||
@@ -344,12 +408,16 @@ func (c *accountTaskCoordinator) runAutoPolish(ctx context.Context, settings db.
|
||||
lastError = result.Message
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(polishErr) {
|
||||
_ = c.repository.FinishRun(ctx, runKey, "failed", summary.Success, summary.Failed, lastError, 0)
|
||||
return summary, polishErr
|
||||
return summary, errors.Join(polishErr, c.finishAccountTaskRun(ctx, runKey, "failed", summary.Success, summary.Failed, lastError, 0))
|
||||
}
|
||||
continue
|
||||
}
|
||||
current = c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
// updatedCookies 保存擦亮接口返回的最新 Cookie;cookieErr 表示外部动作成功后同步 Cookie 的落库错误。
|
||||
updatedCookies, cookieErr := c.persistTaskCookies(ctx, settings.CookieID, current, result.UpdatedCookies)
|
||||
if cookieErr != nil {
|
||||
return summary, c.quarantineAccountTaskRun(ctx, runKey, summary.Success+1, summary.Failed, cookieErr)
|
||||
}
|
||||
current = updatedCookies
|
||||
summary.Success++
|
||||
}
|
||||
// status、retryAt 保存status、retryAt,供当前处理流程使用
|
||||
@@ -357,9 +425,19 @@ func (c *accountTaskCoordinator) runAutoPolish(ctx context.Context, settings db.
|
||||
if summary.Failed > 0 {
|
||||
status, retryAt = "failed", time.Now().UTC().Add(10*time.Minute).Unix()
|
||||
} else {
|
||||
_ = c.repository.MarkPolished(ctx, settings.CookieID, date, time.Now().UTC().Unix())
|
||||
// markErr 表示所有商品已擦亮但日期索引写入失败;返回错误以便运维补偿而不伪装成成功。
|
||||
markErr := c.repository.MarkPolished(ctx, settings.CookieID, date, time.Now().UTC().Unix())
|
||||
if markErr != nil {
|
||||
// persistenceErr 为日期索引失败补充业务上下文,便于人工核对具体失败边界。
|
||||
persistenceErr := fmt.Errorf("保存商品擦亮日期: %w", markErr)
|
||||
return summary, errors.Join(persistenceErr, c.quarantineAccountTaskRun(ctx, runKey, summary.Success, summary.Failed, persistenceErr))
|
||||
}
|
||||
}
|
||||
// finishErr 保存擦亮任务汇总结果的落库错误;失败时将运行记录隔离,避免下一次重放已完成商品。
|
||||
finishErr := c.finishAccountTaskRun(ctx, runKey, status, summary.Success, summary.Failed, lastError, retryAt)
|
||||
if finishErr != nil {
|
||||
return summary, finishErr
|
||||
}
|
||||
_ = c.repository.FinishRun(ctx, runKey, status, summary.Success, summary.Failed, lastError, retryAt)
|
||||
if summary.Failed > 0 {
|
||||
return summary, fmt.Errorf("%d 个商品擦亮失败: %s", summary.Failed, lastError)
|
||||
}
|
||||
@@ -367,15 +445,15 @@ func (c *accountTaskCoordinator) runAutoPolish(ctx context.Context, settings db.
|
||||
}
|
||||
|
||||
// persistTaskCookies 负责persist任务Cookies相关处理。
|
||||
func (c *accountTaskCoordinator) persistTaskCookies(ctx context.Context, accountID, oldValue, newValue string) string {
|
||||
func (c *accountTaskCoordinator) persistTaskCookies(ctx context.Context, accountID, oldValue, newValue string) (string, error) {
|
||||
newValue = strings.TrimSpace(newValue)
|
||||
if newValue == "" || newValue == oldValue {
|
||||
return oldValue
|
||||
return oldValue, nil
|
||||
}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := c.repository.UpdateValueExisting(ctx, accountID, newValue); err != nil {
|
||||
c.logger.Warn("保存账号任务响应 Cookie 失败", "account", accountID, "err", err)
|
||||
return oldValue
|
||||
return oldValue, fmt.Errorf("保存账号任务响应 Cookie: %w", err)
|
||||
}
|
||||
if c.senders != nil {
|
||||
if // sender、ok 保存sender、ok,供当前处理流程使用
|
||||
@@ -383,7 +461,7 @@ func (c *accountTaskCoordinator) persistTaskCookies(ctx context.Context, account
|
||||
sender.UpdateCookie(newValue)
|
||||
}
|
||||
}
|
||||
return newValue
|
||||
return newValue, nil
|
||||
}
|
||||
|
||||
// beijingNow 负责beijingNow相关处理。
|
||||
|
||||
@@ -91,6 +91,132 @@ func TestAccountTaskRateIsOrderIdempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountTaskRateFinishFailureQuarantinesExternalSuccess 验证评价动作已成功但运行结果写入失败时会隔离记录,避免下一轮重复评价。
|
||||
func TestAccountTaskRateFinishFailureQuarantinesExternalSuccess(t *testing.T) {
|
||||
// store 是当前测试使用的 SQLite 自动化存储。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是测试数据库操作共用的上下文。
|
||||
ctx := context.Background()
|
||||
// triggerErr 表示故意阻止 success 状态写入的 SQLite 触发器创建错误。
|
||||
if _, triggerErr := store.DB.ExecContext(ctx, `CREATE TRIGGER reject_account_task_success
|
||||
BEFORE UPDATE OF status ON account_task_runs
|
||||
WHEN NEW.status='success'
|
||||
BEGIN SELECT RAISE(ABORT, 'forced account task finish failure'); END`); triggerErr != nil {
|
||||
t.Fatal(triggerErr)
|
||||
}
|
||||
// client 记录远端评价调用次数,验证本地状态异常不会触发同一轮的重复外部动作。
|
||||
client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-finish-failure"}}}
|
||||
// center 是待验证账号任务结果隔离逻辑的自动化中心。
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
// settingsErr 表示写入自动评价设置时的数据库错误。
|
||||
if settingsErr := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "03:00"}); settingsErr != nil {
|
||||
t.Fatal(settingsErr)
|
||||
}
|
||||
// runErr 保存外部动作成功但本地运行结果收口失败后的人工核对错误。
|
||||
_, runErr := center.RunAccountTask(ctx, "cid", TaskAutoRate)
|
||||
if !errors.Is(runErr, errAutomationNeedsReview) || !strings.Contains(runErr.Error(), "保存账号任务运行结果失败") {
|
||||
t.Fatalf("运行结果写入失败应返回人工核对错误,err=%v", runErr)
|
||||
}
|
||||
if client.rateCalls != 1 {
|
||||
t.Fatalf("外部评价动作应只执行一次,calls=%d", client.rateCalls)
|
||||
}
|
||||
// status、successCount、message 保存隔离后的任务状态、已完成动作数和人工核对原因。
|
||||
var status, message string
|
||||
// successCount 保存已确认完成的评价动作数量。
|
||||
var successCount int
|
||||
// queryErr 表示读取隔离后任务状态时的数据库错误。
|
||||
queryErr := store.DB.QueryRowContext(ctx, `SELECT status,success_count,error_message FROM account_task_runs WHERE run_key=?`,
|
||||
"rate:cid:order-finish-failure").Scan(&status, &successCount, &message)
|
||||
if queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if status != "needs_review" || successCount != 1 || !strings.Contains(message, "禁止自动重放") {
|
||||
t.Fatalf("任务未正确隔离: status=%q success=%d message=%q", status, successCount, message)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountTaskRateFinishAndQuarantineFailureJoinsErrors 验证运行结果和人工核对状态均无法落库时不会吞掉任一错误。
|
||||
func TestAccountTaskRateFinishAndQuarantineFailureJoinsErrors(t *testing.T) {
|
||||
// store 是当前测试使用的 SQLite 自动化存储。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是测试数据库操作共用的上下文。
|
||||
ctx := context.Background()
|
||||
// triggerErr 表示故意阻止 success 与 needs_review 状态写入的 SQLite 触发器创建错误。
|
||||
if _, triggerErr := store.DB.ExecContext(ctx, `CREATE TRIGGER reject_account_task_result_states
|
||||
BEFORE UPDATE OF status ON account_task_runs
|
||||
WHEN NEW.status IN ('success','needs_review')
|
||||
BEGIN SELECT RAISE(ABORT, 'forced account task result failure'); END`); triggerErr != nil {
|
||||
t.Fatal(triggerErr)
|
||||
}
|
||||
// client 记录已经成功执行的远端评价动作。
|
||||
client := &fakeAccountTaskClient{pending: []mtop.PendingRateOrder{{TradeID: "order-double-failure"}}}
|
||||
// center 是待验证双重落库错误传播逻辑的自动化中心。
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
// settingsErr 表示写入自动评价设置时的数据库错误。
|
||||
if settingsErr := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoRateEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "03:00"}); settingsErr != nil {
|
||||
t.Fatal(settingsErr)
|
||||
}
|
||||
// runErr 保存结果写入和隔离写入均失败后的组合错误。
|
||||
_, runErr := center.RunAccountTask(ctx, "cid", TaskAutoRate)
|
||||
if !errors.Is(runErr, errAutomationNeedsReview) || !strings.Contains(runErr.Error(), "保存账号任务运行结果失败") ||
|
||||
!strings.Contains(runErr.Error(), "保存账号任务人工核对状态失败") {
|
||||
t.Fatalf("双重落库失败应返回完整错误链,err=%v", runErr)
|
||||
}
|
||||
if client.rateCalls != 1 {
|
||||
t.Fatalf("外部评价动作应只执行一次,calls=%d", client.rateCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountTaskPolishMarkFailureQuarantinesExternalSuccess 验证商品擦亮成功但日期索引写入失败时会隔离运行记录。
|
||||
func TestAccountTaskPolishMarkFailureQuarantinesExternalSuccess(t *testing.T) {
|
||||
// store 是当前测试使用的 SQLite 自动化存储。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是测试数据库操作共用的上下文。
|
||||
ctx := context.Background()
|
||||
// settingsErr 表示写入擦亮设置时的数据库错误。
|
||||
if settingsErr := store.AccountTasks.Upsert(ctx, db.AccountTaskSettings{CookieID: "cid", AutoPolishEnabled: true,
|
||||
RateContent: "交易愉快", PolishTime: "00:00"}); settingsErr != nil {
|
||||
t.Fatal(settingsErr)
|
||||
}
|
||||
// triggerErr 表示故意阻止擦亮日期索引写入的 SQLite 触发器创建错误。
|
||||
if _, triggerErr := store.DB.ExecContext(ctx, `CREATE TRIGGER reject_account_task_polish_mark
|
||||
BEFORE UPDATE OF last_polish_date ON account_task_settings
|
||||
WHEN NEW.last_polish_date <> ''
|
||||
BEGIN SELECT RAISE(ABORT, 'forced account task polish mark failure'); END`); triggerErr != nil {
|
||||
t.Fatal(triggerErr)
|
||||
}
|
||||
// client 记录远端擦亮调用次数,验证本地状态异常不会导致同一轮重复执行。
|
||||
client := &fakeAccountTaskClient{items: []mtop.ItemListItem{{ID: "item-mark-failure"}}}
|
||||
// center 是待验证擦亮结果隔离逻辑的自动化中心。
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
center.SetAccountTaskClient(client)
|
||||
// runErr 保存外部擦亮成功但日期索引收口失败后的人工核对错误。
|
||||
_, runErr := center.RunAccountTask(ctx, "cid", TaskAutoPolish)
|
||||
if !errors.Is(runErr, errAutomationNeedsReview) || !strings.Contains(runErr.Error(), "保存商品擦亮日期") {
|
||||
t.Fatalf("擦亮日期写入失败应返回人工核对错误,err=%v", runErr)
|
||||
}
|
||||
if client.polishCalls != 1 {
|
||||
t.Fatalf("外部擦亮动作应只执行一次,calls=%d", client.polishCalls)
|
||||
}
|
||||
// status 保存被隔离的擦亮运行状态。
|
||||
var status string
|
||||
// queryErr 表示读取隔离后擦亮运行状态时的数据库错误。
|
||||
queryErr := store.DB.QueryRowContext(ctx, `SELECT status FROM account_task_runs WHERE run_key LIKE 'polish:cid:%'`).Scan(&status)
|
||||
if queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if status != "needs_review" {
|
||||
t.Fatalf("擦亮日期写入失败后应隔离任务,status=%q", status)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountTaskSessionExpiredRecoversOnceAndBlocksFurtherAPIRequests 负责Test账号任务会话ExpiredRecoversOnceAndBlocksFurtherAPI请求列表相关处理。
|
||||
func TestAccountTaskSessionExpiredRecoversOnceAndBlocksFurtherAPIRequests(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
|
||||
@@ -660,7 +660,6 @@ func (a *Account) StopContext(ctx context.Context) error {
|
||||
if !shouldStop {
|
||||
return nil
|
||||
}
|
||||
defer a.lifecycle.finishStop()
|
||||
a.setRuntimeState(RuntimeStopped, "账号服务已停止")
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
@@ -675,6 +674,13 @@ func (a *Account) StopContext(ctx context.Context) error {
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
if a.recorder != nil && !a.recorder.waitContext(ctx) {
|
||||
a.logger.Warn("等待账号 WS 记录 worker 退出超时")
|
||||
if ctx == nil || ctx.Err() == nil {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1140,11 +1146,21 @@ func (a *Account) watchPendingAPIRenew(parent context.Context, result *renew.Res
|
||||
if result == nil || !result.HasPending() {
|
||||
return
|
||||
}
|
||||
// taskCtx 是迟到续期任务继承的账号生命周期上下文;Stop 会先取消它,再等待任务收束。
|
||||
taskCtx, accepted := a.beginTask()
|
||||
if !accepted {
|
||||
return
|
||||
}
|
||||
if parent != nil {
|
||||
// Run 传入的 parent 就是账号运行上下文;直接沿用它可同时响应调用方取消和 Stop 的取消。
|
||||
taskCtx = parent
|
||||
}
|
||||
a.pendingRenewWG.Add(1)
|
||||
go func() {
|
||||
defer a.lifecycle.finishTask()
|
||||
defer a.pendingRenewWG.Done()
|
||||
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
|
||||
ctx, cancel := context.WithTimeout(parent, 35*time.Second)
|
||||
ctx, cancel := context.WithTimeout(taskCtx, 35*time.Second)
|
||||
defer cancel()
|
||||
// late、waitErr 保存late、waitErr,供当前处理流程使用
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
|
||||
@@ -502,11 +502,18 @@ func TestTryAPIRenewPendingWatcherStopsWithAccountContext(t *testing.T) {
|
||||
acc.renewer = xrenew.Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond}
|
||||
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
acc.lifecycle.start(ctx, cancel)
|
||||
if acc.tryAPIRenew(ctx) {
|
||||
t.Fatal("Promise 超时不得伪装成同步续期成功")
|
||||
}
|
||||
cancel()
|
||||
acc.pendingRenewWG.Wait()
|
||||
// stopCtx 验证账号停止会等待迟到续期 worker,而不是只取消其父上下文。
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer stopCancel()
|
||||
// stopErr 表示停止账号并等待迟到续期 worker 的结果。
|
||||
if stopErr := acc.StopContext(stopCtx); stopErr != nil {
|
||||
t.Fatalf("StopContext 未等待迟到续期 worker: %v", stopErr)
|
||||
}
|
||||
// detail、err 保存detail、err,供当前处理流程使用
|
||||
detail, err := store.Cookies.GetDetails(context.Background(), "cid")
|
||||
if err != nil {
|
||||
|
||||
@@ -23,6 +23,8 @@ type accountLifecycle struct {
|
||||
accepting bool
|
||||
// taskWG 等待所有已经通过 beginTask 的业务任务退出。
|
||||
taskWG sync.WaitGroup
|
||||
// activeTasks 记录尚未完成的任务数量,用于在超时 Stop 后由最后一个任务关闭 stopDone。
|
||||
activeTasks int
|
||||
// stopDone 在第一次 Stop 的清理完成后关闭,保证并发 Stop 调用也等待完整收束。
|
||||
stopDone chan struct{}
|
||||
}
|
||||
@@ -33,6 +35,8 @@ func (l *accountLifecycle) start(ctx context.Context, cancel context.CancelFunc)
|
||||
l.stopFn = cancel
|
||||
l.runtimeCtx = ctx
|
||||
l.accepting = true
|
||||
l.stopped = false
|
||||
l.stopDone = nil
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -58,22 +62,16 @@ func (l *accountLifecycle) stopContext(ctx context.Context) (context.CancelFunc,
|
||||
l.stopped = true
|
||||
l.accepting = false
|
||||
l.stopDone = make(chan struct{})
|
||||
if l.activeTasks == 0 {
|
||||
close(l.stopDone)
|
||||
l.stopDone = nil
|
||||
}
|
||||
// cancel 是当前账号 Run 上下文的取消函数。
|
||||
cancel := l.stopFn
|
||||
l.mu.Unlock()
|
||||
return cancel, true, nil
|
||||
}
|
||||
|
||||
// finishStop 标记第一次 Stop 的清理已完成,并唤醒并发 Stop 调用者。
|
||||
func (l *accountLifecycle) finishStop() {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.stopDone != nil {
|
||||
close(l.stopDone)
|
||||
l.stopDone = nil
|
||||
}
|
||||
}
|
||||
|
||||
// beginTask 在生命周期锁内登记业务任务,避免 Stop 与 WaitGroup.Add 竞争。
|
||||
func (l *accountLifecycle) beginTask() (context.Context, bool) {
|
||||
l.mu.Lock()
|
||||
@@ -90,12 +88,22 @@ func (l *accountLifecycle) beginTask() (context.Context, bool) {
|
||||
return nil, false
|
||||
}
|
||||
l.taskWG.Add(1)
|
||||
l.activeTasks++
|
||||
return ctx, true
|
||||
}
|
||||
|
||||
// finishTask 标记一个已登记的业务任务退出。
|
||||
func (l *accountLifecycle) finishTask() {
|
||||
l.taskWG.Done()
|
||||
l.mu.Lock()
|
||||
if l.activeTasks > 0 {
|
||||
l.activeTasks--
|
||||
}
|
||||
if l.stopped && l.activeTasks == 0 && l.stopDone != nil {
|
||||
close(l.stopDone)
|
||||
l.stopDone = nil
|
||||
}
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
// waitContext 等待已登记业务任务结束,并在 ctx 到期时及时返回。
|
||||
|
||||
@@ -83,5 +83,24 @@ func TestAccountStopContextBoundsTaskWait(t *testing.T) {
|
||||
if elapsed := time.Since(started); elapsed > time.Second {
|
||||
t.Fatalf("StopContext waited too long: %s", elapsed)
|
||||
}
|
||||
// retryDone 表示第一次超时后的第二次 Stop 是否仍等待原任务收束。
|
||||
retryDone := make(chan error, 1)
|
||||
go func() {
|
||||
retryDone <- account.StopContext(context.Background())
|
||||
}()
|
||||
select {
|
||||
case <-retryDone:
|
||||
t.Fatal("第一次 Stop 超时后,重试不应在任务完成前返回")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
account.lifecycle.finishTask()
|
||||
select {
|
||||
// retryErr 表示第一次超时后再次停止账号的等待结果。
|
||||
case retryErr := <-retryDone:
|
||||
if retryErr != nil {
|
||||
t.Fatalf("重试 StopContext error=%v", retryErr)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("第一次 Stop 超时后,重试未在任务完成后返回")
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
@@ -23,6 +24,10 @@ type wsRecorder struct {
|
||||
once sync.Once
|
||||
// wg 等待 recorder worker 退出。
|
||||
wg sync.WaitGroup
|
||||
// done 在 recorder worker 退出时关闭,供 Context-aware 等待直接选择而不创建旁路 goroutine。
|
||||
done chan struct{}
|
||||
// started 表示 recorder worker 是否实际启动;未启动的 recorder 无需等待。
|
||||
started atomic.Bool
|
||||
// queue 是有界的报文内存队列,满时丢弃诊断记录而不阻塞 WS。
|
||||
queue chan db.WSMessage
|
||||
}
|
||||
@@ -40,6 +45,7 @@ func newWSRecorder(store *db.Store, cookieID string, logger *slog.Logger) *wsRec
|
||||
cookieID: cookieID,
|
||||
logger: logger,
|
||||
queue: make(chan db.WSMessage, 256),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,9 +79,11 @@ func (r *wsRecorder) start(ctx context.Context) {
|
||||
return
|
||||
}
|
||||
r.once.Do(func() {
|
||||
r.started.Store(true)
|
||||
r.wg.Add(1)
|
||||
go func() {
|
||||
defer r.wg.Done()
|
||||
defer close(r.done)
|
||||
// cleanupCtx 是清理历史报文时的有限时长上下文。
|
||||
cleanupCtx, cleanupCancel := context.WithTimeout(ctx, WSRecordWriteTimeout)
|
||||
// deleted 是本次清理删除的历史报文数量。
|
||||
@@ -131,3 +139,27 @@ func (r *wsRecorder) wait() {
|
||||
r.wg.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// waitContext 在 ctx 约束内等待 recorder worker 退出;数据库写入异常阻塞时及时把停止超时交给调用方。
|
||||
func (r *wsRecorder) waitContext(ctx context.Context) bool {
|
||||
if r == nil {
|
||||
return true
|
||||
}
|
||||
if !r.started.Load() {
|
||||
return true
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
// done 表示 recorder worker 已经退出,供当前等待调用选择上下文超时或正常完成。
|
||||
done := r.done
|
||||
if done == nil {
|
||||
return true
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ type applicationServices struct {
|
||||
itemPublish *itemPublishService
|
||||
// itemSinglePublish 是仅负责单商品发布用例的纯应用服务。
|
||||
itemSinglePublish *itemapp.Service
|
||||
// itemBatchRunner 是商品批量发布 worker 的应用层编排器。
|
||||
itemBatchRunner *itemapp.BatchRunner
|
||||
// accountLogin 是账号登录应用服务。
|
||||
accountLogin *accountLoginService
|
||||
// accountProfile 是账号资料刷新应用服务。
|
||||
@@ -37,10 +39,16 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
if profileErr != nil {
|
||||
panic(profileErr)
|
||||
}
|
||||
// itemBatchRunner 是批量发布 worker 的构造结果,失败表示必需端口装配错误。
|
||||
itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server)
|
||||
if batchRunnerErr != nil {
|
||||
panic(batchRunnerErr)
|
||||
}
|
||||
return &applicationServices{
|
||||
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
|
||||
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
|
||||
itemSinglePublish: newItemPublishApplication(server),
|
||||
itemBatchRunner: itemBatchRunner,
|
||||
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store)},
|
||||
accountProfile: accountProfile,
|
||||
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
|
||||
@@ -48,6 +56,11 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
}
|
||||
}
|
||||
|
||||
// itemBatchRunnerApplication 返回当前 Server 绑定的批量发布 worker 编排器。
|
||||
func (s *Server) itemBatchRunnerApplication() *itemapp.BatchRunner {
|
||||
return s.applicationServiceSet().itemBatchRunner
|
||||
}
|
||||
|
||||
// accountProfileApplication 返回当前 Server 绑定的账号资料应用服务。
|
||||
func (s *Server) accountProfileApplication() *accountapp.ProfileService {
|
||||
return s.applicationServiceSet().accountProfile
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
itemapp "xianyu-go/internal/application/items"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
@@ -549,7 +550,10 @@ func (s *Server) startPublishBatchWorker(parent context.Context, userID int64, b
|
||||
s.registerPublishBatchCancel(batchID, workerToken, cancel)
|
||||
defer cancel()
|
||||
defer s.unregisterPublishBatchCancel(batchID, workerToken)
|
||||
s.runItemPublishBatch(jobCtx, userID, batchID, workerToken, false)
|
||||
// runner 负责批量发布的租约、逐行失败记录和最终状态收口。
|
||||
if runErr := s.itemBatchRunnerApplication().Run(jobCtx, userID, batchID, workerToken, false); runErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("批量发布 worker 结束", "batch", batchID, "err", runErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -656,7 +660,7 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R
|
||||
// cw 保存cw,供当前处理流程使用
|
||||
cw := csv.NewWriter(&buf)
|
||||
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "默认类目ID", "默认类目名称", "商品ID", "商品URL", "错误原因"})
|
||||
// row 表示当前遍历过程中的row
|
||||
// row 表示当前导出的批量明细行。
|
||||
for _, row := range rows {
|
||||
// category 保存分类,供当前处理流程使用
|
||||
var category mtop.PublishCategory
|
||||
@@ -692,105 +696,6 @@ func safeCSVCell(value string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// runItemPublishBatch 负责运行商品发布批次相关处理。
|
||||
func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID, workerToken string, failedOnly bool) {
|
||||
// rows、err 保存rows、err,供当前处理流程使用
|
||||
rows, err := s.itemPublishRepositoryForServer().PendingRows(ctx, batchID, failedOnly)
|
||||
if err != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("读取批量发布行失败", "batch", batchID, "err", err)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
}
|
||||
return
|
||||
}
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := s.mtopClient()
|
||||
// idx、row 表示当前遍历过程中的idx、row
|
||||
for idx, row := range rows {
|
||||
if ctx.Err() != nil {
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
// wctx、cancel 保存wctx、cancel,供当前处理流程使用
|
||||
wctx, cancel := publishStatusContext(ctx)
|
||||
// renewed、renewErr 保存renewed、renewErr,供当前处理流程使用
|
||||
renewed, renewErr := s.itemPublishRepositoryForServer().RenewBatchLease(wctx, batchID, workerToken, time.Now().UTC().Add(publishBatchLease).Unix())
|
||||
cancel()
|
||||
if renewErr != nil || !renewed {
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
wctx, cancel = publishStatusContext(ctx)
|
||||
// batch、err 保存batch、err,供当前处理流程使用
|
||||
batch, err := s.itemPublishRepositoryForServer().GetBatch(wctx, userID, batchID)
|
||||
cancel()
|
||||
if err != nil || batch.Status != "running" || batch.WorkerToken != workerToken {
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
wctx, cancel = publishStatusContext(ctx)
|
||||
// claimed、claimErr 保存claimed、claimErr,供当前处理流程使用
|
||||
claimed, claimErr := s.itemPublishRepositoryForServer().ClaimRow(wctx, row.ID, workerToken)
|
||||
cancel()
|
||||
if claimErr != nil {
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
if !claimed {
|
||||
continue
|
||||
}
|
||||
if // rowErr 保存rowErr,供当前处理流程使用
|
||||
rowErr := s.publishBatchRow(ctx, userID, client, row, workerToken); rowErr != nil {
|
||||
// sessionExpired 保存会话Expired,供当前处理流程使用
|
||||
sessionExpired := mtop.IsSessionExpiredErr(rowErr)
|
||||
// statusCtx、statusCancel 保存状态Ctx、status取消,供当前处理流程使用
|
||||
statusCtx, statusCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
// status 保存状态,供当前处理流程使用
|
||||
status, _ := s.itemPublishRepositoryForServer().BatchStatus(statusCtx, batchID)
|
||||
statusCancel()
|
||||
// message、failureKind 保存message、failure类型,供当前处理流程使用
|
||||
message, failureKind := publishBatchFailure(rowErr, status)
|
||||
// wctx、cancel 保存wctx、cancel,供当前处理流程使用
|
||||
wctx, cancel := publishStatusContext(ctx)
|
||||
// marked、markErr 保存marked、markErr,供当前处理流程使用
|
||||
marked, markErr := s.itemPublishRepositoryForServer().MarkClaimedRowFailed(wctx, row.ID, workerToken, message, failureKind)
|
||||
cancel()
|
||||
if markErr != nil || !marked {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("保存批量发布失败状态失败,等待租约恢复", "batch", batchID, "row", row.ID, "err", markErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if sessionExpired {
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
return
|
||||
}
|
||||
}
|
||||
wctx, cancel = publishStatusContext(ctx)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.itemPublishRepositoryForServer().RecountBatch(wctx, batchID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("重算批量发布进度失败", "batch", batchID, "err", err)
|
||||
}
|
||||
cancel()
|
||||
if idx < len(rows)-1 {
|
||||
// delay 保存延迟,供当前处理流程使用
|
||||
delay := time.Duration(10+idx%21) * time.Second
|
||||
// timer 保存定时器,供当前处理流程使用
|
||||
timer := time.NewTimer(delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
s.finishInterruptedPublishBatch(ctx, userID, batchID, workerToken)
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
s.finishPublishBatch(ctx, userID, batchID, workerToken)
|
||||
}
|
||||
|
||||
// publishBatchFailure 负责发布批次Failure相关处理。
|
||||
func publishBatchFailure(err error, batchStatus string) (string, string) {
|
||||
// message 保存消息,供当前处理流程使用
|
||||
@@ -862,61 +767,6 @@ func publishStatusContext(parent context.Context) (context.Context, context.Canc
|
||||
return context.WithTimeout(context.Background(), 5*time.Second)
|
||||
}
|
||||
|
||||
// finishInterruptedPublishBatch 负责finishInterrupted发布批次相关处理。
|
||||
func (s *Server) finishInterruptedPublishBatch(ctx context.Context, userID int64, batchID, workerToken string) {
|
||||
// wctx、cancel 保存wctx、cancel,供当前处理流程使用
|
||||
wctx, cancel := publishStatusContext(ctx)
|
||||
defer cancel()
|
||||
// batch、err 保存batch、err,供当前处理流程使用
|
||||
batch, err := s.itemPublishRepositoryForServer().GetBatch(wctx, userID, batchID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if batch.Status == "canceled" || batch.Status == "canceling" {
|
||||
if batch.Status == "canceling" {
|
||||
if batch.WorkerToken != workerToken {
|
||||
return
|
||||
}
|
||||
_, _ = s.itemPublishRepositoryForServer().FinalizeCanceled(wctx, batchID, workerToken)
|
||||
}
|
||||
// 取消产生的 interrupted 失败行允许用户稍后重试,图片由统一的过期清理保留 7 天。
|
||||
return
|
||||
}
|
||||
// finalizeErr 保存finalizeErr,供当前处理流程使用
|
||||
_, _, finalizeErr := s.itemPublishRepositoryForServer().FinalizeInterrupted(wctx, batchID, workerToken, "任务超时或已中断")
|
||||
if finalizeErr != nil && s.Logger != nil {
|
||||
s.Logger.Warn("结束中断的批量发布任务失败,等待租约恢复", "batch", batchID, "err", finalizeErr)
|
||||
}
|
||||
}
|
||||
|
||||
// finishPublishBatch 负责finish发布批次相关处理。
|
||||
func (s *Server) finishPublishBatch(ctx context.Context, userID int64, batchID, workerToken string) {
|
||||
// wctx、cancel 保存wctx、cancel,供当前处理流程使用
|
||||
wctx, cancel := publishStatusContext(ctx)
|
||||
defer cancel()
|
||||
// batch、err 保存batch、err,供当前处理流程使用
|
||||
batch, err := s.itemPublishRepositoryForServer().GetBatch(wctx, userID, batchID)
|
||||
if err != nil || batch.Status == "canceled" || batch.WorkerToken != workerToken {
|
||||
return
|
||||
}
|
||||
if batch.Status == "canceling" {
|
||||
_, _ = s.itemPublishRepositoryForServer().FinalizeCanceled(wctx, batchID, workerToken)
|
||||
// 取消任务仍可“重试失败项”,不能在此删除重试所需的本地图片。
|
||||
return
|
||||
}
|
||||
// finalStatus、finished、finishErr 保存finalStatus、finished、finishErr,供当前处理流程使用
|
||||
finalStatus, finished, finishErr := s.itemPublishRepositoryForServer().FinalizeBatch(wctx, batchID, workerToken)
|
||||
if finishErr != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("结束批量发布任务失败,等待租约恢复", "batch", batchID, "err", finishErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if finished && finalStatus == "completed" && strings.TrimSpace(batch.UploadDir) != "" {
|
||||
s.removePublishUploadDir(wctx, batch)
|
||||
}
|
||||
}
|
||||
|
||||
// finalPublishBatchStatus 负责final发布批次状态相关处理。
|
||||
func finalPublishBatchStatus(batch *db.ItemPublishBatch) string {
|
||||
if batch == nil {
|
||||
@@ -1496,7 +1346,7 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
|
||||
pending := 0
|
||||
// running 保存running,供当前处理流程使用
|
||||
running := 0
|
||||
// row 表示当前遍历过程中的row
|
||||
// row 表示当前待转换的批量明细行。
|
||||
for _, row := range rows {
|
||||
if row.Status == "pending" {
|
||||
pending++
|
||||
@@ -1524,7 +1374,7 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
|
||||
}
|
||||
// retryable 保存retryable,供当前处理流程使用
|
||||
retryable := 0
|
||||
// row 表示当前遍历过程中的row
|
||||
// row 表示当前用于统计可重试数量的批量明细行。
|
||||
for _, row := range rows {
|
||||
if row.Status == "failed" && row.FailureKind != "validation" && row.FailureKind != "uncertain_remote" {
|
||||
retryable++
|
||||
@@ -1641,3 +1491,126 @@ func firstNonEmpty(values ...string) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// serverBatchRepository 将数据库批次仓储转换为应用层批量发布端口。
|
||||
type serverBatchRepository struct {
|
||||
// server 保存文件清理和数据库适配所需的 Server 引用。
|
||||
server *Server
|
||||
// repository 保存批量状态的窄数据库接口。
|
||||
repository itemPublishRepository
|
||||
}
|
||||
|
||||
// PendingRows 查询数据库明细并移除数据库模型依赖。
|
||||
func (r serverBatchRepository) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]itemapp.BatchRow, error) {
|
||||
// rows、err 保存数据库批量明细及查询错误。
|
||||
rows, err := r.repository.PendingRows(ctx, batchID, failedOnly)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// result 保存应用层批量明细。
|
||||
result := make([]itemapp.BatchRow, 0, len(rows))
|
||||
// row 表示当前转换的数据库批量明细。
|
||||
for _, row := range rows {
|
||||
result = append(result, toApplicationBatchRow(row))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// RenewBatchLease 委托数据库续租并保持应用层只接收基础类型。
|
||||
func (r serverBatchRepository) RenewBatchLease(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) {
|
||||
return r.repository.RenewBatchLease(ctx, batchID, workerToken, leaseExpiresAt)
|
||||
}
|
||||
|
||||
// GetBatch 查询数据库批次并转换为应用层状态模型。
|
||||
func (r serverBatchRepository) GetBatch(ctx context.Context, userID int64, batchID string) (itemapp.BatchInfo, error) {
|
||||
// batch、err 保存数据库批次及查询错误。
|
||||
batch, err := r.repository.GetBatch(ctx, userID, batchID)
|
||||
if err != nil {
|
||||
return itemapp.BatchInfo{}, err
|
||||
}
|
||||
return itemapp.BatchInfo{ID: batch.ID, UserID: batch.UserID, Status: batch.Status, WorkerToken: batch.WorkerToken, UploadDir: batch.UploadDir}, nil
|
||||
}
|
||||
|
||||
// ClaimRow 委托数据库抢占明细租约。
|
||||
func (r serverBatchRepository) ClaimRow(ctx context.Context, rowID int64, workerToken string) (bool, error) {
|
||||
return r.repository.ClaimRow(ctx, rowID, workerToken)
|
||||
}
|
||||
|
||||
// BatchStatus 委托数据库读取批次状态用于失败分类。
|
||||
func (r serverBatchRepository) BatchStatus(ctx context.Context, batchID string) (string, error) {
|
||||
return r.repository.BatchStatus(ctx, batchID)
|
||||
}
|
||||
|
||||
// MarkClaimedRowFailed 委托数据库记录当前 worker 的失败明细。
|
||||
func (r serverBatchRepository) MarkClaimedRowFailed(ctx context.Context, rowID int64, workerToken, message, kind string) (bool, error) {
|
||||
return r.repository.MarkClaimedRowFailed(ctx, rowID, workerToken, message, kind)
|
||||
}
|
||||
|
||||
// RecountBatch 委托数据库重算批次进度。
|
||||
func (r serverBatchRepository) RecountBatch(ctx context.Context, batchID string) error {
|
||||
return r.repository.RecountBatch(ctx, batchID)
|
||||
}
|
||||
|
||||
// FinalizeBatch 委托数据库正常收口批次。
|
||||
func (r serverBatchRepository) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) {
|
||||
return r.repository.FinalizeBatch(ctx, batchID, workerToken)
|
||||
}
|
||||
|
||||
// FinalizeCanceled 委托数据库收口取消中的批次。
|
||||
func (r serverBatchRepository) FinalizeCanceled(ctx context.Context, batchID, workerToken string) (bool, error) {
|
||||
return r.repository.FinalizeCanceled(ctx, batchID, workerToken)
|
||||
}
|
||||
|
||||
// FinalizeInterrupted 委托数据库收口中断批次。
|
||||
func (r serverBatchRepository) FinalizeInterrupted(ctx context.Context, batchID, workerToken, message string) (string, bool, error) {
|
||||
return r.repository.FinalizeInterrupted(ctx, batchID, workerToken, message)
|
||||
}
|
||||
|
||||
// DeleteUpload 删除已完成批次的上传目录并清除数据库路径。
|
||||
func (r serverBatchRepository) DeleteUpload(ctx context.Context, batchID, uploadDir string) error {
|
||||
if uploadDir == "" {
|
||||
return nil
|
||||
}
|
||||
// removeErr 保存上传目录删除错误;数据库记录仍需尝试清理。
|
||||
removeErr := os.RemoveAll(uploadDir)
|
||||
// clearErr 保存数据库上传目录字段清理错误。
|
||||
clearErr := r.repository.ClearUploadDir(ctx, batchID)
|
||||
if removeErr != nil {
|
||||
return removeErr
|
||||
}
|
||||
return clearErr
|
||||
}
|
||||
|
||||
// serverBatchPublisher 将 Server 的商品发布细节适配为应用层批量发布端口。
|
||||
type serverBatchPublisher struct {
|
||||
// server 保存平台发布和本地商品结果适配所需的 Server 引用。
|
||||
server *Server
|
||||
}
|
||||
|
||||
// PublishRow 调用现有单行发布适配,应用层不再接触数据库或 MTOP 类型。
|
||||
func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) error {
|
||||
return p.server.publishBatchRow(ctx, userID, p.server.mtopClient(), fromApplicationBatchRow(row), workerToken)
|
||||
}
|
||||
|
||||
// toApplicationBatchRow 将数据库行映射为纯应用 DTO。
|
||||
func toApplicationBatchRow(row db.ItemPublishBatchRow) itemapp.BatchRow {
|
||||
return itemapp.BatchRow{ID: row.ID, BatchID: row.BatchID, CookieID: row.CookieID, Title: row.Title, Description: row.Description, Price: row.Price, OriginalPrice: row.OriginalPrice, Quantity: row.Quantity, PostageMode: row.PostageMode, Postage: row.Postage, ImagesJSON: row.ImagesJSON, CategoryJSON: row.CategoryJSON, AutomationJSON: row.AutomationJSON, RawJSON: row.RawJSON, ItemID: row.ItemID, ItemURL: row.ItemURL}
|
||||
}
|
||||
|
||||
// fromApplicationBatchRow 将应用 DTO 还原为 Server 平台适配所需的数据库行模型。
|
||||
func fromApplicationBatchRow(row itemapp.BatchRow) db.ItemPublishBatchRow {
|
||||
return db.ItemPublishBatchRow{ID: row.ID, BatchID: row.BatchID, CookieID: row.CookieID, Title: row.Title, Description: row.Description, Price: row.Price, OriginalPrice: row.OriginalPrice, Quantity: row.Quantity, PostageMode: row.PostageMode, Postage: row.Postage, ImagesJSON: row.ImagesJSON, CategoryJSON: row.CategoryJSON, AutomationJSON: row.AutomationJSON, RawJSON: row.RawJSON, ItemID: row.ItemID, ItemURL: row.ItemURL}
|
||||
}
|
||||
|
||||
// newItemBatchRunnerApplication 创建批量发布应用层 worker 编排器。
|
||||
func newItemBatchRunnerApplication(server *Server) (*itemapp.BatchRunner, error) {
|
||||
// options 配置批量 worker 的租约、间隔和平台错误语义。
|
||||
options := itemapp.BatchRunOptions{
|
||||
LeaseDuration: publishBatchLease,
|
||||
IsSessionExpired: func(err error) bool {
|
||||
return mtop.IsSessionExpiredErr(err)
|
||||
},
|
||||
ClassifyFailure: publishBatchFailure,
|
||||
}
|
||||
return itemapp.NewBatchRunner(serverBatchRepository{server: server, repository: newStoreItemPublishRepository(server.Store)}, serverBatchPublisher{server: server}, options)
|
||||
}
|
||||
Reference in new issue
Block a user