feat(issue#3 方案B): 系统配置页(/system/config KV 管理)+ SrcID 两级回退链(账号 ext_code 优先→系统默认 cmpp.default_ext_code)
This commit is contained in:
@@ -32,6 +32,7 @@ import (
|
||||
"go-sms/internal/service/router"
|
||||
"go-sms/internal/service/send"
|
||||
"go-sms/internal/service/settle"
|
||||
"go-sms/internal/service/sysconfig"
|
||||
"go-sms/internal/service/template"
|
||||
)
|
||||
|
||||
@@ -76,6 +77,9 @@ type Deps struct {
|
||||
// Archive S4·D3:明细冷热归档(/record/history 冷查走 ClickHouse;
|
||||
// nil=不注册 history 端点,前端 404 优于半可用)。
|
||||
Archive *archive.Service
|
||||
// SysConfig Issue#3 方案B:系统参数配置(/system/config GET/PUT;
|
||||
// access 系统默认接入码回退的数据源;nil=不注册)。
|
||||
SysConfig *sysconfig.Service
|
||||
}
|
||||
|
||||
// Register 注册 v1 路由组。
|
||||
@@ -187,6 +191,10 @@ func Register(rg *gin.RouterGroup, deps Deps) {
|
||||
if deps.ErrorCode != nil {
|
||||
registerErrorCodeRoutes(protected, deps.Perm, deps.ErrorCode)
|
||||
}
|
||||
// Issue#3 方案B:系统参数配置(system_config KV 管理页数据源)。
|
||||
if deps.SysConfig != nil {
|
||||
registerSysConfigRoutes(protected, deps.Perm, deps.SysConfig)
|
||||
}
|
||||
// Day 53(runbook §6.4/§6.2 P0):前端错误上报(POST public/GET 排障)+
|
||||
// Alertmanager webhook 接收(AM 推送→日志留痕,告警通道验收抓手)。
|
||||
registerFeErrorRoutes(rg, protected, deps.DB, deps.Perm)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// sysconfig_handler.go Issue#3 方案B:系统参数配置端点(system_config KV 表)。
|
||||
// - GET /system/config 全量列表(登录即可,管理页数据源)
|
||||
// - PUT /system/config 新增/更新(system:write——admin 直通;UPSERT+缓存即刻失效)
|
||||
// 已知键:cmpp.default_ext_code(系统默认接入码前缀,账号 ext_code 空时回退,
|
||||
// 受理热路径 30s 读缓存)/uplink.blacklist.keywords(上行拉黑词表,uplink 域
|
||||
// 自刷新 60s 生效)。表结构无白名单约束,新键=新能力按需扩展。
|
||||
package v1
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-sms/internal/middleware"
|
||||
"go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/pkg/response"
|
||||
"go-sms/internal/service/sysconfig"
|
||||
)
|
||||
|
||||
type sysConfigHandler struct{ svc *sysconfig.Service }
|
||||
|
||||
func registerSysConfigRoutes(protected *gin.RouterGroup, perm middleware.PermissionChecker, svc *sysconfig.Service) {
|
||||
h := &sysConfigHandler{svc: svc}
|
||||
protected.GET("/system/config", h.list)
|
||||
protected.PUT("/system/config", middleware.RequirePermission(perm, "system", "write"), h.set)
|
||||
}
|
||||
|
||||
// list GET /system/config(全量,cfg_key 升序)。
|
||||
func (h *sysConfigHandler) list(c *gin.Context) {
|
||||
rows, err := h.svc.List(c.Request.Context())
|
||||
if err != nil {
|
||||
response.Error(c, errors.InternalError)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{"list": rows})
|
||||
}
|
||||
|
||||
// sysConfigReq PUT 请求体。
|
||||
type sysConfigReq struct {
|
||||
CfgKey string `json:"cfg_key" binding:"required"`
|
||||
CfgValue string `json:"cfg_value"` // 空串=合法值(清空语义)
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
// set PUT /system/config(cfg_key 唯一 UPSERT;审计由 AuditTrail 写方法自动留痕)。
|
||||
func (h *sysConfigHandler) set(c *gin.Context) {
|
||||
var req sysConfigReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.ErrorWithMsg(c, errors.InvalidParam, "参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
claims := operatorClaims(c)
|
||||
operator := ""
|
||||
if claims != nil {
|
||||
operator = claims.Username
|
||||
}
|
||||
row, err := h.svc.Set(c.Request.Context(), req.CfgKey, req.CfgValue, req.Remark, operator)
|
||||
if err != nil {
|
||||
if bizErr, ok := err.(*errors.Error); ok {
|
||||
response.Error(c, bizErr)
|
||||
return
|
||||
}
|
||||
c.Set("biz_error", err.Error())
|
||||
response.Error(c, errors.InternalError)
|
||||
return
|
||||
}
|
||||
response.Success(c, row)
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"go-sms/internal/service/openapi"
|
||||
"go-sms/internal/service/report"
|
||||
"go-sms/internal/service/send"
|
||||
"go-sms/internal/service/sysconfig"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -80,8 +81,19 @@ type Service struct {
|
||||
// 长短信片聚合器(批次 2278141 修复):入向 UDH 拼接多片按组聚合,
|
||||
// 到齐合并为一条逻辑 task;超时逐片退化直发。见 longsms.go。
|
||||
grouper *longSmsGrouper
|
||||
// sysCfg Issue#3 方案B:系统配置源(账号 ext_code 空时回退系统默认接入码
|
||||
// cmpp.default_ext_code);nil=无系统回退(行为不变,测试/降级场景)。
|
||||
sysCfg SystemConfigGetter
|
||||
}
|
||||
|
||||
// SystemConfigGetter 系统配置读取接口(由 sysconfig.Service 实现;解耦包依赖)。
|
||||
type SystemConfigGetter interface {
|
||||
Get(ctx context.Context, key string) string
|
||||
}
|
||||
|
||||
// SetSystemConfig 注入系统配置源(可选;gateway 装配调用,nil=无系统回退)。
|
||||
func (s *Service) SetSystemConfig(g SystemConfigGetter) { s.sysCfg = g }
|
||||
|
||||
// accountCacheEntry 账号缓存条目(u/cfg nil=查无,负缓存防穿透)。
|
||||
type accountCacheEntry struct {
|
||||
u, cfg any // *entity.AccountUser | *entity.AccountConfig | nil
|
||||
@@ -271,31 +283,47 @@ func (s *Service) Submit(sourceAddr, srcID string, dest []string,
|
||||
defer func() { submitStats.record(time.Since(t0)) }()
|
||||
ctx := context.Background()
|
||||
if udh != nil && udh.Total > 1 && len(dest) == 1 {
|
||||
cfg, result := s.precheck(ctx, sourceAddr, srcID)
|
||||
cfg, ext, result := s.precheck(ctx, sourceAddr, srcID)
|
||||
if cfg == nil {
|
||||
return 0, result
|
||||
}
|
||||
return s.grouper.submitFragment(s.api, cfg, sourceAddr, srcID,
|
||||
return s.grouper.submitFragment(s.api, cfg, ext, sourceAddr, srcID,
|
||||
dest[0], content, udh, msgFmt == cmpp.MsgFmtUCS2)
|
||||
}
|
||||
return s.submitDirect(ctx, sourceAddr, srcID, dest, content, msgFmt)
|
||||
}
|
||||
|
||||
// precheck 账号加载+通道号前缀校验(cfg=nil 时返回值为 CMPP 拒绝码)。
|
||||
// precheck 账号加载+通道号校验(cfg=nil 时返回值为 CMPP 拒绝码)。
|
||||
// 直发与长短信聚合共用(聚合组以首片账号快照为准)。
|
||||
func (s *Service) precheck(ctx context.Context, sourceAddr, srcID string) (*entity.AccountConfig, byte) {
|
||||
// Issue#3 方案B:返回生效校验前缀 ext——账号 ext_code 优先,空则回退系统默认
|
||||
// cmpp.default_ext_code(账号级定制>系统级统一;两层均空=不校验)。
|
||||
func (s *Service) precheck(ctx context.Context, sourceAddr, srcID string) (*entity.AccountConfig, string, byte) {
|
||||
_, cfg := s.loadAccount(ctx, sourceAddr)
|
||||
if cfg == nil {
|
||||
return nil, cmpp.SubmitRejected
|
||||
return nil, "", cmpp.SubmitRejected
|
||||
}
|
||||
// 通道号前缀:账号 ext_code 非空时 SrcID 必须以其为前缀(UT:0012 语义)。
|
||||
if cfg.ExtCode != "" && !strings.HasPrefix(srcID, cfg.ExtCode) {
|
||||
ext := s.effectiveExtCode(ctx, cfg)
|
||||
// 通道号前缀:ext 非空时 SrcID 必须以其为前缀(UT:0012 语义;系统默认同)。
|
||||
if ext != "" && !strings.HasPrefix(srcID, ext) {
|
||||
logger.L().Warn("cmpp_submit_src_prefix_mismatch",
|
||||
zap.String("source_addr", sourceAddr), zap.String("src_id", srcID),
|
||||
zap.String("ext_code", cfg.ExtCode))
|
||||
return nil, cmpp.SubmitBadCode
|
||||
zap.String("ext_code", ext),
|
||||
zap.Bool("from_system_default", cfg.ExtCode == ""))
|
||||
return nil, "", cmpp.SubmitBadCode
|
||||
}
|
||||
return cfg, cmpp.SubmitOK
|
||||
return cfg, ext, cmpp.SubmitOK
|
||||
}
|
||||
|
||||
// effectiveExtCode 生效校验前缀:账号 ext_code 优先;空则回退系统默认
|
||||
// (Issue#3 方案B;sysCfg 未注入/系统键未配置=空=不校验)。
|
||||
func (s *Service) effectiveExtCode(ctx context.Context, cfg *entity.AccountConfig) string {
|
||||
if cfg.ExtCode != "" {
|
||||
return cfg.ExtCode
|
||||
}
|
||||
if s.sysCfg != nil {
|
||||
return s.sysCfg.Get(ctx, sysconfig.KeyDefaultExtCode)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// submitDirect 普通提交(原 Submit 主体):P0-1(Day 63)快路径受理。
|
||||
@@ -303,7 +331,7 @@ func (s *Service) precheck(ctx context.Context, sourceAddr, srcID string) (*enti
|
||||
func (s *Service) submitDirect(ctx context.Context, sourceAddr, srcID string,
|
||||
dest []string, content string, msgFmt uint8) (uint64, byte) {
|
||||
tAcc := time.Now()
|
||||
cfg, result := s.precheck(ctx, sourceAddr, srcID)
|
||||
cfg, ext, result := s.precheck(ctx, sourceAddr, srcID)
|
||||
tAccCost := time.Since(tAcc)
|
||||
if cfg == nil {
|
||||
return 0, result
|
||||
@@ -316,7 +344,7 @@ func (s *Service) submitDirect(ctx context.Context, sourceAddr, srcID string,
|
||||
PhoneList: dest,
|
||||
Content: content,
|
||||
SignName: "", // CMPP 内容自带【签名】,与 Day41 验收二变口径一致
|
||||
ExtCode: strings.TrimPrefix(srcID, cfg.ExtCode),
|
||||
ExtCode: strings.TrimPrefix(srcID, ext),
|
||||
// Day 70:按 MsgFmt 分流计费口径(UCS2=8:每码元 2B;fee≡上游真实片数)。
|
||||
ContentEncoding: ucs2Encoding(msgFmt == cmpp.MsgFmtUCS2),
|
||||
}, remoteIPPlaceholder)
|
||||
@@ -356,7 +384,8 @@ func (s *Service) Bind(systemID, password, clientIP string) smpp.Status {
|
||||
return smpp.StatusOK
|
||||
}
|
||||
|
||||
// SubmitSM 实现 smpp.ServerHandler:源地址前缀校验→SendMass 受理。
|
||||
// SubmitSM 实现 smpp.ServerHandler:源地址校验(账号 ext_code 优先,空回退系统
|
||||
// 默认接入码——Issue#3 方案B,与 CMPP precheck 同口径)→SendMass 受理。
|
||||
func (s *Service) SubmitSM(systemID, srcAddr, destAddr, content string,
|
||||
registeredDelivery uint8) (string, smpp.Status) {
|
||||
ctx := context.Background()
|
||||
@@ -364,7 +393,8 @@ func (s *Service) SubmitSM(systemID, srcAddr, destAddr, content string,
|
||||
if cfg == nil {
|
||||
return "", smpp.StatusSysErr
|
||||
}
|
||||
if cfg.ExtCode != "" && !strings.HasPrefix(srcAddr, cfg.ExtCode) {
|
||||
ext := s.effectiveExtCode(ctx, cfg)
|
||||
if ext != "" && !strings.HasPrefix(srcAddr, ext) {
|
||||
return "", smpp.StatusSysErr
|
||||
}
|
||||
resp := s.api.SendMass(ctx, &openapi.AuthContext{
|
||||
@@ -373,7 +403,7 @@ func (s *Service) SubmitSM(systemID, srcAddr, destAddr, content string,
|
||||
}, &openapi.MassReq{
|
||||
PhoneList: []string{destAddr},
|
||||
Content: content,
|
||||
ExtCode: strings.TrimPrefix(srcAddr, cfg.ExtCode),
|
||||
ExtCode: strings.TrimPrefix(srcAddr, ext),
|
||||
}, remoteIPPlaceholder)
|
||||
if resp.Code != openapi.CodeOK {
|
||||
return "", smpp.StatusSysErr
|
||||
|
||||
@@ -90,14 +90,16 @@ func longSmsKey(accountID int64, srcID, mobile string, ref uint8) string {
|
||||
}
|
||||
|
||||
// submitFragment 片提交:入组缓存(未齐回组ID 不发)/到齐合并单次受理。
|
||||
// precheck(账号+通道号前缀)已由调用方 Submit 完成,cfg 为验过快照。
|
||||
// precheck(账号+通道号校验)已由调用方 Submit 完成,cfg 为验过快照;
|
||||
// ext=生效校验前缀(账号 ext_code 或系统默认,Issue#3 方案B)——扩展码
|
||||
// 剥离口径与直发一致(TrimPrefix(srcID, ext))。
|
||||
func (g *longSmsGrouper) submitFragment(api longSmsAPI, cfg *entity.AccountConfig,
|
||||
sourceAddr, srcID, mobile, content string, udh *cmpp.UDHInfo, ucs2 bool) (uint64, byte) {
|
||||
ext, sourceAddr, srcID, mobile, content string, udh *cmpp.UDHInfo, ucs2 bool) (uint64, byte) {
|
||||
auth := &openapi.AuthContext{
|
||||
AccountID: cfg.AccountID, Username: sourceAddr, Config: cfg,
|
||||
Source: send.TaskSourceCMPP, // Day 60:受理来源打标(CMPP 接入)
|
||||
}
|
||||
ext := strings.TrimPrefix(srcID, cfg.ExtCode)
|
||||
extCode := strings.TrimPrefix(srcID, ext)
|
||||
key := longSmsKey(cfg.AccountID, srcID, mobile, udh.Ref)
|
||||
|
||||
isNew := false
|
||||
@@ -112,7 +114,7 @@ func (g *longSmsGrouper) submitFragment(api longSmsAPI, cfg *entity.AccountConfi
|
||||
zap.String("source_addr", sourceAddr), zap.String("mobile", mobile),
|
||||
zap.Uint8("ref", udh.Ref), zap.Uint8("group_total", grp.total),
|
||||
zap.Uint8("frag_total", udh.Total))
|
||||
return directSubmit(api, auth, mobile, ext, content, ucs2)
|
||||
return directSubmit(api, auth, mobile, extCode, content, ucs2)
|
||||
}
|
||||
if !ok {
|
||||
if len(g.groups) >= g.maxGroup {
|
||||
@@ -127,7 +129,7 @@ func (g *longSmsGrouper) submitFragment(api longSmsAPI, cfg *entity.AccountConfi
|
||||
}
|
||||
grp = &pendingLong{
|
||||
groupID: uint64(api.NextMsgID()),
|
||||
auth: auth, srcID: srcID, mobile: mobile, extCode: ext,
|
||||
auth: auth, srcID: srcID, mobile: mobile, extCode: extCode,
|
||||
total: udh.Total, ref: udh.Ref, ucs2: ucs2, frags: make(map[uint8]string),
|
||||
}
|
||||
g.groups[key] = grp
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// sysconfig_fallback_test.go Issue#3 方案B:SrcID 校验两级回退链——
|
||||
// 账号 ext_code 优先 > 系统默认 cmpp.default_ext_code > 均空放行。
|
||||
package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/protocol/cmpp"
|
||||
)
|
||||
|
||||
// sysCfgStub 固定值系统配置桩。
|
||||
type sysCfgStub struct{ v string }
|
||||
|
||||
func (s sysCfgStub) Get(_ context.Context, _ string) string { return s.v }
|
||||
|
||||
// TestSubmit_SystemDefaultFallback 账号 ext_code 空 → 回退系统默认:
|
||||
// 匹配系统前缀受理、不匹配回 9、命中日志可辨识。
|
||||
func TestSubmit_SystemDefaultFallback(t *testing.T) {
|
||||
db := newAccessDB(t)
|
||||
u := entity.AccountUser{Username: "noext_user", Status: 1, Balance: 10000}
|
||||
if err := db.Create(&u).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := entity.AccountConfig{AccountID: u.ID, Business: "sms",
|
||||
ApiSecret: "shared-secret-32hex", AuditMode: 0} // ExtCode 留空
|
||||
if err := db.Create(&cfg).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, _ := newSvc(t, db)
|
||||
s.SetSystemConfig(sysCfgStub{v: "SYS:1069"})
|
||||
|
||||
// 系统前缀+扩展 → 过(方案C 动态扩展同口径)。
|
||||
if _, result := s.Submit("noext_user", "SYS:1069001",
|
||||
[]string{"13800138000"}, "【签名】你好", nil, 1, cmpp.MsgFmtGBK); result != cmpp.SubmitOK {
|
||||
t.Fatalf("系统默认前缀应放行: result=%d", result)
|
||||
}
|
||||
// 不匹配系统前缀 → 9。
|
||||
if _, result := s.Submit("noext_user", "XX:9999",
|
||||
[]string{"13800138000"}, "【签名】你好", nil, 1, cmpp.MsgFmtGBK); result != cmpp.SubmitBadCode {
|
||||
t.Fatalf("不匹配系统默认应拒: result=%d", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmit_AccountExtTakesPriority 账号 ext_code 非空时账号优先——系统默认
|
||||
// 不参与(系统前缀的 SrcID 也拒,证明两级不叠加)。
|
||||
func TestSubmit_AccountExtTakesPriority(t *testing.T) {
|
||||
db := newAccessDB(t)
|
||||
seedAccount(t, db) // ExtCode=UT:0012
|
||||
s, _ := newSvc(t, db)
|
||||
s.SetSystemConfig(sysCfgStub{v: "SYS:1069"})
|
||||
|
||||
if _, result := s.Submit("cmpp_user", "SYS:1069001",
|
||||
[]string{"13800138000"}, "【签名】你好", nil, 1, cmpp.MsgFmtGBK); result != cmpp.SubmitBadCode {
|
||||
t.Fatalf("账号 ext 优先:系统前缀应拒(不叠加放行), result=%d", result)
|
||||
}
|
||||
if _, result := s.Submit("cmpp_user", "UT:001299",
|
||||
[]string{"13800138000"}, "【签名】你好", nil, 1, cmpp.MsgFmtGBK); result != cmpp.SubmitOK {
|
||||
t.Fatalf("账号前缀应放行: result=%d", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSubmit_NoSysCfgNoExt 双空放行(getter 未注入/ext 空/系统键空=回归原行为)。
|
||||
func TestSubmit_NoSysCfgNoExt(t *testing.T) {
|
||||
db := newAccessDB(t)
|
||||
u := entity.AccountUser{Username: "noext_user", Status: 1, Balance: 10000}
|
||||
if err := db.Create(&u).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := entity.AccountConfig{AccountID: u.ID, Business: "sms",
|
||||
ApiSecret: "shared-secret-32hex", AuditMode: 0}
|
||||
if err := db.Create(&cfg).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, _ := newSvc(t, db) // 未注入 sysCfg
|
||||
if _, result := s.Submit("noext_user", "ANY:THING",
|
||||
[]string{"13800138000"}, "【签名】你好", nil, 1, cmpp.MsgFmtGBK); result != cmpp.SubmitOK {
|
||||
t.Fatalf("双空应放行(原行为): result=%d", result)
|
||||
}
|
||||
// 注入但系统键空值=同语义。
|
||||
s.SetSystemConfig(sysCfgStub{v: ""})
|
||||
if _, result := s.Submit("noext_user", "ANY:THING",
|
||||
[]string{"13800138000"}, "【签名】你好", nil, 1, cmpp.MsgFmtGBK); result != cmpp.SubmitOK {
|
||||
t.Fatalf("系统键空应放行: result=%d", result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// Package sysconfig 系统参数配置域(Issue#3 方案B):system_config KV 表统一
|
||||
// 读(Get 带 TTL 缓存)/写(Set UPSERT+缓存即刻失效)/列(List)。
|
||||
// 消费方:access(系统默认接入码回退,见 KeyDefaultExtCode)、uplink 拉黑词表
|
||||
// (uplink.blacklist.keywords,该域自刷新不走本缓存,页面改后 60s 生效)。
|
||||
package sysconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/pkg/errors"
|
||||
"go-sms/internal/pkg/logger"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// KeyDefaultExtCode 系统默认接入码前缀(账号 ext_code 为空时回退;Issue#3 方案B:
|
||||
// 账号级优先、系统级兜底——新账号开箱即有码校验,无需逐账号配置)。
|
||||
const KeyDefaultExtCode = "cmpp.default_ext_code"
|
||||
|
||||
const defaultTTL = 30 * time.Second
|
||||
|
||||
type cacheEntry struct {
|
||||
value string
|
||||
expireAt time.Time
|
||||
}
|
||||
|
||||
// Service 系统配置服务。
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
ttl time.Duration
|
||||
|
||||
mu sync.RWMutex
|
||||
cache map[string]cacheEntry
|
||||
}
|
||||
|
||||
// New 构造(ttl≤0=30s,与 access 账号缓存同量级;Set 主动失效兜底即刻生效)。
|
||||
func New(db *gorm.DB, ttl time.Duration) *Service {
|
||||
if ttl <= 0 {
|
||||
ttl = defaultTTL
|
||||
}
|
||||
return &Service{db: db, ttl: ttl, cache: map[string]cacheEntry{}}
|
||||
}
|
||||
|
||||
// Get 读配置(未配置/缺行=空串;DB 错误降级空串记日志且不缓存——校验语义=不拦,
|
||||
// 与账号级 ext_code 缺省放行口径一致)。
|
||||
func (s *Service) Get(ctx context.Context, key string) string {
|
||||
now := time.Now()
|
||||
s.mu.RLock()
|
||||
e, ok := s.cache[key]
|
||||
s.mu.RUnlock()
|
||||
if ok && now.Before(e.expireAt) {
|
||||
return e.value
|
||||
}
|
||||
var row entity.SystemConfig
|
||||
err := s.db.WithContext(ctx).Where("cfg_key = ?", key).First(&row).Error
|
||||
value := ""
|
||||
if err == nil {
|
||||
value = row.CfgValue
|
||||
} else if err != gorm.ErrRecordNotFound {
|
||||
logger.L().Warn("sysconfig_get_failed", zap.String("key", key), zap.Error(err))
|
||||
return ""
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.cache[key] = cacheEntry{value: value, expireAt: now.Add(s.ttl)}
|
||||
s.mu.Unlock()
|
||||
return value
|
||||
}
|
||||
|
||||
// List 全量(cfg_key 升序;管理页数据源)。
|
||||
func (s *Service) List(ctx context.Context) ([]entity.SystemConfig, error) {
|
||||
var rows []entity.SystemConfig
|
||||
err := s.db.WithContext(ctx).Order("cfg_key").Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
// Set UPSERT(uk cfg_key 冲突→更新值/备注/操作人/时间)并即刻失效该键缓存
|
||||
// (改完即生效——区别于账号 ext_code 的 30s accCache 窗口,管理页操作即时可验)。
|
||||
func (s *Service) Set(ctx context.Context, key, value, remark, updatedBy string) (*entity.SystemConfig, error) {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" || len(key) > 64 {
|
||||
return nil, errors.InvalidParam.WithMsg("cfg_key 须 1~64 字符")
|
||||
}
|
||||
if len(value) > 1024 {
|
||||
return nil, errors.InvalidParam.WithMsg("cfg_value 超 1024 字符")
|
||||
}
|
||||
if len(remark) > 255 {
|
||||
return nil, errors.InvalidParam.WithMsg("remark 超 255 字符")
|
||||
}
|
||||
row := &entity.SystemConfig{CfgKey: key, CfgValue: value, Remark: remark, UpdatedBy: updatedBy}
|
||||
if err := s.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "cfg_key"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"cfg_value", "remark", "updated_by", "updated_at"}),
|
||||
}).Create(row).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
delete(s.cache, key)
|
||||
s.mu.Unlock()
|
||||
return row, nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// service_test.go Issue#3 方案B:system_config 读写/缓存失效/UPSERT/校验。
|
||||
package sysconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
)
|
||||
|
||||
func newDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Migrator().CreateTable(&entity.SystemConfig{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// TestGet_MissingKeyIsEmpty 缺行=空串(=不校验语义),不报错。
|
||||
func TestGet_MissingKeyIsEmpty(t *testing.T) {
|
||||
s := New(newDB(t), 0)
|
||||
if v := s.Get(context.Background(), "no.such.key"); v != "" {
|
||||
t.Fatalf("缺行应空串, got %q", v)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetUpsertAndCacheInvalidation Set 后 Get 立即读到新值(写即刻失效缓存,
|
||||
// 不吃 30s TTL 窗口);同 key 二次 Set=更新不报错。
|
||||
func TestSetUpsertAndCacheInvalidation(t *testing.T) {
|
||||
db := newDB(t)
|
||||
s := New(db, time.Minute) // 长 TTL:若失效逻辑缺失本测试必红
|
||||
ctx := context.Background()
|
||||
if _, err := s.Set(ctx, KeyDefaultExtCode, "10690", "系统默认接入码", "admin"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := s.Get(ctx, KeyDefaultExtCode); v != "10690" {
|
||||
t.Fatalf("Get=%q", v)
|
||||
}
|
||||
// 覆盖更新(UPSERT):缓存里已有旧值,Set 后必须立即新值。
|
||||
if _, err := s.Set(ctx, KeyDefaultExtCode, "1069033", "改", "admin2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v := s.Get(ctx, KeyDefaultExtCode); v != "1069033" {
|
||||
t.Fatalf("Set 后缓存未失效: %q", v)
|
||||
}
|
||||
var rows []entity.SystemConfig
|
||||
if err := db.Find(&rows).Error; err != nil || len(rows) != 1 {
|
||||
t.Fatalf("UPSERT 应单行: rows=%d err=%v", len(rows), err)
|
||||
}
|
||||
if rows[0].UpdatedBy != "admin2" {
|
||||
t.Fatalf("updated_by 应更新: %q", rows[0].UpdatedBy)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListOrdered 全量 cfg_key 升序。
|
||||
func TestListOrdered(t *testing.T) {
|
||||
s := New(newDB(t), 0)
|
||||
ctx := context.Background()
|
||||
for _, k := range []string{"b.key", "a.key"} {
|
||||
if _, err := s.Set(ctx, k, "v", "", "op"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rows, err := s.List(ctx)
|
||||
if err != nil || len(rows) != 2 {
|
||||
t.Fatalf("rows=%d err=%v", len(rows), err)
|
||||
}
|
||||
if rows[0].CfgKey != "a.key" {
|
||||
t.Fatalf("应 cfg_key 升序: %s", rows[0].CfgKey)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetValidation 键空/超长、值超长拒绝。
|
||||
func TestSetValidation(t *testing.T) {
|
||||
s := New(newDB(t), 0)
|
||||
ctx := context.Background()
|
||||
if _, err := s.Set(ctx, " ", "v", "", "op"); err == nil {
|
||||
t.Fatal("空键应拒绝")
|
||||
}
|
||||
if _, err := s.Set(ctx, strings.Repeat("k", 65), "v", "", "op"); err == nil {
|
||||
t.Fatal("超长键应拒绝")
|
||||
}
|
||||
if _, err := s.Set(ctx, "k", strings.Repeat("v", 1025), "", "op"); err == nil {
|
||||
t.Fatal("超长值应拒绝")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user