收口生命周期停止上下文边界
This commit is contained in:
1 parent
e953464df9
commit
12a79d4f62
8 files changed
+201
-38
No files matched your search
+4
-1
@@ -351,7 +351,10 @@ func runServer(parent context.Context, opts serverOptions) error {
|
||||
stopCancel()
|
||||
automationScheduler.Wait()
|
||||
renewalScheduler.Wait()
|
||||
mgr.StopAll()
|
||||
// err 表示账号运行时未能在关闭上下文内完整停止的错误。
|
||||
if err := mgr.StopAllContext(stopCtx); err != nil {
|
||||
logger.Warn("账号运行时关闭未完成", "err", err)
|
||||
}
|
||||
if bm != nil {
|
||||
_ = bm.Close()
|
||||
}
|
||||
|
||||
@@ -731,3 +731,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-15 | P1 订单 Repository Port 迁移切片 | 已完成 | 将 `orderRepository` 从 `internal/server` 迁移为 `internal/application/orders.Repository`;应用 Port 只暴露领域模型、`Writer`/`UnitOfWork`、凭证协调和平台运行视图,不出现 `sql.Tx`、`db.*`、HTTP 或 Server 类型;Server 仅保留 `storeOrderRepository` 基础设施适配器;订单全量测试、架构门禁和中文注释门禁通过。订单运行时 Port 仍依赖 Server 适配边界,其他应用服务及事务/批量治理仍未完成 |
|
||||
| 2026-08-15 | P0 敏感设置跨方言回归补强 | 已完成 | `TestMultiDB_SettingsQuoteKey` 新增敏感设置 `replace/retain/clear`、脱敏读取和密文解密回归;SQLite 在当前环境执行通过,MySQL/Postgres 仅在 `TEST_MYSQL_URL`/`TEST_POSTGRES_URL` 提供时自动加入,当前环境未提供外部数据库,因此不宣称三库实测完成。P0 的运维输出和敏感访问审计仍待完成 |
|
||||
| 2026-08-15 | P1 应用 Port 类型架构门禁切片 | 已完成 | `architecturecheck` 改用完整 AST 扫描 `internal/application` 类型声明,主动拒绝 `db.*`、`sql.Tx` 和 `*Server` 泄露;新增正反例门禁测试;现有订单 Port 通过扫描,架构门禁与中文注释门禁通过。Server 允许边、订单平台 Port 和其他应用服务仍需继续迁移,不能据此宣称目标架构完成 |
|
||||
| 2026-08-15 | P1 生命周期上下文边界切片 | 已完成 | `Account.StopContext`、`Manager.StopContext/StopAllContext` 和 `Server.Stop` 的 HTTP、后台任务及 worker 等待均受调用方 Context 限制;超时后未完成账号仍保留在管理表,避免误报已清理;`cmd/server` 使用关闭上下文停止账号;新增账号与 Server 超时回归及聚焦 race 测试通过。账号删除游离 goroutine、调度器等待和删除 fencing 仍未完成,阶段 5 继续保持“进行中” |
|
||||
@@ -129,18 +129,33 @@ func (m *Manager) Start(ctx context.Context, cookieID, cookieValue string) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop 停止单个账号。
|
||||
// Stop 停止单个账号,并兼容不需要错误返回值的旧调用方。
|
||||
func (m *Manager) Stop(cookieID string) {
|
||||
_ = m.StopContext(context.Background(), cookieID)
|
||||
}
|
||||
|
||||
// StopContext 在 ctx 约束内停止单个账号;超时后保留运行实例记录,避免误报已清理。
|
||||
func (m *Manager) StopContext(ctx context.Context, cookieID string) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
m.mu.Lock()
|
||||
// ma、ok 保存ma、ok,供当前处理流程使用
|
||||
ma, ok := m.accounts[cookieID]
|
||||
m.mu.Unlock()
|
||||
if !ok {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
// err 表示账号运行时停止失败或停止等待超时。
|
||||
if err := ma.acc.StopContext(ctx); err != nil {
|
||||
return fmt.Errorf("停止账号 %s 失败: %w", cookieID, err)
|
||||
}
|
||||
ma.acc.Stop()
|
||||
ma.cancel()
|
||||
<-ma.done
|
||||
select {
|
||||
case <-ma.done:
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("等待账号 %s 运行协程退出失败: %w", cookieID, ctx.Err())
|
||||
}
|
||||
m.mu.Lock()
|
||||
if // current 保存current,供当前处理流程使用
|
||||
current := m.accounts[cookieID]; current == ma {
|
||||
@@ -148,6 +163,7 @@ func (m *Manager) Stop(cookieID string) {
|
||||
}
|
||||
m.mu.Unlock()
|
||||
m.logger.Info("账号已停止", "account", cookieID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetInstance 跨层获取账号运行时的消息发送句柄(供 HTTP 手动发货等操作)。
|
||||
@@ -218,10 +234,18 @@ func (m *Manager) Restart(ctx context.Context, cookieID string) error {
|
||||
return m.Start(ctx, cookieID, cookieValue)
|
||||
}
|
||||
|
||||
// StopAll 停止所有运行中的账号,用于进程优雅退出。
|
||||
// StopAll 停止所有运行中的账号,用于进程优雅退出,并兼容旧调用方。
|
||||
// 先在锁内收集 cookieID 列表再解锁逐个停,避免持锁等待 goroutine 退出。
|
||||
// StopAll 停止All。
|
||||
func (m *Manager) StopAll() {
|
||||
_ = m.StopAllContext(context.Background())
|
||||
}
|
||||
|
||||
// StopAllContext 在同一个关闭上下文内停止所有账号,遇到超时立即返回并保留未完成实例。
|
||||
func (m *Manager) StopAllContext(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
m.mu.Lock()
|
||||
// ids 保存ids,供当前处理流程使用
|
||||
ids := make([]string, 0, len(m.accounts))
|
||||
@@ -232,6 +256,10 @@ func (m *Manager) StopAll() {
|
||||
m.mu.Unlock()
|
||||
// id 表示当前遍历过程中的标识
|
||||
for _, id := range ids {
|
||||
m.Stop(id)
|
||||
// err 表示当前账号停止失败或关闭上下文已到期。
|
||||
if err := m.StopContext(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -644,12 +644,20 @@ func (a *Account) clearConnectionToken(ctx context.Context) {
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
|
||||
// Stop 优雅停止。
|
||||
// Stop 优雅停止并兼容不需要错误返回值的旧调用方。
|
||||
func (a *Account) Stop() {
|
||||
_ = a.StopContext(context.Background())
|
||||
}
|
||||
|
||||
// StopContext 在 ctx 约束内停止账号,并等待已登记任务完成。
|
||||
func (a *Account) StopContext(ctx context.Context) error {
|
||||
// cancel 是当前 Run 上下文的取消函数;shouldStop 表示当前调用是否负责首次清理。
|
||||
cancel, shouldStop := a.lifecycle.stop()
|
||||
cancel, shouldStop, err := a.lifecycle.stopContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !shouldStop {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
defer a.lifecycle.finishStop()
|
||||
a.setRuntimeState(RuntimeStopped, "账号服务已停止")
|
||||
@@ -659,9 +667,14 @@ func (a *Account) Stop() {
|
||||
// 取消所有防抖定时器;回调任务仍由 lifecycle 统一等待。
|
||||
a.stop()
|
||||
|
||||
if !a.lifecycle.wait(10 * time.Second) {
|
||||
if !a.lifecycle.waitContext(ctx) {
|
||||
a.logger.Warn("等待账号业务任务退出超时")
|
||||
if ctx == nil || ctx.Err() == nil {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// beginTask 负责begin任务相关处理。
|
||||
|
||||
@@ -39,15 +39,29 @@ func (l *accountLifecycle) start(ctx context.Context, cancel context.CancelFunc)
|
||||
|
||||
// stop 原子地禁止新任务并取出运行上下文取消函数。
|
||||
func (l *accountLifecycle) stop() (context.CancelFunc, bool) {
|
||||
// cancel、first 分别表示运行上下文取消函数和是否由本次调用负责首次停止。
|
||||
cancel, first, _ := l.stopContext(context.Background())
|
||||
return cancel, first
|
||||
}
|
||||
|
||||
// stopContext 原子地禁止新任务并取出取消函数;并发停止调用会受 ctx 限制地等待首次清理完成。
|
||||
func (l *accountLifecycle) stopContext(ctx context.Context) (context.CancelFunc, bool, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
l.mu.Lock()
|
||||
if l.stopped {
|
||||
// done 是第一次 Stop 完成全部清理后关闭的信号。
|
||||
done := l.stopDone
|
||||
l.mu.Unlock()
|
||||
if done != nil {
|
||||
<-done
|
||||
select {
|
||||
case <-done:
|
||||
case <-ctx.Done():
|
||||
return nil, false, ctx.Err()
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
return nil, false, nil
|
||||
}
|
||||
l.stopped = true
|
||||
l.accepting = false
|
||||
@@ -55,7 +69,7 @@ func (l *accountLifecycle) stop() (context.CancelFunc, bool) {
|
||||
// cancel 是当前账号 Run 上下文的取消函数。
|
||||
cancel := l.stopFn
|
||||
l.mu.Unlock()
|
||||
return cancel, true
|
||||
return cancel, true, nil
|
||||
}
|
||||
|
||||
// finishStop 标记第一次 Stop 的清理已完成,并唤醒并发 Stop 调用者。
|
||||
@@ -94,23 +108,30 @@ func (l *accountLifecycle) finishTask() {
|
||||
|
||||
// wait 等待所有已登记业务任务结束;timeout 小于等于零表示无限等待。
|
||||
func (l *accountLifecycle) wait(timeout time.Duration) bool {
|
||||
if timeout <= 0 {
|
||||
return l.waitContext(context.Background())
|
||||
}
|
||||
// ctx、cancel 分别表示有限等待上下文和释放定时器的函数。
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
return l.waitContext(ctx)
|
||||
}
|
||||
|
||||
// waitContext 等待已登记业务任务结束,并在 ctx 到期时及时返回。
|
||||
func (l *accountLifecycle) waitContext(ctx context.Context) bool {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
// done 是所有已登记任务完成后关闭的等待信号。
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
l.taskWG.Wait()
|
||||
close(done)
|
||||
}()
|
||||
if timeout <= 0 {
|
||||
<-done
|
||||
return true
|
||||
}
|
||||
// timer 是有限等待模式使用的超时定时器。
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -55,3 +56,32 @@ func TestAccountStopWaitsForTaskAndConcurrentStop(t *testing.T) {
|
||||
t.Fatal("Stop 后不应再接受业务任务")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountStopContextBoundsTaskWait 验证停止上下文到期时不会无限等待业务任务。
|
||||
func TestAccountStopContextBoundsTaskWait(t *testing.T) {
|
||||
// account 是用于验证停止超时的测试账号 facade。
|
||||
account := New(Config{CookieID: "lifecycle-timeout", CookieStr: "unb=1"})
|
||||
// runCtx 是测试账号运行上下文;cancel 负责释放运行上下文。
|
||||
runCtx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
account.lifecycle.start(runCtx, cancel)
|
||||
// ok 表示测试业务任务是否成功登记。
|
||||
if _, ok := account.beginTask(); !ok {
|
||||
t.Fatal("业务任务应成功登记")
|
||||
}
|
||||
// stopCtx 是刻意很短的停止上下文,用于验证有界等待。
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer stopCancel()
|
||||
// started 记录停止开始时间,用于验证上下文确实限制等待时长。
|
||||
started := time.Now()
|
||||
// err 表示停止上下文到期后的返回错误。
|
||||
err := account.StopContext(stopCtx)
|
||||
if err == nil || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("StopContext error=%v, want deadline exceeded", err)
|
||||
}
|
||||
// elapsed 表示停止调用实际耗时。
|
||||
if elapsed := time.Since(started); elapsed > time.Second {
|
||||
t.Fatalf("StopContext waited too long: %s", elapsed)
|
||||
}
|
||||
account.lifecycle.finishTask()
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"testing"
|
||||
@@ -176,3 +177,36 @@ func TestServerStartStopIsIdempotentAndWaitsForWorkers(t *testing.T) {
|
||||
t.Fatalf("重复 Stop: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerStopContextBoundsWorkerWait 验证关闭上下文到期时不会无限等待后台 worker。
|
||||
func TestServerStopContextBoundsWorkerWait(t *testing.T) {
|
||||
// srv 是用于验证关闭超时的 HTTP 服务;cleanup 负责释放测试数据库。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.Addr = freeAddr(t)
|
||||
// err 表示 HTTP 服务启动失败。
|
||||
if err := srv.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
// workerDone 保持 worker 未完成,模拟不响应关闭的后台任务。
|
||||
workerDone := srv.beginWorker()
|
||||
// stopCtx 是刻意很短的关闭上下文,用于验证 Stop 的等待边界。
|
||||
stopCtx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
// started 记录停止开始时间,用于验证上下文确实限制等待时长。
|
||||
started := time.Now()
|
||||
// err 表示 worker 未完成时停止上下文到期返回的错误。
|
||||
err := srv.Stop(stopCtx)
|
||||
if err == nil || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("Stop error=%v, want deadline exceeded", err)
|
||||
}
|
||||
// elapsed 表示停止调用实际耗时。
|
||||
if elapsed := time.Since(started); elapsed > time.Second {
|
||||
t.Fatalf("Stop waited too long: %s", elapsed)
|
||||
}
|
||||
workerDone()
|
||||
// err 表示释放 worker 后第二次幂等停止的返回错误。
|
||||
if err := srv.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("second Stop: %v", err)
|
||||
}
|
||||
}
|
||||
+49
-16
@@ -545,11 +545,12 @@ func (s *Server) Stop(ctx context.Context) error {
|
||||
// httpDone 是已进入停止流程的 HTTP 监听完成信号。
|
||||
httpDone := s.httpDone
|
||||
s.lifecycleMu.Unlock()
|
||||
if httpDone != nil {
|
||||
<-httpDone
|
||||
if httpDone != nil && !waitForSignal(ctx, httpDone) {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !waitForWaitGroup(ctx, &s.backgroundWG) || !s.waitForWorkersContext(ctx) {
|
||||
return ctx.Err()
|
||||
}
|
||||
s.backgroundWG.Wait()
|
||||
s.waitForWorkers(0)
|
||||
return nil
|
||||
}
|
||||
s.stopped = true
|
||||
@@ -572,11 +573,12 @@ func (s *Server) Stop(ctx context.Context) error {
|
||||
if httpServer != nil {
|
||||
shutdownErr = httpServer.Shutdown(ctx)
|
||||
}
|
||||
if httpDone != nil {
|
||||
<-httpDone
|
||||
if httpDone != nil && !waitForSignal(ctx, httpDone) {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !waitForWaitGroup(ctx, &s.backgroundWG) || !s.waitForWorkersContext(ctx) {
|
||||
return ctx.Err()
|
||||
}
|
||||
s.backgroundWG.Wait()
|
||||
s.waitForWorkers(0)
|
||||
return shutdownErr
|
||||
}
|
||||
|
||||
@@ -651,20 +653,51 @@ func (s *Server) beginWorker() func() {
|
||||
|
||||
// waitForWorkers 负责waitForWorkers相关处理。
|
||||
func (s *Server) waitForWorkers(timeout time.Duration) {
|
||||
if timeout <= 0 {
|
||||
_ = s.waitForWorkersContext(context.Background())
|
||||
return
|
||||
}
|
||||
// ctx、cancel 分别表示有限等待上下文和释放定时器的函数。
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
_ = s.waitForWorkersContext(ctx)
|
||||
}
|
||||
|
||||
// waitForWorkersContext 等待批量 worker,并将等待限制在调用方的关闭上下文内。
|
||||
func (s *Server) waitForWorkersContext(ctx context.Context) bool {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.workerMu.Lock()
|
||||
// done 保存done,供当前处理流程使用
|
||||
done := s.workersDone
|
||||
s.workerMu.Unlock()
|
||||
if timeout <= 0 {
|
||||
<-done
|
||||
return
|
||||
}
|
||||
// timer 保存定时器,供当前处理流程使用
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-done:
|
||||
case <-timer.C:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
s.Logger.Warn("等待后台 worker 退出超时")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// waitForSignal 在关闭上下文取消或目标信号到达时返回,避免无界阻塞。
|
||||
func waitForSignal(ctx context.Context, signal <-chan struct{}) bool {
|
||||
select {
|
||||
case <-signal:
|
||||
return true
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// waitForWaitGroup 在关闭上下文取消或 WaitGroup 清空时返回,避免无界阻塞。
|
||||
func waitForWaitGroup(ctx context.Context, group *sync.WaitGroup) bool {
|
||||
// done 是 WaitGroup 清空后的完成信号。
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
group.Wait()
|
||||
close(done)
|
||||
}()
|
||||
return waitForSignal(ctx, done)
|
||||
}
|
||||
Reference in new issue
Block a user