推进P1后台任务与通知补偿收口

This commit is contained in:
Christ committed 2026-08-16 00:04:22 +08:00
1 parent 3fdd0fe267
commit 25531c05cb
15 files changed
+985 -59

No files matched your search

+13 -9
View File
@@ -4,6 +4,7 @@ import (
accountapp "xianyu-go/internal/application/account"
chatapp "xianyu-go/internal/application/chat"
itemapp "xianyu-go/internal/application/items"
notificationsapp "xianyu-go/internal/application/notifications"
orderapp "xianyu-go/internal/application/orders"
)
@@ -25,6 +26,8 @@ type applicationServices struct {
communication *communicationService
// chat 是聊天历史查询应用服务,负责用户归属和分页编排。
chat *chatapp.Service
// uncertainNotifications 是通知不确定状态运维查询应用服务。
uncertainNotifications *notificationsapp.Service
// analytics 是订单分析应用服务。
analytics *analyticsService
}
@@ -63,15 +66,16 @@ func newApplicationServices(server *Server) *applicationServices {
}
}
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), createApplication: accountLoginCreate, qrApplication: accountQRLogin},
accountProfile: accountProfile,
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
chat: chatapp.New(newStoreChatApplicationRepository(server.Store)),
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
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), createApplication: accountLoginCreate, qrApplication: accountQRLogin},
accountProfile: accountProfile,
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
chat: chatapp.New(newStoreChatApplicationRepository(server.Store)),
uncertainNotifications: notificationsapp.New(newStoreNotificationUncertainRepository(server.Store)),
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
}
}
@@ -576,8 +576,8 @@ func (s *Server) RunPublishBatchRecovery(ctx context.Context) {
// StartPublishBatchRecovery 先登记生命周期,再启动恢复循环,避免关闭流程在
// goroutine 尚未调度时误判扫描器已经退出。
// StartPublishBatchRecovery 启动发布批次Recovery。
func (s *Server) StartPublishBatchRecovery(ctx context.Context) {
s.startBackgroundTask("批量发布恢复扫描器", func() {
func (s *Server) StartPublishBatchRecovery(ctx context.Context) string {
return s.startBackgroundTaskContext("批量发布恢复扫描器", ctx, func() {
s.RunPublishBatchRecovery(ctx)
})
}
+71 -14
View File
@@ -1,6 +1,7 @@
package server
import (
"context"
"errors"
"net/http"
"strconv"
@@ -8,9 +9,77 @@ import (
"github.com/go-chi/chi/v5"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/db"
)
// storeNotificationUncertainRepository 将数据库通知摘要查询适配为应用层端口。
type storeNotificationUncertainRepository struct {
// store 保存数据库聚合入口,仅在脱敏摘要适配器内使用。
store *db.Store
}
// ListUncertainForUser 查询指定用户的不确定通知摘要,并转换为应用模型。
func (r storeNotificationUncertainRepository) ListUncertainForUser(ctx context.Context, userID int64, limit int) ([]notificationsapp.UncertainSummary, error) {
// rows、err 保存数据库摘要查询结果及错误。
rows, err := r.store.Notifications.ListUncertainOutboxForUser(ctx, userID, limit)
if err != nil {
return nil, err
}
return newNotificationUncertainApplicationSummaries(rows), nil
}
// CountUncertainForUser 统计指定用户的不确定通知数量。
func (r storeNotificationUncertainRepository) CountUncertainForUser(ctx context.Context, userID int64) (int, error) {
return r.store.Notifications.CountUncertainOutboxForUser(ctx, userID)
}
// ListUncertainForAdmin 查询全局不确定通知摘要,并转换为应用模型。
func (r storeNotificationUncertainRepository) ListUncertainForAdmin(ctx context.Context, limit int) ([]notificationsapp.UncertainSummary, error) {
// rows、err 保存数据库全局摘要查询结果及错误。
rows, err := r.store.Notifications.ListUncertainOutboxForAdmin(ctx, limit)
if err != nil {
return nil, err
}
return newNotificationUncertainApplicationSummaries(rows), nil
}
// CountUncertainForAdmin 统计全局不确定通知数量。
func (r storeNotificationUncertainRepository) CountUncertainForAdmin(ctx context.Context) (int, error) {
return r.store.Notifications.CountUncertainOutboxForAdmin(ctx)
}
// newStoreNotificationUncertainRepository 创建通知不确定状态应用服务使用的数据库适配器。
func newStoreNotificationUncertainRepository(store *db.Store) notificationsapp.Repository {
if store == nil || store.Notifications == nil {
return nil
}
return storeNotificationUncertainRepository{store: store}
}
// newNotificationUncertainApplicationSummaries 将数据库摘要转换为不含正文的应用模型。
func newNotificationUncertainApplicationSummaries(rows []db.NotificationUncertainSummary) []notificationsapp.UncertainSummary {
// summaries 保存脱离数据库模型的非敏感通知摘要。
summaries := make([]notificationsapp.UncertainSummary, 0, len(rows))
// row 表示当前待转换的数据库通知摘要。
for _, row := range rows {
summaries = append(summaries, notificationsapp.UncertainSummary{
ID: row.ID, ChannelID: row.ChannelID, OwnerUserID: row.OwnerUserID,
EventType: row.EventType, AttemptCount: row.AttemptCount,
UncertainAt: row.UncertainAt, HasError: row.HasError,
})
}
return summaries
}
// 确保数据库适配器覆盖通知不确定状态应用端口的全部能力。
var _ notificationsapp.Repository = storeNotificationUncertainRepository{}
// uncertainNotificationsApplication 返回当前 Server 绑定的通知不确定状态应用服务。
func (s *Server) uncertainNotificationsApplication() *notificationsapp.Service {
return s.applicationServiceSet().uncertainNotifications
}
// mountNotificationsReal 通知渠道 + 账号绑定。
func (s *Server) mountNotificationsReal(r chi.Router) {
r.Get("/notification-channels", s.listChannels)
@@ -32,17 +101,11 @@ func (s *Server) listUncertainNotifications(w http.ResponseWriter, r *http.Reque
// limit 保存运维列表页请求的最大条数,超出范围时使用数据库默认上限。
limit := parsePositiveInt(r.URL.Query().Get("limit"), 20)
// items 保存当前用户可见的不确定通知摘要。
items, err := s.Store.Notifications.ListUncertainOutboxForUser(r.Context(), sess.UserID, limit)
items, total, err := s.uncertainNotificationsApplication().ListForUser(r.Context(), sess.UserID, limit)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询通知状态失败")
return
}
// total 保存当前用户渠道的不确定通知总数。
total, err := s.Store.Notifications.CountUncertainOutboxForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计通知状态失败")
return
}
writeJSON(w, http.StatusOK, newNotificationUncertainOutboxResponse(items, total, false))
}
@@ -51,17 +114,11 @@ func (s *Server) listAdminUncertainNotifications(w http.ResponseWriter, r *http.
// limit 保存管理员运维查询的最大条数,超出范围时使用数据库默认上限。
limit := parsePositiveInt(r.URL.Query().Get("limit"), 50)
// items 保存所有用户渠道的不确定通知摘要,但不包含正文和错误原文。
items, err := s.Store.Notifications.ListUncertainOutboxForAdmin(r.Context(), limit)
items, total, err := s.uncertainNotificationsApplication().ListForAdmin(r.Context(), limit)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询通知状态失败")
return
}
// total 保存全局不确定通知总数。
total, err := s.Store.Notifications.CountUncertainOutboxForAdmin(r.Context())
if err != nil {
writeErr(w, http.StatusInternalServerError, "统计通知状态失败")
return
}
writeJSON(w, http.StatusOK, newNotificationUncertainOutboxResponse(items, total, true))
}
@@ -267,8 +267,8 @@ func (s *Server) RunOrderRefreshRecovery(ctx context.Context) {
}
// StartOrderRefreshRecovery 启动受 Server 生命周期管理的订单刷新恢复扫描器。
func (s *Server) StartOrderRefreshRecovery(ctx context.Context) {
s.startBackgroundTask("订单刷新恢复扫描器", func() {
func (s *Server) StartOrderRefreshRecovery(ctx context.Context) string {
return s.startBackgroundTaskContext("订单刷新恢复扫描器", ctx, func() {
s.RunOrderRefreshRecovery(ctx)
})
}
+44 -12
View File
@@ -99,14 +99,18 @@ type Server struct {
workerCount int
workersDone chan struct{}
backgroundWG sync.WaitGroup
lifecycleMu sync.RWMutex
lifecycleCtx context.Context
lifecycleCancel context.CancelFunc
httpServer *http.Server
httpDone chan struct{}
httpErr error
started bool
stopped bool
// taskRegistryMu 保护后台任务注册表的惰性初始化,避免测试构造的零值 Server 产生数据竞争。
taskRegistryMu sync.Mutex
// taskRegistry 保存 Server 自有后台任务的生命周期状态,不持久化业务数据或敏感凭证。
taskRegistry *taskRegistry
lifecycleMu sync.RWMutex
lifecycleCtx context.Context
lifecycleCancel context.CancelFunc
httpServer *http.Server
httpDone chan struct{}
httpErr error
started bool
stopped bool
qrMu sync.Mutex
qrPersisted map[string]qrLoginPersistence
@@ -163,6 +167,7 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
qrOwners: make(map[string]qrLoginOwner),
loginLimiter: newLoginFailureLimiter(),
itemSpecCache: make(map[string]itemSpecCacheEntry),
taskRegistry: newTaskRegistry(),
}
// option 表示当前遍历过程中的option
for _, option := range options {
@@ -631,11 +636,20 @@ func (s *Server) lifecycleContext() context.Context {
// startBackgroundTask 登记并启动一个受 Server 生命周期管理的后台任务。
// 调用方负责在任务函数内部响应上下文取消;WaitForBackground 会等待任务退出。
// startBackgroundTask 负责开始Background任务相关处理。
func (s *Server) startBackgroundTask(name string, task func()) {
func (s *Server) startBackgroundTask(name string, task func()) string {
return s.startBackgroundTaskContext(name, s.lifecycleContext(), task)
}
// startBackgroundTaskContext 登记并启动带显式 Context 的 Server 后台任务。
// 返回值是可供管理端查询的任务 ID;任务完成、取消或超时后会保留有限历史。
func (s *Server) startBackgroundTaskContext(name string, ctx context.Context, task func()) string {
// taskID、complete 记录任务状态并提供一次性收束回调。
taskID, complete := s.taskRegistryForServer().start(name, ctx)
s.backgroundWG.Add(1)
// #nosec G118 -- 任务由调用方提供的 Server 生命周期控制。
go func() {
defer s.backgroundWG.Done()
defer complete(nil)
if task == nil {
if s.Logger != nil {
s.Logger.Warn("跳过空后台任务", "task", name)
@@ -644,18 +658,32 @@ func (s *Server) startBackgroundTask(name string, task func()) {
}
task()
}()
return taskID
}
// StartOrderReconciliationRecovery 启动受 Server 生命周期管理的订单补偿扫描器。
func (s *Server) StartOrderReconciliationRecovery(ctx context.Context) {
func (s *Server) StartOrderReconciliationRecovery(ctx context.Context) string {
if s == nil || s.reconciliation == nil {
return
return ""
}
s.startBackgroundTask("订单状态补偿扫描器", func() {
return s.startBackgroundTaskContext("订单状态补偿扫描器", ctx, func() {
s.reconciliation.Run(ctx)
})
}
// taskRegistryForServer 返回 Server 的后台任务注册表;零值 Server 也会安全惰性初始化。
func (s *Server) taskRegistryForServer() *taskRegistry {
if s == nil {
return newTaskRegistry()
}
s.taskRegistryMu.Lock()
defer s.taskRegistryMu.Unlock()
if s.taskRegistry == nil {
s.taskRegistry = newTaskRegistry()
}
return s.taskRegistry
}
// beginWorker 负责begin工作器相关处理。
func (s *Server) beginWorker() func() {
s.workerMu.Lock()
@@ -695,6 +723,10 @@ func (s *Server) waitForWorkersContext(ctx context.Context) bool {
// done 保存done,供当前处理流程使用
done := s.workersDone
s.workerMu.Unlock()
if done == nil {
// 零值 Server 尚未登记批量 worker,可直接视为已完成。
return true
}
select {
case <-done:
return true
+4 -3
View File
@@ -2,6 +2,7 @@ package server
import (
chatapp "xianyu-go/internal/application/chat"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
@@ -816,12 +817,12 @@ type notificationUncertainOutboxResponse struct {
Items []notificationUncertainOutboxItem `json:"items"`
}
// newNotificationUncertainOutboxResponse 将数据库不确定状态摘要转换为非敏感 HTTP DTO。
// newNotificationUncertainOutboxResponse 将应用层不确定状态摘要转换为非敏感 HTTP DTO。
// includeOwner 仅管理员列表使用,用于展示渠道所属用户但不改变正文脱敏边界。
func newNotificationUncertainOutboxResponse(items []db.NotificationUncertainSummary, total int, includeOwner bool) notificationUncertainOutboxResponse {
func newNotificationUncertainOutboxResponse(items []notificationsapp.UncertainSummary, total int, includeOwner bool) notificationUncertainOutboxResponse {
// result 保存不确定通知查询的具名响应。
result := notificationUncertainOutboxResponse{Total: total, Items: make([]notificationUncertainOutboxItem, 0, len(items))}
// item 保存当前待转换的数据库摘要。
// item 保存当前待转换的应用层摘要。
for _, item := range items {
// responseItem 保存当前摘要对应的非敏感 API 行。
responseItem := notificationUncertainOutboxItem{
+62
View File
@@ -0,0 +1,62 @@
package server
import (
"net/http"
"strconv"
"time"
)
// taskStatusResponse 是管理端查询 Server 后台任务状态时使用的具名响应 DTO。
type taskStatusResponse struct {
// ID 是进程内任务标识,可用于关联日志和本次查询结果。
ID string `json:"id"`
// Name 是任务的稳定业务名称。
Name string `json:"name"`
// State 是 running、succeeded、failed、canceled 或 timed_out 之一。
State string `json:"state"`
// StartedAt 是任务登记时间,使用 UTC RFC3339 JSON 格式。
StartedAt time.Time `json:"started_at"`
// FinishedAt 是任务终态时间;运行中的任务为 null。
FinishedAt *time.Time `json:"finished_at,omitempty"`
// DeadlineAt 是任务上下文截止时间;无截止时间时为 null。
DeadlineAt *time.Time `json:"deadline_at,omitempty"`
}
// listAdminTasks 返回管理员可见的 Server 后台任务状态,不包含任务参数和敏感数据。
func (s *Server) listAdminTasks(w http.ResponseWriter, r *http.Request) {
// limit 控制单次响应的历史任务数量,避免管理端一次读取过大结果。
limit := 128
// rawLimit 是管理端请求的 limit 查询参数原文。
if rawLimit := r.URL.Query().Get("limit"); rawLimit != "" {
// parsedLimit 是调用方请求的历史条数。
parsedLimit, parseErr := strconv.Atoi(rawLimit)
if parseErr != nil || parsedLimit < 1 || parsedLimit > 128 {
writeErr(w, http.StatusBadRequest, "limit 必须是 1 到 128 之间的整数")
return
}
limit = parsedLimit
}
// snapshots 是注册表返回的后台任务状态副本。
snapshots := s.taskRegistryForServer().list()
// result 是经过 transport DTO 转换后的管理端响应列表。
result := make([]taskStatusResponse, 0, minInt(limit, len(snapshots)))
// index、snapshot 分别表示返回列表中的下标和当前后台任务状态快照。
for index, snapshot := range snapshots {
if index >= limit {
break
}
result = append(result, taskStatusResponse{
ID: snapshot.ID, Name: snapshot.Name, State: string(snapshot.State),
StartedAt: snapshot.StartedAt, FinishedAt: snapshot.FinishedAt, DeadlineAt: snapshot.DeadlineAt,
})
}
writeJSON(w, http.StatusOK, result)
}
// minInt 返回两个非负整数中的较小值,供响应容量计算使用。
func minInt(left, right int) int {
if left < right {
return left
}
return right
}
+191
View File
@@ -0,0 +1,191 @@
package server
import (
"context"
"fmt"
"sort"
"sync"
"sync/atomic"
"time"
)
// taskState 表示 Server 后台任务对外可观测的生命周期状态。
type taskState string
const (
// taskStateRunning 表示任务已启动但尚未完成。
taskStateRunning taskState = "running"
// taskStateSucceeded 表示任务函数正常返回且上下文未取消。
taskStateSucceeded taskState = "succeeded"
// taskStateFailed 表示任务函数返回时记录了错误。
taskStateFailed taskState = "failed"
// taskStateCanceled 表示任务因父 Context 被主动取消而收束。
taskStateCanceled taskState = "canceled"
// taskStateTimedOut 表示任务因带截止时间的 Context 超时而收束。
taskStateTimedOut taskState = "timed_out"
)
// taskStatusSnapshot 是后台任务的非敏感状态快照,供管理端 DTO 转换使用。
type taskStatusSnapshot struct {
// ID 是当前 Server 进程内唯一的任务标识,不代表数据库主键。
ID string
// Name 是任务的稳定业务名称,用于运维定位任务来源。
Name string
// State 是任务当前生命周期状态。
State taskState
// StartedAt 是任务开始执行的 UTC 时间。
StartedAt time.Time
// FinishedAt 是任务完成或取消的 UTC 时间;仍运行时为空。
FinishedAt *time.Time
// DeadlineAt 是任务 Context 的截止时间;没有截止时间时为空。
DeadlineAt *time.Time
}
// trackedTask 保存单个后台任务的内部状态及其取消上下文。
type trackedTask struct {
// snapshot 保存任务的可查询字段;修改时由 taskRegistry.mu 保护。
snapshot taskStatusSnapshot
// ctx 用于在查询时识别尚未写入终态的取消或超时任务。
ctx context.Context
}
// taskRegistry 管理 Server 后台任务的有限状态历史。
// registry 只保存任务名称、时间和状态,不保存请求体、Cookie、Token 或错误正文。
type taskRegistry struct {
// mu 保护 tasks、order 和任务快照;nextID 由原子操作单独保护。
mu sync.RWMutex
// nextID 生成当前进程内单调递增的任务序号。
nextID uint64
// tasks 按任务 ID 保存运行中和有限历史任务。
tasks map[string]*trackedTask
// order 按启动顺序保存任务 ID,用于限制历史容量和稳定返回顺序。
order []string
// maxHistory 限制内存中保留的任务数量,避免恢复扫描器长期运行导致无界增长。
maxHistory int
}
// newTaskRegistry 创建一个保留有限历史的后台任务注册表。
func newTaskRegistry() *taskRegistry {
return &taskRegistry{
tasks: make(map[string]*trackedTask),
maxHistory: 128,
}
}
// start 登记任务并返回任务 ID 与幂等收束回调。
// ctx 是任务的取消和超时来源;complete 必须在任务函数退出时调用,重复调用不会覆盖首个终态。
func (r *taskRegistry) start(name string, ctx context.Context) (string, func(error)) {
if r == nil {
r = newTaskRegistry()
}
if ctx == nil {
ctx = context.Background()
}
// taskID 是进程内唯一标识,便于日志与管理端状态查询关联。
taskID := fmt.Sprintf("srv-task-%d", atomic.AddUint64(&r.nextID, 1))
// startedAt 记录任务实际进入 goroutine 前的登记时间。
startedAt := time.Now().UTC()
// snapshot 是新任务的初始状态快照。
snapshot := taskStatusSnapshot{ID: taskID, Name: name, State: taskStateRunning, StartedAt: startedAt}
// deadline、hasDeadline 分别表示 Context 的截止时间及其是否存在截止时间。
if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
// deadlineAt 保存 Context 的截止时间,帮助运维识别尚未收束的超时任务。
deadlineAt := deadline.UTC()
snapshot.DeadlineAt = &deadlineAt
}
r.mu.Lock()
r.tasks[taskID] = &trackedTask{snapshot: snapshot, ctx: ctx}
r.order = append(r.order, taskID)
r.pruneLocked()
r.mu.Unlock()
// complete 负责把任务函数的退出结果转换为统一状态;它可被 defer 安全调用。
complete := func(taskErr error) {
r.finish(taskID, taskErr)
}
return taskID, complete
}
// finish 将任务写入首个终态;错误正文不会进入注册表,避免敏感信息通过管理端泄露。
func (r *taskRegistry) finish(taskID string, taskErr error) {
if r == nil {
return
}
r.mu.Lock()
defer r.mu.Unlock()
// task 保存待收束的任务记录。
task, ok := r.tasks[taskID]
if !ok || task.snapshot.State != taskStateRunning {
return
}
// finishedAt 记录任务函数退出的 UTC 时间。
finishedAt := time.Now().UTC()
task.snapshot.FinishedAt = &finishedAt
if taskErr != nil {
task.snapshot.State = taskStateFailed
return
}
task.snapshot.State = stateForContext(task.ctx)
}
// stateForContext 将已取消的 Context 分类为主动取消或截止时间超时。
func stateForContext(ctx context.Context) taskState {
if ctx == nil {
return taskStateSucceeded
}
// contextErr 是任务退出时 Context 的最终错误分类。
contextErr := ctx.Err()
switch contextErr {
case context.DeadlineExceeded:
return taskStateTimedOut
case context.Canceled:
return taskStateCanceled
default:
return taskStateSucceeded
}
}
// list 返回按最近启动时间倒序排列的状态快照,并即时反映尚未收束任务的 Context 超时。
func (r *taskRegistry) list() []taskStatusSnapshot {
if r == nil {
return nil
}
r.mu.RLock()
// snapshots 是脱离锁后返回的快照副本,避免调用方持有注册表读锁。
snapshots := make([]taskStatusSnapshot, 0, len(r.tasks))
// task 表示当前遍历的内部任务记录。
for _, task := range r.tasks {
// snapshot 是当前任务的值副本,指针时间字段在复制前后均不再修改。
snapshot := task.snapshot
// contextState 表示任务 Context 当前是否已经取消或超时。
contextState := stateForContext(task.ctx)
if snapshot.State == taskStateRunning {
if contextState != taskStateSucceeded {
snapshot.State = contextState
}
}
snapshots = append(snapshots, snapshot)
}
r.mu.RUnlock()
sort.SliceStable(snapshots, func(left, right int) bool {
return snapshots[left].StartedAt.After(snapshots[right].StartedAt)
})
return snapshots
}
// pruneLocked 删除最早的已完成历史,调用方必须持有 r.mu 写锁。
func (r *taskRegistry) pruneLocked() {
for len(r.order) > r.maxHistory {
// oldestID 是按启动顺序最早的任务标识。
oldestID := r.order[0]
r.order = r.order[1:]
// oldestTask 是待删除的历史记录。
oldestTask, exists := r.tasks[oldestID]
if !exists || oldestTask.snapshot.State != taskStateRunning {
delete(r.tasks, oldestID)
continue
}
// 运行中的任务不能被历史容量清理,放回队尾等待完成后再清理。
r.order = append(r.order, oldestID)
return
}
}
+156
View File
@@ -0,0 +1,156 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
// TestTaskRegistryTracksCompletion 证明正常返回的后台任务会留下成功终态。
func TestTaskRegistryTracksCompletion(t *testing.T) {
// registry 是本测试使用的内存任务注册表。
registry := newTaskRegistry()
// taskID、complete 是任务标识及退出时的收束回调。
taskID, complete := registry.start("测试任务", context.Background())
complete(nil)
// snapshots 是任务状态快照列表。
snapshots := registry.list()
if len(snapshots) != 1 || snapshots[0].ID != taskID || snapshots[0].State != taskStateSucceeded {
t.Fatalf("任务正常完成后的状态不正确: %+v", snapshots)
}
}
// TestTaskRegistryTracksCancellationAndTimeout 证明取消与超时不会被误报为成功。
func TestTaskRegistryTracksCancellationAndTimeout(t *testing.T) {
// canceledContext、cancelCanceled 是主动取消任务的上下文及其取消函数。
canceledContext, cancelCanceled := context.WithCancel(context.Background())
// canceledRegistry 是主动取消场景使用的注册表。
canceledRegistry := newTaskRegistry()
// canceledComplete 是主动取消任务的终态收束回调。
_, canceledComplete := canceledRegistry.start("取消任务", canceledContext)
cancelCanceled()
canceledComplete(nil)
// snapshots 是主动取消任务的状态快照列表。
if snapshots := canceledRegistry.list(); len(snapshots) != 1 || snapshots[0].State != taskStateCanceled {
t.Fatalf("任务取消后的状态不正确: %+v", snapshots)
}
// timeoutContext、cancelTimeout 是超时任务的上下文及其释放函数。
timeoutContext, cancelTimeout := context.WithTimeout(context.Background(), time.Millisecond)
defer cancelTimeout()
// timeoutRegistry 是超时场景使用的注册表。
timeoutRegistry := newTaskRegistry()
// timeoutComplete 是超时任务的终态收束回调。
_, timeoutComplete := timeoutRegistry.start("超时任务", timeoutContext)
select {
case <-timeoutContext.Done():
case <-time.After(time.Second):
t.Fatal("超时上下文未按预期结束")
}
// pendingSnapshots 是任务函数尚未退出时的即时状态,用于验证超时可观测性。
pendingSnapshots := timeoutRegistry.list()
if len(pendingSnapshots) != 1 || pendingSnapshots[0].State != taskStateTimedOut {
t.Fatalf("任务超时未被即时观测: %+v", pendingSnapshots)
}
timeoutComplete(nil)
// finalSnapshots 是超时任务退出后的最终状态快照列表。
if finalSnapshots := timeoutRegistry.list(); len(finalSnapshots) != 1 || finalSnapshots[0].State != taskStateTimedOut {
t.Fatalf("任务退出后的超时状态不正确: %+v", finalSnapshots)
}
}
// TestListAdminTasksReturnsNamedStatusDTO 证明管理端任务查询只返回具名非敏感状态字段。
func TestListAdminTasksReturnsNamedStatusDTO(t *testing.T) {
// srv 是只装配任务注册表的最小 HTTP 服务实例。
srv := &Server{taskRegistry: newTaskRegistry()}
// _, complete 是已登记任务的标识和完成回调。
_, complete := srv.taskRegistry.start("HTTP 测试任务", context.Background())
complete(nil)
// request、recorder 是管理端查询请求及其响应捕获器。
request := httptest.NewRequest(http.MethodGet, "/api/v1/admin/tasks?limit=1", nil)
// recorder 捕获管理端任务查询响应。
recorder := httptest.NewRecorder()
srv.listAdminTasks(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("任务查询状态码=%d, body=%s", recorder.Code, recorder.Body.String())
}
// response 是管理端具名状态 DTO 列表。
var response []taskStatusResponse
// decodeErr 是管理端状态 DTO 的 JSON 解析错误。
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("任务状态响应解析失败: %v", decodeErr)
}
if len(response) != 1 || response[0].Name != "HTTP 测试任务" || response[0].State != string(taskStateSucceeded) {
t.Fatalf("任务状态响应不正确: %+v", response)
}
}
// TestVersionedAdminTaskRouteRequiresAdminAndReturnsStatus 证明版本化管理路由已挂载并继承管理员权限。
func TestVersionedAdminTaskRouteRequiresAdminAndReturnsStatus(t *testing.T) {
// srv、cleanup 是带测试数据库和认证服务的完整 HTTP 服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// taskDone 是用于快速完成测试任务的退出信号。
taskDone := make(chan struct{})
srv.startBackgroundTaskContext("路由测试任务", context.Background(), func() {
close(taskDone)
})
<-taskDone
// handler 是当前版本化管理路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后的认证会话。
sessionCookie := loginHelper(t, handler)
// request、recorder 是版本化任务查询请求及响应捕获器。
request := httptest.NewRequest(http.MethodGet, "/api/v1/admin/tasks", nil)
request.AddCookie(sessionCookie)
// recorder 捕获版本化管理员任务查询响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("管理员任务查询状态码=%d, body=%s", recorder.Code, recorder.Body.String())
}
// response 是路由返回的任务状态 DTO 列表。
var response []taskStatusResponse
// decodeErr 是路由响应 JSON 的解析错误。
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("管理员任务响应解析失败: %v", decodeErr)
}
if len(response) == 0 || response[0].Name != "路由测试任务" {
t.Fatalf("管理员任务响应不正确: %+v", response)
}
}
// TestStartBackgroundTaskContextWaitsForTaskExit 证明 Server Stop 会等待已登记任务退出。
func TestStartBackgroundTaskContextWaitsForTaskExit(t *testing.T) {
// srv 是零值兼容的 Server 生命周期测试实例。
srv := &Server{}
// taskStarted、releaseTask 分别表示任务开始及允许任务退出的信号。
taskStarted := make(chan struct{})
// releaseTask 是允许阻塞测试任务退出的信号。
releaseTask := make(chan struct{})
srv.startBackgroundTaskContext("阻塞测试任务", context.Background(), func() {
close(taskStarted)
<-releaseTask
})
<-taskStarted
// waitDone 表示 WaitForBackground 的退出信号。
waitDone := make(chan struct{})
go func() {
srv.WaitForBackground()
close(waitDone)
}()
select {
case <-waitDone:
t.Fatal("后台任务仍未退出时不应完成等待")
case <-time.After(20 * time.Millisecond):
}
close(releaseTask)
select {
case <-waitDone:
case <-time.After(time.Second):
t.Fatal("后台任务退出后等待未完成")
}
}
@@ -26,5 +26,6 @@ func (s *Server) mountVersionedAdminAnalyticsRoutes(r chi.Router) {
r.Delete("/api/v1/admin/users/{user_id}", s.adminDeleteUser)
r.Get("/api/v1/admin/cookies", s.adminListCookies)
r.Get("/api/v1/admin/stats", s.adminStats)
r.Get("/api/v1/admin/tasks", s.listAdminTasks)
})
}