169 lines
5.7 KiB
Go
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
|
|
}
|