阶段五:收口应用构造与生命周期接口
This commit is contained in:
1 parent
e81c003601
commit
10ba79c292
7 files changed
+1089
-892
No files matched your search
@@ -16,10 +16,8 @@ import (
|
||||
)
|
||||
|
||||
func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
srv, store, cleanup := newTestServerWithChat(t)
|
||||
defer cleanup()
|
||||
service := chat.New(store)
|
||||
srv.SetChatService(service)
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
|
||||
@@ -62,10 +60,9 @@ func TestChatHistoryAndAccountTaskSettingsEndpoints(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
srv, _, cleanup := newTestServerWithChat(t)
|
||||
defer cleanup()
|
||||
service := chat.New(store)
|
||||
srv.SetChatService(service)
|
||||
service := srv.chat
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
httpServer := httptest.NewServer(handler)
|
||||
@@ -95,9 +92,8 @@ func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
srv, _, cleanup := newTestServerWithChat(t)
|
||||
defer cleanup()
|
||||
srv.SetChatService(chat.New(srv.Store))
|
||||
handler := srv.Router()
|
||||
cookie := loginHelper(t, handler)
|
||||
|
||||
|
||||
@@ -101,3 +101,59 @@ func TestPublishRecoveryLifecycleStopsBeforeWorkerWait(t *testing.T) {
|
||||
t.Fatal("批量发布恢复扫描器关闭后没有退出")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewRejectsMissingRequiredDependencies 确保 HTTP 服务构造阶段拒绝缺失核心依赖。
|
||||
func TestNewRejectsMissingRequiredDependencies(t *testing.T) {
|
||||
// err 是缺少 Store 时的构造校验错误。
|
||||
if _, err := New(nil, nil, false, "", ":0", nil, nil, nil); err == nil {
|
||||
t.Fatal("缺少 db.Store 时应返回构造错误")
|
||||
}
|
||||
// srv 是用于提供合法 Store 的测试服务;cleanup 负责释放测试数据库。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
if srv == nil {
|
||||
t.Fatal("测试服务不应为空")
|
||||
}
|
||||
// err 是缺少 Manager 时的构造校验错误。
|
||||
if _, err := New(srv.Store, nil, false, "", ":0", nil, nil, nil); err == nil {
|
||||
t.Fatal("缺少 account.Manager 时应返回构造错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServerStartStopIsIdempotentAndWaitsForWorkers 验证 Start/Stop 可重复调用且 Stop 等待 worker。
|
||||
func TestServerStartStopIsIdempotentAndWaitsForWorkers(t *testing.T) {
|
||||
// srv 是待验证幂等生命周期的 HTTP 服务;cleanup 负责释放测试资源。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
srv.Addr = freeAddr(t)
|
||||
if err := srv.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if err := srv.Start(context.Background()); err != nil {
|
||||
t.Fatalf("重复 Start: %v", err)
|
||||
}
|
||||
// workerDone 是模拟批量发布 worker 完成时调用的释放函数。
|
||||
workerDone := srv.beginWorker()
|
||||
// stopDone 是显式 Stop 完成时关闭的测试信号。
|
||||
stopDone := make(chan struct{})
|
||||
go func() {
|
||||
// 显式停止过程的错误不影响本测试对等待语义的判断。
|
||||
_ = srv.Stop(context.Background())
|
||||
close(stopDone)
|
||||
}()
|
||||
select {
|
||||
case <-stopDone:
|
||||
t.Fatal("Stop 在 worker 完成前提前返回")
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
workerDone()
|
||||
select {
|
||||
case <-stopDone:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("Stop 未在 worker 完成后返回")
|
||||
}
|
||||
// err 是重复 Stop 返回的关闭错误。
|
||||
if err := srv.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("重复 Stop: %v", err)
|
||||
}
|
||||
}
|
||||
+175
-28
@@ -6,6 +6,7 @@ package server
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -54,6 +55,9 @@ type publishBatchWorker struct {
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// ServerOption 是 Server 构造阶段应用可选依赖的配置函数。
|
||||
type ServerOption func(*Server)
|
||||
|
||||
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
|
||||
// 不再允许外部直接改字段,避免运行时被替换成 nil。
|
||||
type Server struct {
|
||||
@@ -72,14 +76,20 @@ type Server struct {
|
||||
// applications 保存统一装配的应用服务实例。
|
||||
applications *applicationServices
|
||||
|
||||
publishMu sync.Mutex
|
||||
publishCancels map[string]publishBatchWorker
|
||||
workerMu sync.Mutex
|
||||
workerCount int
|
||||
workersDone chan struct{}
|
||||
backgroundWG sync.WaitGroup
|
||||
lifecycleMu sync.RWMutex
|
||||
lifecycleCtx context.Context
|
||||
publishMu sync.Mutex
|
||||
publishCancels map[string]publishBatchWorker
|
||||
workerMu sync.Mutex
|
||||
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
|
||||
|
||||
qrMu sync.Mutex
|
||||
qrPersisted map[string]qrLoginPersistence
|
||||
@@ -91,16 +101,29 @@ type Server struct {
|
||||
initializationMu sync.Mutex
|
||||
}
|
||||
|
||||
// SetChatService installs the shared chat persistence and live event hub.
|
||||
func (s *Server) SetChatService(service *chat.Service) { s.chat = service }
|
||||
// WithChatService 注入聊天持久化与实时事件中心。
|
||||
func WithChatService(service *chat.Service) ServerOption {
|
||||
return func(server *Server) {
|
||||
// server 是当前构造流程中待注入聊天服务的 HTTP 服务实例。
|
||||
server.chat = service
|
||||
}
|
||||
}
|
||||
|
||||
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
|
||||
// adapter → manager → automation → notifier → server)。
|
||||
func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
|
||||
// New 构造并校验 HTTP 服务所需依赖。autoCenter/notifier 由调用方完成创建后注入
|
||||
// (创建顺序:adapter → manager → automation → notifier → server)。
|
||||
func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier, options ...ServerOption) (*Server, error) {
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("server 依赖 db.Store 不能为空")
|
||||
}
|
||||
if manager == nil {
|
||||
return nil, fmt.Errorf("server 依赖 account.Manager 不能为空")
|
||||
}
|
||||
if logger == nil {
|
||||
logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
|
||||
}
|
||||
// qrMgr 是二维码登录流程使用的默认会话管理器。
|
||||
qrMgr := qrlogin.NewManager(logger)
|
||||
// server 是完成依赖装配、等待应用服务初始化后的 HTTP 服务实例。
|
||||
server := &Server{
|
||||
Store: store,
|
||||
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
|
||||
@@ -121,8 +144,14 @@ func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr st
|
||||
qrOwners: make(map[string]qrLoginOwner),
|
||||
loginLimiter: newLoginFailureLimiter(),
|
||||
}
|
||||
for _, option := range options {
|
||||
// option 是当前构造调用提供的可选依赖配置。
|
||||
if option != nil {
|
||||
option(server)
|
||||
}
|
||||
}
|
||||
server.applications = newApplicationServices(server)
|
||||
return server
|
||||
return server, nil
|
||||
}
|
||||
|
||||
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
|
||||
@@ -380,12 +409,22 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// 各分组 mount*Real 方法在 handlers 文件中实现;为避免单文件过大,按业务域分文件。
|
||||
|
||||
// Run 启动 HTTP 服务(阻塞)。
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
// Start 启动 HTTP 服务及其生命周期监听。重复调用不会重复监听端口。
|
||||
func (s *Server) Start(ctx context.Context) error {
|
||||
if s == nil {
|
||||
return fmt.Errorf("server 不能为空")
|
||||
}
|
||||
// ctx 是控制 HTTP 服务及其后台任务的进程级生命周期上下文。
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.lifecycleMu.Lock()
|
||||
s.lifecycleCtx = ctx
|
||||
s.lifecycleMu.Unlock()
|
||||
srv := &http.Server{
|
||||
if s.started {
|
||||
s.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
// httpServer 是本次启动创建的标准库 HTTP 监听器。
|
||||
httpServer := &http.Server{
|
||||
Addr: s.Addr,
|
||||
Handler: s.Router(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
@@ -394,20 +433,124 @@ func (s *Server) Run(ctx context.Context) error {
|
||||
WriteTimeout: 2 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
}
|
||||
// 关闭任务由传入的服务生命周期上下文控制,并登记到统一后台生命周期。
|
||||
s.startBackgroundTask("HTTP 服务关闭", func() {
|
||||
<-ctx.Done()
|
||||
shCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
// lifecycleCtx 是 Server 内部可取消的生命周期上下文。
|
||||
// lifecycleCancel 是触发 Server 生命周期收束的取消函数。
|
||||
lifecycleCtx, lifecycleCancel := context.WithCancel(ctx)
|
||||
s.lifecycleCtx = lifecycleCtx
|
||||
s.lifecycleCancel = lifecycleCancel
|
||||
s.httpServer = httpServer
|
||||
s.httpDone = make(chan struct{})
|
||||
s.httpErr = nil
|
||||
s.started = true
|
||||
s.stopped = false
|
||||
// httpDone 是 HTTP 监听 goroutine 结束时关闭的完成信号。
|
||||
httpDone := s.httpDone
|
||||
s.lifecycleMu.Unlock()
|
||||
|
||||
// 生命周期上下文取消时触发统一 Stop;该 goroutine 不登记到后台任务组,
|
||||
// 避免 Stop 等待自身造成死锁。
|
||||
go func() {
|
||||
<-lifecycleCtx.Done()
|
||||
// stopCtx 是自动关闭 HTTP 服务时使用的有限时长上下文。
|
||||
// cancel 释放 stopCtx 的定时器资源。
|
||||
stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shCtx); err != nil {
|
||||
if err := s.Stop(stopCtx); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("HTTP 服务关闭异常", "err", err)
|
||||
}
|
||||
})
|
||||
s.Logger.Info("HTTP 服务启动", "addr", s.Addr)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
}()
|
||||
go func() {
|
||||
s.Logger.Info("HTTP 服务启动", "addr", s.Addr)
|
||||
// err 是 HTTP 监听器退出时返回的原始错误。
|
||||
err := httpServer.ListenAndServe()
|
||||
if err == http.ErrServerClosed {
|
||||
err = nil
|
||||
}
|
||||
s.lifecycleMu.Lock()
|
||||
s.httpErr = err
|
||||
s.lifecycleMu.Unlock()
|
||||
close(httpDone)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Wait 等待 HTTP 服务结束,并返回监听或关闭错误。
|
||||
func (s *Server) Wait() error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
s.lifecycleMu.RLock()
|
||||
// httpDone 是 HTTP 监听 goroutine 的完成信号。
|
||||
httpDone := s.httpDone
|
||||
s.lifecycleMu.RUnlock()
|
||||
if httpDone == nil {
|
||||
return fmt.Errorf("server 尚未启动")
|
||||
}
|
||||
<-httpDone
|
||||
s.lifecycleMu.RLock()
|
||||
// err 是监听 goroutine 记录的退出错误。
|
||||
err := s.httpErr
|
||||
s.lifecycleMu.RUnlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// Stop 幂等关闭 HTTP 服务,并等待 Server 自有后台任务和批量 worker 退出。
|
||||
func (s *Server) Stop(ctx context.Context) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
// ctx 是限制 HTTP 优雅关闭等待时间的上下文。
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.lifecycleMu.Lock()
|
||||
if !s.started {
|
||||
s.lifecycleMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if s.stopped {
|
||||
// httpDone 是已进入停止流程的 HTTP 监听完成信号。
|
||||
httpDone := s.httpDone
|
||||
s.lifecycleMu.Unlock()
|
||||
if httpDone != nil {
|
||||
<-httpDone
|
||||
}
|
||||
s.backgroundWG.Wait()
|
||||
s.waitForWorkers(0)
|
||||
return nil
|
||||
}
|
||||
s.stopped = true
|
||||
// httpServer 是需要执行优雅关闭的标准库 HTTP 服务。
|
||||
// httpDone 是监听 goroutine 退出的完成信号。
|
||||
// lifecycleCancel 是取消 Server 内部生命周期上下文的函数。
|
||||
httpServer := s.httpServer
|
||||
httpDone := s.httpDone
|
||||
lifecycleCancel := s.lifecycleCancel
|
||||
s.lifecycleMu.Unlock()
|
||||
|
||||
if lifecycleCancel != nil {
|
||||
lifecycleCancel()
|
||||
}
|
||||
// shutdownErr 是 HTTP 优雅关闭返回的错误;后台等待错误由 worker 自身记录。
|
||||
var shutdownErr error
|
||||
if httpServer != nil {
|
||||
shutdownErr = httpServer.Shutdown(ctx)
|
||||
}
|
||||
if httpDone != nil {
|
||||
<-httpDone
|
||||
}
|
||||
s.backgroundWG.Wait()
|
||||
s.waitForWorkers(0)
|
||||
return shutdownErr
|
||||
}
|
||||
|
||||
// Run 启动并阻塞等待 HTTP 服务结束,兼容旧的进程入口调用方式。
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
// err 是显式启动阶段返回的构造或监听准备错误。
|
||||
if err := s.Start(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return s.Wait()
|
||||
}
|
||||
|
||||
// WaitForBackground 等待恢复扫描器先退出,再等待其已经登记的批量 worker。
|
||||
@@ -469,6 +612,10 @@ func (s *Server) waitForWorkers(timeout time.Duration) {
|
||||
s.workerMu.Lock()
|
||||
done := s.workersDone
|
||||
s.workerMu.Unlock()
|
||||
if timeout <= 0 {
|
||||
<-done
|
||||
return
|
||||
}
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/account"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/chat"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -24,6 +25,7 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// store 是当前测试数据库的 repository 聚合入口。
|
||||
store := db.NewStore(d, db.DialectSQLite)
|
||||
// 管理员和测试账号已经在共享 SQLite 模板中预置,避免每个测试重复执行 bcrypt。
|
||||
// 一个账号的 cookie 夹具由模板初始化阶段写入当前测试副本。
|
||||
@@ -31,8 +33,13 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
|
||||
// 当前测试副本保持模板中的固定账号数据不变。
|
||||
// 具体测试可以在自己的请求流程中修改这些副本数据。
|
||||
|
||||
// mgr 是使用空处理器的测试账号管理器。
|
||||
mgr := account.NewManager(store, noopHandler{}, nil)
|
||||
srv := New(store, mgr, false, "", ":0", nil, nil, nil)
|
||||
// srv 是未启用聊天服务的基础测试 HTTP 服务。
|
||||
srv, err := New(store, mgr, false, "", ":0", nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
mtopClient := mtop.NewClient()
|
||||
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
@@ -51,16 +58,34 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) { // newTestServer
|
||||
}
|
||||
}
|
||||
|
||||
// newTestServerWithChat 构造启用通信应用服务的测试服务器,供聊天 REST/WebSocket 测试复用。
|
||||
func newTestServerWithChat(t *testing.T) (*Server, *db.Store, func()) {
|
||||
// srv、store 和 cleanup 分别是基础 HTTP 服务、数据库聚合和资源释放函数。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
// chatService 是仅供聊天测试使用的通信应用服务实例。
|
||||
chatService := chat.New(store)
|
||||
// srv.chat 在测试构造阶段一次性注入通信服务,模拟构造 option 的效果。
|
||||
srv.chat = chatService
|
||||
return srv, store, cleanup
|
||||
}
|
||||
|
||||
func newUninitializedTestServer(t *testing.T) (*Server, *db.Store, func()) {
|
||||
t.Helper()
|
||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
||||
// d 是当前未初始化测试使用的数据库连接;err 是打开错误。
|
||||
d, _, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// store 是未初始化测试数据库的 repository 聚合入口。
|
||||
store := db.NewStore(d, db.DialectSQLite)
|
||||
// mgr 是未初始化测试使用的空处理器账号管理器。
|
||||
mgr := account.NewManager(store, noopHandler{}, nil)
|
||||
srv := New(store, mgr, false, "", ":0", nil, nil, nil)
|
||||
// srv 是未初始化测试使用的 HTTP 服务实例。
|
||||
srv, err := New(store, mgr, false, "", ":0", nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
return srv, store, func() {
|
||||
mgr.StopAll()
|
||||
_ = d.Close()
|
||||
|
||||
Reference in new issue
Block a user