重构:完成架构一致性整改与生命周期收口

This commit is contained in:
Christ committed 2026-08-18 14:05:08 +08:00
1 parent 55904cc409
commit 9eb6be2875
344 files changed
+15961 -13926

No files matched your search

+1 -1
View File
@@ -29,7 +29,7 @@ var (
// SyncError 保留同步失败阶段,同时隐藏底层数据库和平台实现类型。
type SyncError struct {
// Kind 表示错误发生的平台、凭证或持久化阶段。
// Kind 记录当前操作失败原因发生的平台、凭证或持久化阶段。
Kind SyncErrorKind
// Err 保存供日志和错误链判断的底层原因。
Err error
+48 -12
View File
@@ -37,6 +37,14 @@ type FuncComponent struct {
CloseFunc func(context.Context) error
}
// closeAttempt 保存一次关闭尝试的完成信号和聚合错误;等待者读取固定结果,不受后续重试覆盖。
type closeAttempt struct {
// done 在本次关闭尝试结束后关闭,供并发 Close 等待。
done chan struct{}
// err 保存本次关闭尝试的聚合错误,写入完成后不再修改。
err error
}
// Start 启动函数适配组件。
func (component FuncComponent) Start(ctx context.Context) error {
if component.StartFunc == nil {
@@ -78,7 +86,11 @@ type Coordinator struct {
closed bool
// done 在关闭完成后关闭,供并发 Close/Wait 调用等待。
done chan struct{}
// closeErr 保存首次关闭或启动回滚的聚合错误。
// componentClosed 记录每个已启动组件是否成功关闭;失败组件保留以便后续重试。
componentClosed []bool
// closeAttempt 保存当前或最近一次关闭尝试,保证并发等待者取得对应尝试的固定结果。
closeAttempt *closeAttempt
// closeErr 保存最近一次关闭或启动回滚的聚合错误。
closeErr error
}
@@ -143,9 +155,10 @@ func (coordinator *Coordinator) Start(parent context.Context) error {
lifecycleCtx, cancel := context.WithCancel(parent)
coordinator.lifecycleCtx = lifecycleCtx
coordinator.parentCancel = cancel
coordinator.started = true
// components 是启动阶段的组件快照,避免组件回调期间持有协调器锁。
components := append([]NamedComponent(nil), coordinator.components...)
coordinator.componentClosed = make([]bool, len(components))
coordinator.started = true
coordinator.mu.Unlock()
// index、component 分别表示当前启动组件在登记快照中的序号和定义。
@@ -227,21 +240,20 @@ func (coordinator *Coordinator) Close(ctx context.Context) error {
return err
}
if coordinator.closing {
// done 是首个关闭调用完成时关闭的信号。
done := coordinator.done
// attempt 保存当前关闭尝试;等待者只接收本轮结果,不会被下一轮重试覆盖。
attempt := coordinator.closeAttempt
coordinator.mu.Unlock()
select {
case <-done:
coordinator.mu.Lock()
// err 保存首个关闭调用的聚合结果。
err := coordinator.closeErr
coordinator.mu.Unlock()
return err
case <-attempt.done:
return attempt.err
case <-ctx.Done():
return ctx.Err()
}
}
coordinator.closing = true
// attempt 表示本次关闭尝试;失败后仍可创建新的尝试继续 Join。
attempt := &closeAttempt{done: make(chan struct{})}
coordinator.closeAttempt = attempt
// components 保存已经成功启动的组件快照,关闭时按其登记顺序逆序处理。
components := append([]NamedComponent(nil), coordinator.components[:coordinator.startedCount]...)
// cancel 是协调器共享 Context 的取消函数;组件关闭前先广播取消。
@@ -255,16 +267,40 @@ func (coordinator *Coordinator) Close(ctx context.Context) error {
var closeErr error
// index 表示当前逆序关闭的组件下标。
for index := len(components) - 1; index >= 0; index-- {
coordinator.mu.Lock()
// alreadyClosed 表示该组件是否已在之前的关闭尝试中成功收束。
alreadyClosed := coordinator.componentClosed[index]
coordinator.mu.Unlock()
if alreadyClosed {
continue
}
// err 表示当前组件关闭失败。
if err := components[index].Component.Close(ctx); err != nil {
closeErr = errors.Join(closeErr, fmt.Errorf("关闭生命周期组件 %q 失败: %w", components[index].Name, err))
continue
}
coordinator.mu.Lock()
coordinator.componentClosed[index] = true
coordinator.mu.Unlock()
}
coordinator.mu.Lock()
coordinator.closed = true
// allClosed 表示所有已启动组件都已成功关闭;只有此时才允许 Wait 返回完成。
allClosed := true
// index 表示已启动组件快照中的下标,用于确认每个组件均已收束。
for index := range components {
if !coordinator.componentClosed[index] {
allClosed = false
break
}
}
if allClosed {
coordinator.closed = true
close(coordinator.done)
}
coordinator.closing = false
coordinator.closeErr = closeErr
close(coordinator.done)
attempt.err = closeErr
close(attempt.done)
coordinator.mu.Unlock()
return closeErr
}
@@ -3,6 +3,7 @@ package lifecycle
import (
"context"
"errors"
"strings"
"sync"
"testing"
"time"
@@ -38,6 +39,33 @@ func (fake *lifecycleComponentFake) Close(context.Context) error {
return fake.closeErr
}
// retryCloseComponent 首次关闭等待 Context 取消,后续关闭模拟外部任务最终收束。
type retryCloseComponent struct {
// mu 保护 closeCalls,确保并发测试读取关闭次数时无数据竞争。
mu sync.Mutex
// closeCalls 记录协调器实际调用 Close 的次数。
closeCalls int
}
// Start 让可重试关闭组件立即进入运行状态。
func (*retryCloseComponent) Start(context.Context) error {
return nil
}
// Close 首次等待调用方截止,第二次模拟使用更长 Context 成功收束。
func (component *retryCloseComponent) Close(ctx context.Context) error {
component.mu.Lock()
component.closeCalls++
// callCount 保存本次关闭调用序号,用于区分首次超时和后续重试。
callCount := component.closeCalls
component.mu.Unlock()
if callCount == 1 {
<-ctx.Done()
return ctx.Err()
}
return nil
}
// TestCoordinatorStartsAndClosesInDeterministicOrder 验证正常启动、重复调用和逆序关闭。
func TestCoordinatorStartsAndClosesInDeterministicOrder(t *testing.T) {
// events 保存生命周期事件顺序;mu 保护并发回调写入。
@@ -172,6 +200,56 @@ func TestCoordinatorCloseContextBoundsConcurrentClose(t *testing.T) {
}
}
// TestCoordinatorCloseRetainsIncompleteComponentsForRetry 验证关闭超时后保留未完成组件并支持再次 Join。
func TestCoordinatorCloseRetainsIncompleteComponentsForRetry(t *testing.T) {
// component 保存首次超时、第二次成功的生命周期组件。
component := &retryCloseComponent{}
// coordinator 保存待验证的关闭重试协调器。
coordinator := NewCoordinator()
// err 表示登记可重试组件时的参数校验错误。
if err := coordinator.Add(NamedComponent{Name: "retryable", Component: component}); err != nil {
t.Fatalf("登记可重试组件失败: %v", err)
}
// err 表示启动可重试组件协调器的失败原因。
if err := coordinator.Start(context.Background()); err != nil {
t.Fatalf("启动协调器失败: %v", err)
}
// timeoutCtx 限制首次关闭,模拟组件无法在本轮预算内完成。
timeoutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
// firstErr 保存首次关闭的组件诊断错误。
firstErr := coordinator.Close(timeoutCtx)
if !errors.Is(firstErr, context.DeadlineExceeded) {
t.Fatalf("首次关闭应返回截止错误: %v", firstErr)
}
// err 表示关闭诊断中是否包含未完成组件名称。
if !strings.Contains(firstErr.Error(), "retryable") {
t.Fatalf("关闭错误应包含未完成组件名称: %v", firstErr)
}
// waitCtx 确认首次失败不能伪造协调器已完成关闭。
waitCtx, waitCancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer waitCancel()
// err 表示未完成关闭在短等待 Context 下的结果。
if err := coordinator.WaitContext(waitCtx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("关闭未完成时 Wait 应返回截止错误: %v", err)
}
// err 表示使用更长 Context 重试关闭的结果。
if err := coordinator.Close(context.Background()); err != nil {
t.Fatalf("使用更长 Context 重试关闭失败: %v", err)
}
component.mu.Lock()
// closeCalls 保存组件被协调器调用的总次数,必须包含一次失败和一次重试。
closeCalls := component.closeCalls
component.mu.Unlock()
if closeCalls != 2 {
t.Fatalf("组件关闭调用次数=%d,期望=2", closeCalls)
}
// err 表示所有组件重试收束后等待协调器完成的结果。
if err := coordinator.WaitContext(context.Background()); err != nil {
t.Fatalf("重试成功后 Wait 应完成: %v", err)
}
}
// TestCoordinatorCloseWaitsForStart 验证关闭不会越过仍在执行的组件启动回调。
func TestCoordinatorCloseWaitsForStart(t *testing.T) {
// entered、release 控制组件启动回调的阻塞窗口。
@@ -178,7 +178,7 @@ func TestServiceRejectsSensitivePlainValue(t *testing.T) {
repository := &settingsRepositoryFake{sensitiveKeys: []string{"ai_api_key"}}
// service 保存待测试的设置应用服务。
service := NewService(repository, nil)
// err 表示错误的普通敏感值写入结果。
// err 记录当前操作失败原因的普通敏感值写入结果。
err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"ai_api_key": "secret"}, nil)
if err == nil || !strings.Contains(err.Error(), "敏感设置") {
t.Fatalf("sensitive plain value should fail: %v", err)