90 lines
2.9 KiB
Go
90 lines
2.9 KiB
Go
// Package interceptor Day 42(阶段 4):发送前拦截器链——
|
|
// 黑名单三级(白名单豁免) / 频次滑动窗口 / 签名 / 退订标识 / 地区屏蔽,
|
|
// 命中短路并经 Recorder 落库 send_block_log;Day 46 提交主链与 /send/precheck 预检共用。
|
|
package interceptor
|
|
|
|
import (
|
|
"context"
|
|
|
|
errs "go-sms/internal/pkg/errors"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// Req 拦截器入参(单号码粒度;Content 为渲染后完整内容=签名+正文)。
|
|
type Req struct {
|
|
TaskNo string
|
|
AccountID int64
|
|
Mobile string
|
|
Content string
|
|
SendType int8
|
|
// DryRun 预检模式(D18/调试):不产生频次计数等副作用,只报告当前状态。
|
|
DryRun bool
|
|
// Scope 请求级数据快照(Day51 R3):批量提交/预检时由 Chain.NewScope 构造,
|
|
// 拦截器经其批量 IN+跨号复用消除逐号重复查库;nil=逐号旧路径(单号调用)。
|
|
Scope *Scope
|
|
}
|
|
|
|
// Block 拦截结果( nil=放行)。
|
|
type Block struct {
|
|
Interceptor string // 命中的拦截器名(链内唯一)
|
|
Code string // ISC 码(落库/前端字典)
|
|
Msg string // 拒绝原因(落库/响应)
|
|
HTTP *errs.Error // HTTP 语义错误(已 WithMsg)
|
|
}
|
|
|
|
// Interceptor 单个拦截器:Check 返回 nil 放行。
|
|
type Interceptor interface {
|
|
Name() string
|
|
Check(ctx context.Context, r *Req) *Block
|
|
}
|
|
|
|
// Recorder 拦截原因落库(Day 42 验收:拦截原因落库)。
|
|
type Recorder interface {
|
|
Record(ctx context.Context, r *Req, b *Block)
|
|
}
|
|
|
|
// Chain 有序拦截器链:按序执行,首个命中短路返回;命中经 Recorder 落库。
|
|
// 固定顺序(硬拦截在前):黑名单 → 频次 → 签名 → 退订 → 地区(NewDefaultChain)。
|
|
type Chain struct {
|
|
items []Interceptor
|
|
rec Recorder // 可 nil(测试/预检不落库)
|
|
db *gorm.DB // Day51:NewScope 依赖(装配库;NewChain 直造为零值=scope 降级放行)
|
|
}
|
|
|
|
// NewChain 构造链(items 顺序即执行顺序)。
|
|
func NewChain(rec Recorder, items ...Interceptor) *Chain {
|
|
return &Chain{items: items, rec: rec}
|
|
}
|
|
|
|
// NewScope 生成请求级快照(Day51 R3:批量提交/预检的拦截链入口调用;
|
|
// 逐号 Check 前构造一次,所有拦截器共享;db 取链装配库;nil 链返回 nil=降级逐号)。
|
|
func (c *Chain) NewScope(ctx context.Context, accountID int64, mobiles []string) *Scope {
|
|
if c == nil {
|
|
return nil
|
|
}
|
|
return NewScope(ctx, c.db, accountID, mobiles)
|
|
}
|
|
|
|
// Names 链顺序(验收:命中顺序符合配置)。
|
|
func (c *Chain) Names() []string {
|
|
out := make([]string, len(c.items))
|
|
for i, it := range c.items {
|
|
out[i] = it.Name()
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Check 执行链:返回首个 Block(命中即短路并落库),nil=放行。
|
|
func (c *Chain) Check(ctx context.Context, r *Req) *Block {
|
|
for _, it := range c.items {
|
|
if b := it.Check(ctx, r); b != nil {
|
|
if c.rec != nil && !r.DryRun { // DryRun 预检不落库(仅真实提交拦截留痕)
|
|
c.rec.Record(ctx, r, b)
|
|
}
|
|
return b
|
|
}
|
|
}
|
|
return nil
|
|
}
|