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

93 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package svc
import (
"context"
"strings"
"bj_power_wms/ent"
"bj_power_wms/internal/backup"
"bj_power_wms/internal/config"
"bj_power_wms/internal/db"
"bj_power_wms/internal/eventlog"
"bj_power_wms/internal/mesclient"
)
type ServiceContext struct {
Config config.Config
EntClient *ent.Client
EventLog *eventlog.Writer
Mes *mesclient.Client
Backup *backup.Service
}
func NewServiceContext(c config.Config) *ServiceContext {
// 启动期密钥校验:编译期默认密钥已移除,yaml 缺失/为空则直接 panic,
// 杜绝「空 token 绕过内部接口鉴权」的攻击面(安全审计 #6/#13)。
validateWmsSecrets(c)
conf := db.DatabaseConf{
Host: c.Postgres.Host,
Port: c.Postgres.Port,
User: c.Postgres.User,
Password: c.Postgres.Password,
Dbname: c.Postgres.DBName,
}
// 目标数据库不存在则自动创建
if err := db.EnsureDB(conf); err != nil {
panic(err)
}
entClient := db.MustNewDB(conf)
// 启动时自动建表
if err := db.AutoMigrate(entClient); err != nil {
panic(err)
}
// 首次启动预置基础数据
if err := db.SeedIfEmpty(entClient); err != nil {
panic(err)
}
// MES 地址:sys_config 覆盖优先(基础设置页可改,保存即生效;2026-11-02)
mes := mesclient.New(c.Mes.BaseURL, c.Mes.Token)
if rows, err := entClient.SysConfig.Query().All(context.Background()); err == nil {
for _, r := range rows {
if r.Key == "mes.base.url" && strings.TrimSpace(r.Value) != "" {
mes.SetBaseURL(r.Value)
}
}
}
return &ServiceContext{
Config: c,
EntClient: entClient,
EventLog: eventlog.NewWriter(entClient),
Mes: mes,
// 备份/清理:attRoot 用 WMS 附件根目录;sibling 为 MES 内部接口地址与 token,
// 用于清理共享附件目录前跨库确认对端已备份(fail-closed)。
Backup: backup.New(entClient, eventlog.NewWriter(entClient), c.Attachment.RootDir),
}
}
// 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, ", "))
}
}