Files
go-sms-V2/internal/service/callback/callback.go
T
Tory bb60d60529
ci / test (push) Canceled after 0s
ci / web-test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / deploy-dev (push) Canceled after 0s
S4-D1/D2: C1 回调推送引擎+C2 上行自动拉黑——验收项「死信可查/拒收即拉黑」✅: ①C1=callback_task 队列表(迁移 v21,状态机 pending→sent/dead+attempt/next_retry_at/last_code)+PushWorker(2s 扫/批 100/并发 8/2^n 秒指数退避封顶 10min/10 次耗尽死信/UPDATE CAS 防竞态)+双挂点(report 终态首锁[Consumer+PairService,与 CMPP Deliver 同点同语义]+uplink 消费尾)+URL 门控 account_config.report_url/uplink_url(60s TTL 缓存,未配置零任务)+GET /ops/callback(列表+状态计数面板)/POST /ops/callback/:id/resend(casbin ops callback:read/write v21 所种)+前端回调管理页(ops-callback 路由系统管理组+api/callback.ts+状态面板/筛选/载荷展开/死信重派;matrix+guard 33 菜单显式更)+metrics callback_push_total{type,result}/blacklist_total+openapi v1.4.0;②C2=AutoBlacklister 等值词表(trim+lower 防误伤,默认 R/TD/退订/拒收;SystemConfig uplink.blacklist.keywords 可配 60s 刷新)→policy_blacklist(source=2/账号级/uk 幂等)+Redis Set 即时生效,拉黑不影响上行推送(需求原文);③真机全链六步实证(dev 中间件):回执 DELIVRD→detail 终态→HTTP 回调 JSON 送达(200/sent)+上行 R→拉黑(source=2+Redis=1)+推送送达+坏 URL→attempt10→dead→resend ISC:000→修复重投 sent+status_counts 面板;一次性探针 cmd/cbprobe 用后即删+冒烟数据全清;④单测 +13(callback 6[入队门控/载荷/状态机全链/并发批]+uplink 5[词表/配置覆盖/幂等缓存/消费链]+report 2[首锁一次/nil]);⑤门禁=build/vet/-race 40 包/lint 0/eslint0/vue-tsc0/vitest 148/build 全绿;迁移测试 v15..v21 两遍幂等+dev 实跑 v21;gofmt 存量 8 文件顺手清零(S2 遗留);⑥口径诚实标注:载荷无签名挂账/拦截终态 HTTP 未挂(CMPP 侧已有)/PushWorker 单实例 at-least-once;验收单 s4-d1d2-callback.md+CHANGELOG+memory-bank 回填
2026-11-16 11:19:55 +08:00

169 lines
5.7 KiB
Go

