阶段六:修复生命周期与运行状态一致性
This commit is contained in:
1 parent
5f8d999ab0
commit
c23a5a18b8
43 files changed
+1541
-171
No files matched your search
@@ -3,6 +3,15 @@ package account
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrRuntimeStopConflict 表示账号实例未能在关闭预算内完全停止,持久化状态保持可重试。
|
||||
ErrRuntimeStopConflict = errors.New("账号运行实例尚未停止")
|
||||
// ErrRuntimeStartUnavailable 表示账号已写入启用或新 Cookie,但运行实例未能达到可运行状态。
|
||||
ErrRuntimeStartUnavailable = errors.New("账号运行实例未能启动")
|
||||
)
|
||||
|
||||
// SettingsUpdateInput 是账号编辑用例的输入;Password 为 nil 时保留数据库中的既有密码。
|
||||
@@ -93,8 +102,12 @@ type SettingsRepository interface {
|
||||
type SettingsRuntime interface {
|
||||
// Restart 在账号启用且 Cookie 变化后重新加载运行实例。
|
||||
Restart(context.Context, string) error
|
||||
// Stop 在账号停用后停止运行实例。
|
||||
Stop(string)
|
||||
// BeginStopping 建立账号停止 fencing,阻止其他运行时入口在停用转换期间启动实例。
|
||||
BeginStopping(string) bool
|
||||
// EndStopping 在状态转换结束后释放账号停止 fencing。
|
||||
EndStopping(string)
|
||||
// StopContext 在调用方关闭预算内停止账号实例,并等待其完全退出。
|
||||
StopContext(context.Context, string) error
|
||||
}
|
||||
|
||||
// SettingsService 编排账号设置、登录信息、状态和暂停用例,不依赖 HTTP 或数据库模型。
|
||||
@@ -103,6 +116,10 @@ type SettingsService struct {
|
||||
repository SettingsRepository
|
||||
// runtime 提供可选的账号运行实例控制能力。
|
||||
runtime SettingsRuntime
|
||||
// transitionMu 保护 transitionLocks 映射;每把锁串行化一个账号的启用、停用和重启状态转换。
|
||||
transitionMu sync.Mutex
|
||||
// transitionLocks 保存按账号分配的状态转换锁;锁不跨账号共享,也不在持锁时持有凭证锁。
|
||||
transitionLocks map[string]*sync.Mutex
|
||||
}
|
||||
|
||||
// NewSettingsService 构造账号设置应用服务并校验必需的持久化端口。
|
||||
@@ -110,10 +127,23 @@ func NewSettingsService(repository SettingsRepository, runtime SettingsRuntime)
|
||||
if repository == nil {
|
||||
return nil, errors.New("账号设置 repository 未初始化")
|
||||
}
|
||||
return &SettingsService{repository: repository, runtime: runtime}, nil
|
||||
return &SettingsService{repository: repository, runtime: runtime, transitionLocks: make(map[string]*sync.Mutex)}, nil
|
||||
}
|
||||
|
||||
// UpdateSettings 原子保存账号设置;Cookie 变化后的运行时重启在释放凭证锁后执行。
|
||||
// transitionLock 返回指定账号唯一的状态转换锁,用于避免启用、停用和 Cookie 重启相互覆盖。
|
||||
func (s *SettingsService) transitionLock(accountID string) *sync.Mutex {
|
||||
s.transitionMu.Lock()
|
||||
defer s.transitionMu.Unlock()
|
||||
// lock 保存当前账号的转换锁;首次使用时创建,之后在服务生命周期内复用。
|
||||
lock := s.transitionLocks[accountID]
|
||||
if lock == nil {
|
||||
lock = &sync.Mutex{}
|
||||
s.transitionLocks[accountID] = lock
|
||||
}
|
||||
return lock
|
||||
}
|
||||
|
||||
// UpdateSettings 原子保存账号设置;Cookie、metadata 和旧 Token 在同一凭证锁内完成,运行时重启在锁外串行执行。
|
||||
func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpdateInput) (SettingsResult, error) {
|
||||
if s == nil || s.repository == nil {
|
||||
return SettingsResult{}, errors.New("账号设置服务未初始化")
|
||||
@@ -121,12 +151,12 @@ func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpda
|
||||
if input.AccountID == "" {
|
||||
return SettingsResult{}, errors.New("缺少账号 ID")
|
||||
}
|
||||
// unlock 负责释放本次账号设置写入的凭证锁。
|
||||
// unlock 负责释放本次账号设置写入的凭证锁,锁覆盖 Cookie、metadata 和旧 Token 的完整替换。
|
||||
unlock := s.repository.LockCredentials(input.AccountID)
|
||||
// pausedUntil、updateErr 保存设置事务返回的暂停截止时间和错误。
|
||||
pausedUntil, updateErr := s.repository.UpdateSettings(ctx, input)
|
||||
unlock()
|
||||
if updateErr != nil {
|
||||
unlock()
|
||||
return SettingsResult{}, updateErr
|
||||
}
|
||||
// result 保存设置写入及后续运行时处理结果。
|
||||
@@ -136,16 +166,36 @@ func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpda
|
||||
tokenErr := s.repository.ClearTokens(ctx, input.AccountID)
|
||||
result.TokenCleanupError = tokenErr
|
||||
}
|
||||
// Cookie、metadata 与旧 Token 都已完成转换后才释放锁;后续运行时 I/O 不得占用该锁。
|
||||
unlock()
|
||||
if input.Cookie != nil && s.runtime != nil {
|
||||
// enabled 表示写入成功后账号的最新启用状态;状态读取失败不覆盖已成功的设置写入。
|
||||
enabled, statusErr := s.repository.StatusOwned(ctx, input.UserID, input.AccountID)
|
||||
if statusErr == nil && enabled {
|
||||
result.RuntimeError = s.runtime.Restart(ctx, input.AccountID)
|
||||
// lock 串行化 Cookie 重启与同账号启停,避免已更新 Cookie 的实例被并发停用或替换。
|
||||
lock := s.transitionLock(input.AccountID)
|
||||
lock.Lock()
|
||||
// restartErr 保存锁外运行时重启错误;Cookie 主写入仍保留,但数据库必须补偿为停用避免状态失真。
|
||||
restartErr := s.runtime.Restart(ctx, input.AccountID)
|
||||
if restartErr != nil {
|
||||
// compensationErr 保存重启失败后写回停用状态的错误;两个错误共同决定调用方是否需要人工恢复。
|
||||
compensationErr := s.setStatusLocked(ctx, input.UserID, input.AccountID, false, "runtime_restart_failed")
|
||||
result.RuntimeError = fmt.Errorf("%w: %v", ErrRuntimeStartUnavailable, errors.Join(restartErr, compensationErr))
|
||||
}
|
||||
lock.Unlock()
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// setStatusLocked 在短凭证锁内写入账号启用状态;调用方不得在持有该锁时执行运行时或平台 I/O。
|
||||
func (s *SettingsService) setStatusLocked(ctx context.Context, userID int64, accountID string, enabled bool, reason string) error {
|
||||
// unlock 仅保护持久化状态更新与相关敏感元数据一致性,不跨越运行时关闭或启动。
|
||||
unlock := s.repository.LockCredentials(accountID)
|
||||
defer unlock()
|
||||
return s.repository.SetStatusOwned(ctx, userID, accountID, enabled, reason)
|
||||
}
|
||||
|
||||
// UpdateLoginInfo 保存账号用户名、密码和浏览器显示设置;既有密码不会被应用层读取。
|
||||
func (s *SettingsService) UpdateLoginInfo(ctx context.Context, input LoginInfoUpdateInput) error {
|
||||
if s == nil || s.repository == nil {
|
||||
@@ -160,7 +210,7 @@ func (s *SettingsService) UpdateLoginInfo(ctx context.Context, input LoginInfoUp
|
||||
return s.repository.UpdateLoginInfo(ctx, input)
|
||||
}
|
||||
|
||||
// SetStatus 更新账号启用状态并在持久化成功后控制运行实例。
|
||||
// SetStatus 同步完成账号持久化状态与运行实例转换;失败会保留可重试状态而不是伪造成功。
|
||||
func (s *SettingsService) SetStatus(ctx context.Context, userID int64, accountID string, enabled bool) (StatusResult, error) {
|
||||
if s == nil || s.repository == nil {
|
||||
return StatusResult{}, errors.New("账号设置服务未初始化")
|
||||
@@ -168,27 +218,43 @@ func (s *SettingsService) SetStatus(ctx context.Context, userID int64, accountID
|
||||
if accountID == "" {
|
||||
return StatusResult{}, errors.New("缺少账号 ID")
|
||||
}
|
||||
// reason 由应用层统一产生,避免 HTTP 层决定持久化状态原因。
|
||||
reason := ""
|
||||
// lock 串行化同一账号的启用、停用和 Cookie 重启,锁顺序始终先转换锁、后短凭证锁。
|
||||
lock := s.transitionLock(accountID)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
// result 保存持久化状态完成后运行时收束或启动失败的显式结果。
|
||||
result := StatusResult{}
|
||||
if !enabled {
|
||||
reason = "manual"
|
||||
if s.runtime != nil {
|
||||
if !s.runtime.BeginStopping(accountID) {
|
||||
result.RuntimeError = ErrRuntimeStopConflict
|
||||
return result, nil
|
||||
}
|
||||
defer s.runtime.EndStopping(accountID)
|
||||
// stopErr 保存关闭预算内无法完全停止旧实例的原因;此时禁止写数据库停用状态。
|
||||
if stopErr := s.runtime.StopContext(ctx, accountID); stopErr != nil {
|
||||
result.RuntimeError = fmt.Errorf("%w: %v", ErrRuntimeStopConflict, stopErr)
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
// statusErr 保存停止完成后写入数据库停用状态的错误。
|
||||
if statusErr := s.setStatusLocked(ctx, userID, accountID, false, "manual"); statusErr != nil {
|
||||
return StatusResult{}, statusErr
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
// unlock 负责释放账号状态写入期间持有的凭证锁。
|
||||
unlock := s.repository.LockCredentials(accountID)
|
||||
// statusErr 保存账号状态持久化错误。
|
||||
statusErr := s.repository.SetStatusOwned(ctx, userID, accountID, enabled, reason)
|
||||
unlock()
|
||||
if statusErr != nil {
|
||||
// statusErr 保存写入数据库启用状态的错误;写入失败时不得启动运行实例。
|
||||
if statusErr := s.setStatusLocked(ctx, userID, accountID, true, ""); statusErr != nil {
|
||||
return StatusResult{}, statusErr
|
||||
}
|
||||
// result 保存状态写入后运行时启停的结果。
|
||||
result := StatusResult{}
|
||||
if s.runtime != nil {
|
||||
if enabled {
|
||||
result.RuntimeError = s.runtime.Restart(ctx, accountID)
|
||||
} else {
|
||||
s.runtime.Stop(accountID)
|
||||
}
|
||||
if s.runtime == nil {
|
||||
return result, nil
|
||||
}
|
||||
// restartErr 保存启用后实例未能启动的原因;补偿为停用使持久化与运行时状态不再矛盾。
|
||||
if restartErr := s.runtime.Restart(ctx, accountID); restartErr != nil {
|
||||
// compensationErr 保存补偿写入失败;错误仍返回给 HTTP 层,避免伪造启用成功。
|
||||
compensationErr := s.setStatusLocked(ctx, userID, accountID, false, "runtime_start_failed")
|
||||
result.RuntimeError = fmt.Errorf("%w: %v", ErrRuntimeStartUnavailable, errors.Join(restartErr, compensationErr))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ package account
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeSettingsRepository 记录账号设置应用服务对持久化端口的调用。
|
||||
@@ -74,6 +76,66 @@ type fakeSettingsRuntime struct {
|
||||
stopCalls int
|
||||
// restartErr 是预置的重启错误。
|
||||
restartErr error
|
||||
// stopErr 是预置的运行实例停止错误。
|
||||
stopErr error
|
||||
// stopping 表示测试替身是否已建立停止 fencing。
|
||||
stopping bool
|
||||
}
|
||||
|
||||
// credentialInterleavingRepository 用真实互斥锁模拟 Cookie 替换和平台新 Token 保存的竞争时序。
|
||||
type credentialInterleavingRepository struct {
|
||||
// mu 串行化同一账号 Cookie、metadata 与 Token 的敏感持久化转换。
|
||||
mu sync.Mutex
|
||||
// token 保存测试观察到的当前连接 Token,不包含真实凭证。
|
||||
token string
|
||||
// clearStarted 通知旧 Token 清理已经持有凭证锁。
|
||||
clearStarted chan struct{}
|
||||
// allowClear 控制旧 Token 清理何时完成,用于确认并发新 Token 写入会被锁阻塞。
|
||||
allowClear chan struct{}
|
||||
}
|
||||
|
||||
// LockCredentials 获取测试账号唯一的敏感凭证锁。
|
||||
func (repository *credentialInterleavingRepository) LockCredentials(string) func() {
|
||||
repository.mu.Lock()
|
||||
return repository.mu.Unlock
|
||||
}
|
||||
|
||||
// UpdateSettings 模拟 Cookie 主写入成功,不改变测试中的新 Token。
|
||||
func (repository *credentialInterleavingRepository) UpdateSettings(context.Context, SettingsUpdateInput) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// UpdateLoginInfo 满足设置仓储接口;本竞争用例不写入登录资料。
|
||||
func (repository *credentialInterleavingRepository) UpdateLoginInfo(context.Context, LoginInfoUpdateInput) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetStatusOwned 满足设置仓储接口;本竞争用例不改变账号状态。
|
||||
func (repository *credentialInterleavingRepository) SetStatusOwned(context.Context, int64, string, bool, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// StatusOwned 返回停用,避免本凭证锁测试触发运行时重启。
|
||||
func (repository *credentialInterleavingRepository) StatusOwned(context.Context, int64, string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// SetPauseOwned 满足设置仓储接口;本竞争用例不涉及暂停状态。
|
||||
func (repository *credentialInterleavingRepository) SetPauseOwned(context.Context, int64, string, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// GetPauseOwned 满足设置仓储接口;本竞争用例不读取暂停状态。
|
||||
func (repository *credentialInterleavingRepository) GetPauseOwned(context.Context, int64, string) (PauseState, error) {
|
||||
return PauseState{}, nil
|
||||
}
|
||||
|
||||
// ClearTokens 在持有凭证锁时等待测试放行,然后清除 Cookie 变更前的旧 Token。
|
||||
func (repository *credentialInterleavingRepository) ClearTokens(context.Context, string) error {
|
||||
close(repository.clearStarted)
|
||||
<-repository.allowClear
|
||||
repository.token = ""
|
||||
return nil
|
||||
}
|
||||
|
||||
// Restart 记录重启并返回预置错误。
|
||||
@@ -82,8 +144,75 @@ func (f *fakeSettingsRuntime) Restart(context.Context, string) error {
|
||||
return f.restartErr
|
||||
}
|
||||
|
||||
// Stop 记录运行实例停止。
|
||||
func (f *fakeSettingsRuntime) Stop(string) { f.stopCalls++ }
|
||||
// BeginStopping 记录当前测试账号的停止 fencing;重复进入时返回 false。
|
||||
func (f *fakeSettingsRuntime) BeginStopping(string) bool {
|
||||
if f.stopping {
|
||||
return false
|
||||
}
|
||||
f.stopping = true
|
||||
return true
|
||||
}
|
||||
|
||||
// EndStopping 释放当前测试账号的停止 fencing。
|
||||
func (f *fakeSettingsRuntime) EndStopping(string) { f.stopping = false }
|
||||
|
||||
// StopContext 记录带关闭预算的停止调用并返回预置错误。
|
||||
func (f *fakeSettingsRuntime) StopContext(context.Context, string) error {
|
||||
f.stopCalls++
|
||||
return f.stopErr
|
||||
}
|
||||
|
||||
// TestSettingsServiceKeepsCredentialLockUntilOldTokenCleared 验证并发保存的新 Token 不会被旧 Token 清理覆盖。
|
||||
func TestSettingsServiceKeepsCredentialLockUntilOldTokenCleared(t *testing.T) {
|
||||
// repository 保存带真实互斥锁的敏感凭证替身。
|
||||
repository := &credentialInterleavingRepository{token: "old-token", clearStarted: make(chan struct{}), allowClear: make(chan struct{})}
|
||||
// service 保存待验证 Cookie 更新顺序的账号设置服务。
|
||||
service, serviceErr := NewSettingsService(repository, nil)
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造设置服务失败: %v", serviceErr)
|
||||
}
|
||||
// cookie 保存本次替换的 Cookie 明文,仅在测试输入范围存在。
|
||||
cookie := "updated-cookie"
|
||||
// updateDone 保存 Cookie 更新和旧 Token 清理完成后的结果。
|
||||
updateDone := make(chan error, 1)
|
||||
go func() {
|
||||
// _, updateErr 保存设置写入结果与错误;当前测试只关注凭证锁释放时机。
|
||||
_, updateErr := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "acc-1", Cookie: &cookie})
|
||||
updateDone <- updateErr
|
||||
}()
|
||||
select {
|
||||
case <-repository.clearStarted:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("旧 Token 清理未开始")
|
||||
}
|
||||
// newTokenWritten 通知并发平台流程何时真正拿到凭证锁并写入新 Token。
|
||||
newTokenWritten := make(chan struct{})
|
||||
go func() {
|
||||
// unlock 是并发平台流程持有的同账号凭证锁释放函数。
|
||||
unlock := repository.LockCredentials("acc-1")
|
||||
repository.token = "new-token"
|
||||
unlock()
|
||||
close(newTokenWritten)
|
||||
}()
|
||||
select {
|
||||
case <-newTokenWritten:
|
||||
t.Fatal("旧 Token 清理完成前不应写入新 Token")
|
||||
case <-time.After(25 * time.Millisecond):
|
||||
}
|
||||
close(repository.allowClear)
|
||||
// updateErr 保存 Cookie 更新协程完成后返回的错误。
|
||||
if updateErr := <-updateDone; updateErr != nil {
|
||||
t.Fatalf("Cookie 更新失败: %v", updateErr)
|
||||
}
|
||||
select {
|
||||
case <-newTokenWritten:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("凭证锁释放后未写入新 Token")
|
||||
}
|
||||
if repository.token != "new-token" {
|
||||
t.Fatalf("旧 Token 清理覆盖了新 Token: %q", repository.token)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSettingsServiceRestartsAfterCookieWrite 验证 Cookie 写入释放凭证锁后才重启运行实例。
|
||||
func TestSettingsServiceRestartsAfterCookieWrite(t *testing.T) {
|
||||
|
||||
@@ -74,6 +74,74 @@ func TestRefreshJobServiceCreateAndStart(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshJobServiceWorkerOutlivesRequestContext 验证任务创建成功后 HTTP 请求结束不会取消进程生命周期拥有的刷新 worker。
|
||||
func TestRefreshJobServiceWorkerOutlivesRequestContext(t *testing.T) {
|
||||
// repository 保存可完成终态写入的测试任务仓储。
|
||||
repository := completeAppliedRepository()
|
||||
// owner 允许当前用户操作测试账号。
|
||||
owner := &refreshJobOwnerTestDouble{owned: true}
|
||||
// started 通知后台刷新已取得进程生命周期 Context。
|
||||
started := make(chan context.Context, 1)
|
||||
// release 控制后台刷新何时正常结束。
|
||||
release := make(chan struct{})
|
||||
// refresher 保存会等待 release 的刷新端口,便于在 HTTP Context 取消后检查 worker 是否仍活跃。
|
||||
refresher := refreshJobServiceBlockingRefresher{started: started, release: release}
|
||||
// runner、runnerErr 保存应用层 worker 运行器及其构造错误。
|
||||
runner, runnerErr := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{})
|
||||
if runnerErr != nil {
|
||||
t.Fatalf("构造运行器失败: %v", runnerErr)
|
||||
}
|
||||
// service、serviceErr 保存创建和启动任务的应用服务。
|
||||
service, serviceErr := NewRefreshJobService(repository, owner, runner, RefreshJobServiceOptions{})
|
||||
if serviceErr != nil {
|
||||
t.Fatalf("构造刷新任务服务失败: %v", serviceErr)
|
||||
}
|
||||
// requestCtx、cancelRequest 模拟在 HTTP 响应返回后立即结束的请求 Context。
|
||||
requestCtx, cancelRequest := context.WithCancel(context.Background())
|
||||
defer cancelRequest()
|
||||
// lifecycleCtx、cancelLifecycle 是独立于请求的进程生命周期 Context。
|
||||
lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
|
||||
defer cancelLifecycle()
|
||||
// _, startErr 保存创建并启动后台任务的结果。
|
||||
_, startErr := service.CreateAndStart(requestCtx, lifecycleCtx, 7, "cookie-1", "")
|
||||
if startErr != nil {
|
||||
t.Fatalf("创建并启动刷新任务失败: %v", startErr)
|
||||
}
|
||||
// workerCtx 保存后台刷新收到的 Context;必须不是 requestCtx。
|
||||
workerCtx := <-started
|
||||
cancelRequest()
|
||||
if workerCtx == requestCtx || workerCtx.Err() != nil {
|
||||
t.Fatalf("请求结束后 worker 被误取消: worker=%p request=%p err=%v", workerCtx, requestCtx, workerCtx.Err())
|
||||
}
|
||||
close(release)
|
||||
// closeCtx、cancelClose 限制异步任务正常退出的等待时间。
|
||||
closeCtx, cancelClose := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancelClose()
|
||||
// closeErr 保存正常完成后运行器关闭与等待的结果。
|
||||
if closeErr := runner.Close(closeCtx); closeErr != nil {
|
||||
t.Fatalf("关闭后台刷新 worker 失败: %v", closeErr)
|
||||
}
|
||||
}
|
||||
|
||||
// refreshJobServiceBlockingRefresher 是请求与后台生命周期分离测试使用的阻塞刷新端口。
|
||||
type refreshJobServiceBlockingRefresher struct {
|
||||
// started 返回 worker 实际收到的生命周期 Context。
|
||||
started chan<- context.Context
|
||||
// release 控制测试中的刷新业务何时结束。
|
||||
release <-chan struct{}
|
||||
}
|
||||
|
||||
// Refresh 等待测试放行,并在调用方生命周期取消时提前退出。
|
||||
func (refresher refreshJobServiceBlockingRefresher) Refresh(ctx context.Context, _ int64, _, _ string) (RefreshResult, error) {
|
||||
refresher.started <- ctx
|
||||
select {
|
||||
case <-refresher.release:
|
||||
return RefreshResult{Message: "完成"}, nil
|
||||
case <-ctx.Done():
|
||||
return RefreshResult{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshJobServiceCreateRejectsUnownedAccount 验证账号不属于用户时不会创建或抢占任务。
|
||||
func TestRefreshJobServiceCreateRejectsUnownedAccount(t *testing.T) {
|
||||
// repository 记录不应发生的创建和抢占调用。
|
||||
|
||||
@@ -368,6 +368,71 @@ func TestRefreshJobRunnerRecovery(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshJobRunnerRecoversAfterLifecycleCancellation 验证进程取消导致终态无法写入后,过期租约会在后续恢复扫描中重新接管。
|
||||
func TestRefreshJobRunnerRecoversAfterLifecycleCancellation(t *testing.T) {
|
||||
// fixedNow 是首次取消和后续恢复扫描共享的确定性时钟。
|
||||
fixedNow := time.Date(2026, 8, 19, 9, 0, 0, 0, time.UTC)
|
||||
// repository 保存终态写入失败及后续恢复队列的测试配置。
|
||||
repository := completeAppliedRepository()
|
||||
repository.completeErr = context.Canceled
|
||||
repository.jobs = []RefreshJob{{ID: "job-recover-after-cancel", UserID: 7, CookieID: "cookie-7"}}
|
||||
// refresher 等待进程 Context 取消后返回,使失败终态沿用已取消 Context。
|
||||
refresher := &refreshRunnerTestRefresher{waitForCancel: true}
|
||||
// runner、runnerErr 保存具有固定租约和令牌的任务运行器。
|
||||
runner, runnerErr := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{Now: func() time.Time { return fixedNow }, NewToken: func() string { return "recovered-token" }})
|
||||
if runnerErr != nil {
|
||||
t.Fatalf("构造运行器失败: %v", runnerErr)
|
||||
}
|
||||
// lifecycleCtx、cancelLifecycle 模拟进程关闭取消。
|
||||
lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
|
||||
// startErr 保存初始 worker 启动结果。
|
||||
startErr := runner.StartJob(lifecycleCtx, &RefreshJob{ID: "job-recover-after-cancel", UserID: 7, CookieID: "cookie-7"}, "cancelled-token")
|
||||
if startErr != nil {
|
||||
t.Fatalf("启动取消 worker 失败: %v", startErr)
|
||||
}
|
||||
cancelLifecycle()
|
||||
// workerDone 等待取消 worker 清理内存登记;不能调用 Close,否则运行器会拒绝后续恢复 worker。
|
||||
workerDone := make(chan struct{})
|
||||
go func() {
|
||||
runner.Wait()
|
||||
close(workerDone)
|
||||
}()
|
||||
select {
|
||||
case <-workerDone:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("取消 worker 未退出")
|
||||
}
|
||||
repository.mu.Lock()
|
||||
// completionCalls 保存进程取消时失败的终态写入记录。
|
||||
completionCalls := append([]refreshRunnerCompleteCall(nil), repository.completeCalls...)
|
||||
repository.completeErr = nil
|
||||
repository.mu.Unlock()
|
||||
if len(completionCalls) == 0 || completionCalls[0].jobID != "job-recover-after-cancel" {
|
||||
t.Fatalf("取消后未尝试终态写入: %+v", completionCalls)
|
||||
}
|
||||
// recoveryErr 保存新的可用生命周期下恢复扫描的结果。
|
||||
recoveryErr := runner.RunRecovery(context.Background())
|
||||
if recoveryErr != nil {
|
||||
t.Fatalf("恢复扫描失败: %v", recoveryErr)
|
||||
}
|
||||
// recoveryCloseCtx、cancelRecoveryClose 等待恢复 worker 完成。
|
||||
recoveryCloseCtx, cancelRecoveryClose := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancelRecoveryClose()
|
||||
// closeErr 保存恢复 worker 结束后的关闭结果。
|
||||
if closeErr := runner.Close(recoveryCloseCtx); closeErr != nil {
|
||||
t.Fatalf("关闭恢复 worker 失败: %v", closeErr)
|
||||
}
|
||||
repository.mu.Lock()
|
||||
// requeues 保存恢复扫描对过期任务的重新入队记录;claims 保存恢复 worker 获得的新租约记录。
|
||||
requeues := append([]string(nil), repository.requeueCalls...)
|
||||
// claims 是断言恢复 worker 使用新令牌的租约快照。
|
||||
claims := append([]refreshRunnerClaimCall(nil), repository.claimCalls...)
|
||||
repository.mu.Unlock()
|
||||
if len(requeues) != 1 || requeues[0] != "job-recover-after-cancel" || len(claims) != 1 || claims[0].token != "recovered-token" {
|
||||
t.Fatalf("取消后的恢复接管不正确: requeues=%v claims=%+v", requeues, claims)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshJobRunnerRecoveryError 验证恢复仓储错误直接返回,便于生命周期层观测并决定下一轮重试。
|
||||
func TestRefreshJobRunnerRecoveryError(t *testing.T) {
|
||||
// scanErr 是恢复扫描仓储返回的错误。
|
||||
|
||||
Reference in new issue
Block a user