推进P1批量发布Engine生命周期与账号任务收口
This commit is contained in:
1 parent
e53177ccd1
commit
417723d2c0
12 files changed
+918
-190
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user