Files
bj_power/bj_power_wms/internal/svc/service_context.go
T

80 lines
2.0 KiB
Go
Raw Normal View History

2026-08-28 15:06:01 +08:00
package svc
import (
"strings"
2026-08-28 15:06:01 +08:00
"bj_power_wms/ent"
"bj_power_wms/internal/agv"
2026-08-28 15:06:01 +08:00
"bj_power_wms/internal/config"
"bj_power_wms/internal/db"
"bj_power_wms/internal/eventlog"
"bj_power_wms/internal/mesclient"
2026-08-28 15:06:01 +08:00
)
type ServiceContext struct {
Config config.Config
EntClient *ent.Client
EventLog *eventlog.Writer
Agv agv.Client
Mes *mesclient.Client
2026-08-28 15:06:01 +08:00
}
func NewServiceContext(c config.Config) *ServiceContext {
// 启动期密钥校验:编译期默认密钥已移除,yaml 缺失/为空则直接 panic,
// 杜绝「空 token 绕过内部接口鉴权」的攻击面(安全审计 #6/#13)。
validateWmsSecrets(c)
2026-08-29 15:30:25 +08:00
conf := db.DatabaseConf{
2026-08-28 15:06:01 +08:00
Host: c.Postgres.Host,
Port: c.Postgres.Port,
User: c.Postgres.User,
Password: c.Postgres.Password,
Dbname: c.Postgres.DBName,
2026-08-29 15:30:25 +08:00
}
// 目标数据库不存在则自动创建
if err := db.EnsureDB(conf); err != nil {
panic(err)
}
entClient := db.MustNewDB(conf)
2026-08-28 15:06:01 +08:00
// 启动时自动建表
if err := db.AutoMigrate(entClient); err != nil {
panic(err)
}
// 首次启动预置基础数据
if err := db.SeedIfEmpty(entClient); err != nil {
panic(err)
}
return &ServiceContext{
Config: c,
EntClient: entClient,
EventLog: eventlog.NewWriter(entClient),
Agv: agv.New(c.Agv),
Mes: mesclient.New(c.Mes.BaseURL, c.Mes.Token),
2026-08-28 15:06:01 +08:00
}
}
// validateWmsSecrets 启动期校验必要密钥非空(编译期默认密钥已移除)。
func validateWmsSecrets(c config.Config) {
missing := make([]string, 0, 4)
if strings.TrimSpace(c.Auth.AccessSecret) == "" {
missing = append(missing, "Auth.AccessSecret")
}
if strings.TrimSpace(c.Internal.Token) == "" {
missing = append(missing, "Internal.Token")
}
if strings.TrimSpace(c.Mes.Token) == "" {
missing = append(missing, "Mes.Token")
}
if strings.TrimSpace(c.Cli.AdminPassword) == "" {
missing = append(missing, "Cli.AdminPassword")
}
if len(missing) > 0 {
panic("配置缺失必要密钥(已禁止编译期默认密钥,必须在 etc/*.yaml 中显式配置):" + strings.Join(missing, ", "))
}
}