阶段4:推进启动稳定性与组合根注入

This commit is contained in:
Christ committed 2026-08-18 19:51:38 +08:00
1 parent 9da450d940
commit d2d8e02a39
36 files changed
+830 -168

No files matched your search

+112 -18
View File
@@ -12,6 +12,7 @@ import (
"fmt"
"io"
"log/slog"
"net"
"os"
"os/signal"
"path/filepath"
@@ -377,7 +378,11 @@ func openServerInfrastructure(ctx context.Context, startup serverStartupConfig,
}
// initialized 表示系统是否已有管理员;查询失败按未初始化提示而不阻断启动。
if initialized, _ := store.Users.IsSystemInitialized(ctx); !initialized {
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
if isNonLoopbackListenAddress(opts.addr) {
logger.Warn("系统尚未初始化且 HTTP 监听可被远程访问;首个访问初始化页面的客户端可创建管理员,请由部署者通过网络隔离或 -init-admin 承担该风险", "addr", opts.addr)
} else {
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
}
}
return serverInfrastructure{database: database, store: store, logger: logger, logWriter: logWriter, closeLog: closeLog}, nil
}
@@ -517,13 +522,28 @@ func buildServerRuntime(opts serverOptions, infrastructure serverInfrastructure)
}
// authentication 负责 HTTP 会话认证;Secure 策略由启动参数控制。
authentication := &auth.Service{Store: infrastructure.store, Logger: infrastructure.logger, Secure: opts.secure}
// httpServer 是完成所有窄依赖注入后的 HTTP 服务实例。
httpServer, serverErr := server.New(authentication, mgr, opts.webDir, opts.addr, infrastructure.logger, autoCenter, notifier, server.WithChatService(chatService), server.WithChatDependencies(chatDependencies), server.WithDatabaseHealth(databaseHealth), server.WithOrderReconciliationRecovery(orderReconciliationRecovery), server.WithOrderDependencies(orderDependencies), server.WithAccountDependencies(accountDependencies), server.WithItemDependencies(itemDependencies), server.WithAutomationDependencies(automationDependencies), server.WithTransportApplicationServices(transportApplications), server.WithPlatformDependencies(platformDependencies), server.WithApplicationLifecycle(lifecycleCoordinator))
// compositionServer 仅在迁移期间复用旧应用服务装配逻辑;它不绑定端口、不启动 worker,也不作为 HTTP Server 运行。
compositionServer, compositionErr := server.New(authentication, mgr, opts.webDir, opts.addr, infrastructure.logger, autoCenter, notifier, server.WithChatService(chatService), server.WithChatDependencies(chatDependencies), server.WithDatabaseHealth(databaseHealth), server.WithOrderReconciliationRecovery(orderReconciliationRecovery), server.WithOrderDependencies(orderDependencies), server.WithAccountDependencies(accountDependencies), server.WithItemDependencies(itemDependencies), server.WithAutomationDependencies(automationDependencies), server.WithTransportApplicationServices(transportApplications), server.WithPlatformDependencies(platformDependencies), server.WithApplicationLifecycle(lifecycleCoordinator))
if compositionErr != nil {
return serverRuntime{}, fmt.Errorf("构造应用服务集合失败: %w", compositionErr)
}
// applications 是组合期一次性构造的只读应用服务集合,HTTP Server 不得在自身构造期间补建业务服务。
applications := compositionServer.ApplicationServices()
// httpServer 是只接收完整依赖快照的 HTTP transport 实例。
httpServer, serverErr := server.NewWithDependencies(server.Dependencies{
Auth: authentication, Manager: mgr, WebDir: opts.webDir, Addr: opts.addr, Logger: infrastructure.logger,
Automation: autoCenter, Notifier: notifier, Chat: chatService, OrderDependencies: orderDependencies,
AccountDependencies: accountDependencies, ItemDependencies: itemDependencies, ChatDependencies: chatDependencies,
AutomationDependencies: automationDependencies, TransportApplications: transportApplications,
PlatformDependencies: platformDependencies, DatabaseHealth: databaseHealth,
OrderReconciliationRecovery: orderReconciliationRecovery, Applications: applications,
ApplicationLifecycle: lifecycleCoordinator,
})
if serverErr != nil {
return serverRuntime{}, fmt.Errorf("构造 HTTP 服务失败: %w", serverErr)
}
// component 表示 HTTP 服务暴露给进程装配层的应用 worker 生命周期组件。
for _, component := range httpServer.ApplicationLifecycleComponents() {
// component 表示应用服务集合交给进程组合根登记的 worker 生命周期组件。
for _, component := range applications.LifecycleComponents() {
// err 表示当前 HTTP 应用 worker 生命周期组件登记失败。
if err := lifecycleCoordinator.Add(component); err != nil {
return serverRuntime{}, fmt.Errorf("登记应用 worker 生命周期组件 %q 失败: %w", component.Name, err)
@@ -534,9 +554,16 @@ func buildServerRuntime(opts serverOptions, infrastructure serverInfrastructure)
// runServerLifecycle 启动应用组件和 HTTP 监听,等待退出后执行有限时长的 HTTP 与组件逆序关闭。
func runServerLifecycle(ctx context.Context, runtime serverRuntime, logger *slog.Logger) error {
// bindErr 是应用 worker 启动前同步占用 HTTP 端口的错误,端口冲突不得触发任何业务副作用。
if bindErr := runtime.httpServer.Bind(); bindErr != nil {
return fmt.Errorf("绑定 HTTP 服务失败: %w", bindErr)
}
// err 表示应用组件按依赖顺序启动失败。
if err := runtime.lifecycleCoordinator.Start(ctx); err != nil {
return fmt.Errorf("启动应用生命周期失败: %w", err)
// stopCtx、stopCancel 关闭已绑定但尚未 Serve 的监听器,避免启动失败后端口泄漏。
stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer stopCancel()
return errors.Join(fmt.Errorf("启动应用生命周期失败: %w", err), runtime.httpServer.Stop(stopCtx))
}
// err 表示 HTTP 服务监听启动失败;失败后必须关闭已启动的应用组件。
if err := runtime.httpServer.Start(ctx); err != nil {
@@ -692,16 +719,11 @@ func loadOrCreateDataKey(path string) (string, error) {
if path == "" {
return "", fmt.Errorf("data key 文件路径不能为空")
}
// raw、err 分别是既有密钥文件的内容及读取失败原因。
if raw, err := os.ReadFile(path); err == nil {
// key 是去除首尾空白后的现有数据加密主密钥,禁止记录到日志。
key := strings.TrimSpace(string(raw))
if key == "" {
return "", fmt.Errorf("data key 文件为空: %s", path)
}
// key、readErr 分别是已存在密钥文件的内容及读取错误;已有文件永远优先于本次生成。
if key, readErr := readDataKey(path); readErr == nil {
return key, nil
} else if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("读取 data key 文件失败: %w", err)
} else if !errors.Is(readErr, os.ErrNotExist) {
return "", readErr
}
// err 表示创建数据加密主密钥父目录失败。
@@ -716,13 +738,85 @@ func loadOrCreateDataKey(path string) (string, error) {
}
// key 是待写入权限为 0600 文件的数据加密主密钥,禁止记录到日志。
key := base64.RawStdEncoding.EncodeToString(raw)
// err 表示原子性不足的首次密钥文件写入失败,调用方必须终止启动。
if err := os.WriteFile(path, []byte(key+"\n"), 0o600); err != nil {
return "", fmt.Errorf("写入 data key 文件失败: %w", err)
// file、createErr 分别是以排他方式创建的密钥文件及创建错误;同一时刻只能有一个进程成为写入者。
file, createErr := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if errors.Is(createErr, os.ErrExist) {
return waitForDataKey(path)
}
if createErr != nil {
return "", fmt.Errorf("创建 data key 文件失败: %w", createErr)
}
// writeErr 表示新密钥写入错误;失败时删除当前进程独占创建的文件,避免遗留不可恢复的空文件。
if _, writeErr := io.WriteString(file, key+"\n"); writeErr != nil {
_ = file.Close()
_ = os.Remove(path)
return "", fmt.Errorf("写入 data key 文件失败: %w", writeErr)
}
// syncErr 表示密钥内容持久化到文件系统前发生的同步错误;不能在未落盘时继续启动。
if syncErr := file.Sync(); syncErr != nil {
_ = file.Close()
_ = os.Remove(path)
return "", fmt.Errorf("同步 data key 文件失败: %w", syncErr)
}
// closeErr 表示关闭新建密钥文件时产生的错误;关闭失败同样视为密钥未可靠创建。
if closeErr := file.Close(); closeErr != nil {
_ = os.Remove(path)
return "", fmt.Errorf("关闭 data key 文件失败: %w", closeErr)
}
return key, nil
}
// readDataKey 读取并校验已有的数据加密主密钥;返回错误时绝不输出密钥内容。
func readDataKey(path string) (string, error) {
// raw、readErr 分别是文件原始内容及读取失败原因。
raw, readErr := os.ReadFile(path)
if readErr != nil {
if errors.Is(readErr, os.ErrNotExist) {
return "", os.ErrNotExist
}
return "", fmt.Errorf("读取 data key 文件失败: %w", readErr)
}
// key 是去除文件末尾换行后的数据加密主密钥,禁止记录到日志。
key := strings.TrimSpace(string(raw))
if key == "" {
return "", fmt.Errorf("data key 文件为空: %s", path)
}
return key, nil
}
// waitForDataKey 等待并读取由并发启动进程创建的密钥文件,不会生成或覆盖另一把密钥。
func waitForDataKey(path string) (string, error) {
// attempt 是读取竞争方写入结果的有限尝试次数,避免空文件永久阻塞启动。
for attempt := 0; attempt < 20; attempt++ {
// key、readErr 分别是当前尝试读到的密钥及读取错误。
key, readErr := readDataKey(path)
if readErr == nil {
return key, nil
}
if !strings.Contains(readErr.Error(), "文件为空") && !errors.Is(readErr, os.ErrNotExist) {
return "", readErr
}
time.Sleep(10 * time.Millisecond)
}
return "", fmt.Errorf("等待并发创建 data key 文件超时: %s", path)
}
// isNonLoopbackListenAddress 判断监听地址是否可能接收本机以外的连接;空 host 与通配地址均视为远程可达。
func isNonLoopbackListenAddress(address string) bool {
// host、port、splitErr 分别是监听地址的主机部分、端口部分和解析错误。
host, _, splitErr := net.SplitHostPort(strings.TrimSpace(address))
if splitErr != nil {
return true
}
host = strings.TrimSpace(host)
if host == "" || strings.EqualFold(host, "localhost") {
return host == ""
}
// ip 是可直接判断 loopback 属性的 IP 地址;主机名按远程可达处理,避免漏报部署风险。
ip := net.ParseIP(host)
return ip == nil || !ip.IsLoopback()
}
// ensureAdmin 封装ensureAdmin业务协调。
func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error {
if password == "" {
+108
View File
@@ -9,6 +9,7 @@ import (
"os"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
@@ -231,6 +232,113 @@ func TestLoadOrCreateDataKeyPersists(t *testing.T) {
}
}
// TestLoadOrCreateDataKeyConcurrentCreation 验证并发首次启动只能观测到同一把持久化主密钥。
func TestLoadOrCreateDataKeyConcurrentCreation(t *testing.T) {
// path 是所有并发启动模拟共享的、尚不存在的数据密钥文件路径。
path := filepath.Join(t.TempDir(), "concurrent-data-key")
// workerCount 是并发调用数量,足以覆盖多个 goroutine 同时通过不存在检查的竞争窗口。
const workerCount = 32
// start 统一放行所有调用,避免调度器提前串行化创建过程。
start := make(chan struct{})
// keys 收集每个调用成功读取或创建到的密钥,禁止将密钥写入测试失败输出。
keys := make(chan string, workerCount)
// failures 收集并发创建过程中发生的错误,以便主 goroutine 统一断言。
failures := make(chan error, workerCount)
// workers 等待全部并发调用结束,避免测试提前读取未完成文件。
var workers sync.WaitGroup
// workerIndex 为每个并发调用分配稳定的启动序号,循环体本身不依赖其数值。
for workerIndex := 0; workerIndex < workerCount; workerIndex++ {
workers.Add(1)
go func() {
defer workers.Done()
<-start
// key、keyErr 分别是当前调用读取或创建到的主密钥及错误。
key, keyErr := loadOrCreateDataKey(path)
if keyErr != nil {
failures <- keyErr
return
}
keys <- key
}()
}
close(start)
workers.Wait()
close(keys)
close(failures)
// failure 是任一并发创建协程返回的错误,仅用于统一失败报告。
for failure := range failures {
t.Fatalf("并发创建 data key 失败: %v", failure)
}
// firstKey 是所有并发调用必须一致的首个密钥值,仅用于相等性比较。
var firstKey string
// key 是单个并发调用观测到的密钥,仅参与同值比较且不输出明文。
for key := range keys {
if firstKey == "" {
firstKey = key
continue
}
if key != firstKey {
t.Fatal("并发创建返回了不一致的数据密钥")
}
}
if firstKey == "" {
t.Fatal("并发创建没有返回数据密钥")
}
// persistedKey、readErr 分别是最终文件中的密钥及读取错误。
persistedKey, readErr := readDataKey(path)
if readErr != nil {
t.Fatalf("读取并发创建后的 data key 失败: %v", readErr)
}
if persistedKey != firstKey {
t.Fatal("持久化 data key 与并发调用返回值不一致")
}
}
// TestLoadOrCreateDataKeyRejectsEmptyExistingFile 验证遗留空密钥文件不会被静默覆盖或替换。
func TestLoadOrCreateDataKeyRejectsEmptyExistingFile(t *testing.T) {
// path 是预先创建为空内容的密钥文件路径,模拟异常进程留下的不完整状态。
path := filepath.Join(t.TempDir(), "empty-data-key")
// writeErr 是构造异常空密钥文件时的写入错误。
if writeErr := os.WriteFile(path, nil, 0o600); writeErr != nil {
t.Fatalf("创建空 data key 文件失败: %v", writeErr)
}
// keyErr 是读取空密钥文件时必须返回的阻断错误。
_, keyErr := loadOrCreateDataKey(path)
if keyErr == nil {
t.Fatal("空 data key 文件不应被静默替换")
}
}
// TestIsNonLoopbackListenAddress 验证远程可达监听地址会触发未初始化部署风险告警。
func TestIsNonLoopbackListenAddress(t *testing.T) {
// cases 覆盖 loopback、通配地址和主机名监听的风险分类。
cases := []struct {
// name 是当前地址分类场景的稳定测试名称。
name string
// address 是传给服务端监听器的地址字符串。
address string
// want 是该地址是否可能接收远程客户端连接。
want bool
}{
{name: "loopback IPv4", address: "127.0.0.1:59188", want: false},
{name: "loopback IPv6", address: "[::1]:59188", want: false},
{name: "all interfaces", address: ":59188", want: true},
{name: "public interface", address: "0.0.0.0:59188", want: true},
{name: "hostname", address: "host.example:59188", want: true},
}
// testCase 是当前待执行的监听地址分类。
for _, testCase := range cases {
// testCase 是当前待执行的监听地址分类。
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
// got 是地址是否可能接受远程连接的实际判断结果。
if got := isNonLoopbackListenAddress(testCase.address); got != testCase.want {
t.Fatalf("地址 %q 远程可达=%t,want %t", testCase.address, got, testCase.want)
}
})
}
}
// TestOpenServerLogWriterUsesConfiguredDirectory 封装TestOpenServerLogWriterUsesConfiguredDirectory业务协调。
func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
// logDir 用于本次流程后续判断的logDir