Files
go-sms-V2/internal/service/interceptor/blacklist.go
T

113 lines
3.5 KiB
Go

// blacklist.go Day 42:黑名单三级检测(白名单豁免)。
package interceptor
import (
"context"
"go-sms/internal/model/entity"
errs "go-sms/internal/pkg/errors"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
// BlacklistCacheKey 本地黑名单 Redis Set(持久,技术方案 9.3)。
const BlacklistCacheKey = "gosms:blacklist:local"
// ThirdPartyBlacklist 三级检测接口(第三方黑名单 API;生产按上家适配器实现)。
type ThirdPartyBlacklist interface {
CheckBlacklist(ctx context.Context, mobile string) (hit bool, err error)
}
// Blacklist 黑名单拦截器(三级+白名单豁免)。
type Blacklist struct {
DB *gorm.DB // 二级:本地库(必传)
RDB redis.UniversalClient // 一级:Redis 缓存(可 nil=降级直查库)
Third ThirdPartyBlacklist // 三级:第三方(可 nil=跳过)
}
// NewBlacklist 构造。
func NewBlacklist(db *gorm.DB, rdb redis.UniversalClient, third ThirdPartyBlacklist) *Blacklist {
return &Blacklist{DB: db, RDB: rdb, Third: third}
}
// Name 拦截器名。
func (b *Blacklist) Name() string { return "blacklist" }
// Check 三级检测;DB/Redis 瞬时故障按放行处理(可用性优先,漏拦由三级兜底)。
func (b *Blacklist) Check(ctx context.Context, r *Req) *Block {
if b == nil || b.DB == nil {
return nil
}
hit := func() *Block {
return &Block{Interceptor: b.Name(), Code: errs.Blacklist.Code,
Msg: "黑名单号码", HTTP: errs.Blacklist}
}
// Day51 R3:请求级快照路径(批量提交/预检)——白名单/黑名单各一次 IN 批查,
// Redis 一级 SMIsMember 批量;语义与逐号路径一致(豁免→一级→二级→三级)。
if r.Scope != nil {
if r.Scope.Whitelisted(r.Mobile) {
return nil
}
if b.RDB != nil && r.Scope.RedisBlacklisted(b.RDB, r.Mobile) {
return hit()
}
if r.Scope.Blacklisted(r.Mobile) {
b.cacheAdd(ctx, r.Mobile) // 命中回写(少数路径,单号回写足够)
return hit()
}
if b.Third != nil {
if ok, err := b.Third.CheckBlacklist(ctx, r.Mobile); err == nil && ok {
b.cacheAdd(ctx, r.Mobile)
return hit()
}
}
return nil
}
// 白名单豁免(账号级或全局 account_id=0)。
var wl int64
if err := b.DB.WithContext(ctx).Model(&entity.PolicyWhitelist{}).
Where("mobile = ? AND account_id IN ?", r.Mobile, []int64{0, r.AccountID}).
Count(&wl).Error; err == nil && wl > 0 {
return nil
}
// 一级:Redis 缓存。
if b.RDB != nil {
if n, err := b.RDB.SIsMember(ctx, BlacklistCacheKey, r.Mobile).Result(); err == nil && n {
return hit()
}
}
// 二级:本地库(手工/上行拒收/第三方来源)。
var cnt int64
if err := b.DB.WithContext(ctx).Model(&entity.PolicyBlacklist{}).
Where("mobile = ? AND account_id IN ?", r.Mobile, []int64{0, r.AccountID}).
Count(&cnt).Error; err == nil && cnt > 0 {
b.cacheAdd(ctx, r.Mobile)
return hit()
}
// 三级:第三方黑名单 API。
if b.Third != nil {
if ok, err := b.Third.CheckBlacklist(ctx, r.Mobile); err == nil && ok {
b.cacheAdd(ctx, r.Mobile)
return hit()
}
}
return nil
}
// cacheAdd 命中回写 Redis 缓存(尽力而为)。
func (b *Blacklist) cacheAdd(ctx context.Context, mobile string) {
if b.RDB != nil {
_ = b.RDB.SAdd(ctx, BlacklistCacheKey, mobile).Err()
}
}
// AddBlacklistCache 黑名单入库后同步缓存(策略中心写路径可调用)。
func AddBlacklistCache(ctx context.Context, rdb redis.UniversalClient, mobile string) error {
if rdb == nil {
return nil
}
return rdb.SAdd(ctx, BlacklistCacheKey, mobile).Err()
}