补齐证书任务并发保护和DNS阶段进度

增加同域名同类活动任务保护、DNS验证阶段进度回调及相关接口冲突响应,补充仓储回归测试。
This commit is contained in:
xuans committed 2026-09-30 03:56:51 +08:00
1 parent 69dc6e10dc
commit 604a1bf4f0
6 files changed
+101 -3

No files matched your search

@@ -41,6 +41,9 @@ type TaskAttempt struct {
CreatedAt time.Time `json:"created_at"`
}
// ErrTaskAlreadyRunning 表示同一域名的同类任务仍处于活动状态。
var ErrTaskAlreadyRunning = errors.New("同一域名的同类任务正在执行")
type TaskRepository interface {
CreateTask(context.Context, Task) error
GetTask(context.Context, string) (Task, error)
@@ -119,6 +122,14 @@ func (r *SQLTaskRepository) CreateTask(ctx context.Context, item Task) error {
}
return fmt.Errorf("读取任务所属域名失败:%w", err)
}
var activeTaskID string
if err := tx.QueryRowContext(ctx, r.query(`SELECT id FROM tasks
WHERE domain_id = ? AND task_type = ? AND status IN ('queued', 'running', 'retry_wait', 'cancelling')
ORDER BY created_at DESC LIMIT 1`), item.DomainID, item.TaskType).Scan(&activeTaskID); err == nil {
return fmt.Errorf("%w:%s", ErrTaskAlreadyRunning, activeTaskID)
} else if !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("检查活动任务失败:%w", err)
}
args = append(args, projectID)
result, err := tx.ExecContext(ctx, r.query(insertQuery+`VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'project', ?)`), args...)
if err != nil {
@@ -3,6 +3,7 @@ package repository
import (
"context"
"database/sql"
"errors"
"path/filepath"
"testing"
"time"
@@ -99,6 +100,28 @@ func TestSQLTaskRepositoryRejectsInvalidStatus(t *testing.T) {
}
}
func TestSQLTaskRepositoryRejectsConcurrentActiveTaskOfSameType(t *testing.T) {
repository, db := newTaskRepositoryTest(t)
defer db.Close()
ctx := context.Background()
if err := repository.CreateTask(ctx, Task{
ID: "task-active", DomainID: "domain-1", TaskType: "certificate_validate",
Status: "running", Stage: "certificate_validate", Message: "正在校验证书",
}); err != nil {
t.Fatalf("创建活动任务失败:%v", err)
}
err := repository.CreateTask(ctx, Task{
ID: "task-duplicate", DomainID: "domain-1", TaskType: "certificate_validate",
Status: "queued", Stage: "queued", Message: "等待校验证书",
})
if !errors.Is(err, ErrTaskAlreadyRunning) {
t.Fatalf("同类活动任务应被拒绝:%v", err)
}
if _, err := repository.GetTask(ctx, "task-duplicate"); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("拒绝并发任务后不应留下重复任务:%v", err)
}
}
func TestSQLTaskRepositoryCancelMarksRunningAttempt(t *testing.T) {
repository, db := newTaskRepositoryTest(t)
defer db.Close()