// Package callback S4·C1:HTTP 回调推送引擎(指数退避+死信可查)。
// 入队源:report 终态首锁(EnqueueReport,与 CMPP Deliver 同挂点)/uplink
// 消费(EnqueueUplink);投递=PushWorker 周期扫描 callback_task(需求 2.5
// 回执/上行绑定地址;实施计划 5.8 重试队列+指数退避)。
// 客户通知双通道并存:CMPP 活跃会话走 cmpp-deliver(deliver_push.go),
// 配置 report_url/uplink_url 的账号走本引擎(验收=死信可查/重派可恢复)。
package callback
import (
"context"
"encoding/json"
"sync"
"time"
"go-sms/internal/model/entity"
"go-sms/internal/pkg/logger"
"go.uber.org/zap"
"gorm.io/gorm"
)
// urlCacheTTL 账号回调地址缓存 TTL(策略变更最迟生效窗口)。
const urlCacheTTL = 60 * time.Second
// statForStatus 明细终态 int8 → 回调载荷状态词(与 statForDeliver 同口径;
// 成功=DELIVRD,失败/未知=errCode 透传截 16B,空兜底 UNKNOWN)。
func statForStatus(status int8, errCode string) string {
if status == 2 {
return "DELIVRD"
}
if errCode == "" {
return "UNKNOWN"
}
if r := []rune(errCode); len(r) > 16 {
return string(r[:16])
}
return errCode
}
// ReportPayload 回执终态回调载荷(标准 JSON;detail_id 与 Submit_Resp MsgID
// 同口径,客户据此对账)。
type ReportPayload struct {
Type string `json:"type"` // "report"
DetailID int64 `json:"detail_id"`
AccountID int64 `json:"account_id"`
Mobile string `json:"mobile"`
Status int8 `json:"status"` // 2 成功 3 失败 4 未知
Stat string `json:"stat"` // DELIVRD/UNDELIV/上游原始码
ErrorCode string `json:"error_code"`
ReportAt time.Time `json:"report_at"`
}
// UplinkPayload 上行消息回调载荷(需求 2.5:拉黑不影响上行推送)。
type UplinkPayload struct {
Type string `json:"type"` // "uplink"
UplinkID int64 `json:"uplink_id"`
AccountID int64 `json:"account_id"`
DestCode string `json:"dest_code"`
SrcMobile string `json:"src_mobile"`
Content string `json:"content"`
RecvAt string `json:"recv_at"` // RFC3339(透传事件原值)
}
type urlEntry struct {
report, uplink string
exp time.Time
}
// Service 回调入队器:URL 缓存(60s TTL)+ 载荷构造 + callback_task 写入。
// 实现 report.ReportEnqueuer / uplink.UplinkEnqueuer(装配层注入)。
type Service struct {
db *gorm.DB
mu sync.RWMutex
urls map[int64]urlEntry
}
// NewService 构造。
func NewService(db *gorm.DB) *Service {
return &Service{db: db, urls: map[int64]urlEntry{}}
}
// urlsFor 账号回调地址(缓存 miss 回源 account_config;DB 故障返回空串=
// 该账号本轮跳过,下轮回源自愈)。
func (s *Service) urlsFor(ctx context.Context, accountID int64) (report, uplink string) {
now := time.Now()
s.mu.RLock()
e, ok := s.urls[accountID]
s.mu.RUnlock()
if ok && now.Before(e.exp) {
return e.report, e.uplink
}
var cfg entity.AccountConfig
if err := s.db.WithContext(ctx).
Where("account_id = ? AND business = ?", accountID, "sms").
First(&cfg).Error; err != nil {
if err != gorm.ErrRecordNotFound {
logger.L().Warn("callback_url_lookup_failed",
zap.Int64("account_id", accountID), zap.Error(err))
}
return "", "" // 不缓存失败:下轮重查
}
s.mu.Lock()
s.urls[accountID] = urlEntry{report: cfg.ReportURL, uplink: cfg.UplinkURL, exp: now.Add(urlCacheTTL)}
s.mu.Unlock()
return cfg.ReportURL, cfg.UplinkURL
}
// EnqueueReport 回执终态入队(report 域调用;失败仅返回错误由调用方 Warn,
// 终态不回滚——与 CMPP Deliver 下发同口径)。
func (s *Service) EnqueueReport(ctx context.Context, detailID int64,
status int8, st, errCode, mobile string, now time.Time) error {
var accountID int64
if err := s.db.WithContext(ctx).Table("message_detail").
Select("account_id").Where("id = ?", detailID).Scan(&accountID).Error; err != nil {
return err
}
reportURL, _ := s.urlsFor(ctx, accountID)
if reportURL == "" {
return nil // 未配置回调地址:零任务(多数账号)
}
p := ReportPayload{
Type: "report", DetailID: detailID, AccountID: accountID, Mobile: mobile,
Status: status, Stat: statForStatus(status, errCode), ErrorCode: errCode,
ReportAt: now,
}
if st != "" { // report 域三态词优先(DELIVRD/FAILURE/UNKNOWN)
p.Stat = st
}
return s.insert(ctx, accountID, entity.CallbackTypeReport, reportURL, p)
}
// EnqueueUplink 上行消息入队(uplink 域调用;拉黑判定在前不影响推送)。
func (s *Service) EnqueueUplink(ctx context.Context, uplinkID, accountID int64,
destCode, srcMobile, content, recvAt string) error {
_, uplinkURL := s.urlsFor(ctx, accountID)
if uplinkURL == "" {
return nil
}
return s.insert(ctx, accountID, entity.CallbackTypeUplink, uplinkURL, UplinkPayload{
Type: "uplink", UplinkID: uplinkID, AccountID: accountID,
DestCode: destCode, SrcMobile: srcMobile, Content: content, RecvAt: recvAt,
})
}
func (s *Service) insert(ctx context.Context, accountID int64, typ int8, url string, payload any) error {
body, err := json.Marshal(payload)
if err != nil {
return err
}
return s.db.WithContext(ctx).Create(&entity.CallbackTask{
AccountID: accountID, Type: typ, URL: url,
Payload: string(body), Status: entity.CallbackPending,
NextRetryAt: time.Now(),
}).Error
}
// Resend 死信重派(status 2→0/attempt 清零/立即到期;CAS 仅死信可派)。
// 返回影响行数(0=非死信或不存在)。
func (s *Service) Resend(ctx context.Context, id int64) (int64, error) {
res := s.db.WithContext(ctx).Model(&entity.CallbackTask{}).
Where("id = ? AND status = ?", id, entity.CallbackDead).
Updates(map[string]any{
"status": entity.CallbackPending, "attempt": 0,
"next_retry_at": time.Now(), "last_err": "resend by ops",
})
return res.RowsAffected, res.Error
}