// pair.go 阶段 5 收尾(Day58 挂账清偿/D28):回执重推与手动配对服务。 // - Pending:挂起明细分页(status=1 且挂起超 3h,实施计划 5.5 可配对口径)—— // 手动配对页数据源;msg_id 取该明细首段(message_report_seg MIN)。 // - Pair:四方式(msg_mobile/detail/task_time/time_mobile)圈中挂起明细→ // 人工指定终态(2 成功/3 失败退款/4 未知释放);终态链复用 finalizeDetail // 单一实现(首锁回写+message_report 落库+计费确认+CMPP Deliver 推送), // 与回执消费者行为零漂移——重复配对走锁定跳过分支,资金动作至多一次。 // - Repush:30 天窗口回执重推——命中行重投 DeliverEvent(与首推同口径)+ // push_status 回写;同步执行(dev 命中千级内;异步任务表挂账 D29 下载中心)。 package report import ( "context" "errors" "fmt" "time" "go.uber.org/zap" "gorm.io/gorm" "go-sms/internal/pkg/logger" "go-sms/internal/util" ) // PairPendingWindow 手动配对可用窗口:挂起超 3h(实施计划 5.5 口径)。 const PairPendingWindow = 3 * time.Hour // RepushWindowDays 回执重推数据源保留窗口(message_report 30 天)。 const RepushWindowDays = 30 // RepushBatchMax 单次重推执行上限(同步执行保护;超出记日志截断)。 const RepushBatchMax = 1000 // ErrPairParam 配对/重推参数错误(handler 映射 ISC:400)。 var ErrPairParam = errors.New("pair/repush param") // PairQuery 挂起明细查询(配对页列表)。 type PairQuery struct { Page, PageSize int64 Mobile string // 尾号模糊 TaskNo string // 精确 } // PairPendingRow 挂起明细行(契约 web/src/api/record.ts PendingDetail)。 type PairPendingRow struct { DetailID int64 TaskNo string MsgID string // 通道 msg_id(该明细首段;msg_mobile 配对键) Mobile string Content string SentAt time.Time AgeHours int64 } // PairRequest 手动配对请求(四方式,按 mode 取对应字段)。 type PairRequest struct { Mode string // msg_mobile|detail|task_time|time_mobile MsgID string // msg_mobile:通道 msg_id Mobile string // msg_mobile/time_mobile DetailID int64 // detail:明细雪花 ID 精确 TaskNo string // task_time Start, End *time.Time TargetStatus int8 // 2 成功(不退费)/3 失败(退款)/4 未知(冻结释放) } // PairResult 配对结果(matched=圈中挂起;updated=首锁回写;skipped=并发已终态)。 type PairResult struct { Matched int64 `json:"matched"` Updated int64 `json:"updated"` Skipped int64 `json:"skipped"` } // RepushRequest 回执重推请求(时间窗必填;账号/手机号收窄)。 type RepushRequest struct { AccountID int64 Mobiles []string Start, End time.Time } // PairService 回执重推+手动配对(gateway 进程装配;db/bill/push 与 Consumer 同构)。 type PairService struct { db *gorm.DB bill *Billing push PushSink cb ReportEnqueuer // S4·C1:HTTP 回调入队(nil=跳过) sf *util.Snowflake // 重推受理号(雪花;D29 异步任务表落地后即任务主键) } // NewPairService 构造(bill/push 可为 nil=跳过计费/推送;sf 可为 nil=受理号降级时间戳)。 func NewPairService(db *gorm.DB, bill *Billing, sf *util.Snowflake) *PairService { return &PairService{db: db, bill: bill, sf: sf} } // WithPushSink 注入 CMPP Deliver 下发出口(链式,nil=跳过)。 func (p *PairService) WithPushSink(s PushSink) *PairService { p.push = s return p } // WithCallback 注入 HTTP 回调入队出口(S4·C1;链式,nil=跳过)。 func (p *PairService) WithCallback(e ReportEnqueuer) *PairService { p.cb = e return p } // DB 裸查询出口(handler 回执分页 JOIN 查询复用同一连接)。 func (p *PairService) DB() *gorm.DB { return p.db } // pendingScope 挂起明细基础口径(status=1 且 COALESCE(send_at,created_at) 早于 now-3h)。 func (p *PairService) pendingScope(ctx context.Context) *gorm.DB { return p.db.WithContext(ctx). Table("message_detail AS d"). Where("d.status = 1 AND COALESCE(d.send_at, d.created_at) < ?", time.Now().Add(-PairPendingWindow)) } // Pending 挂起明细分页(挂起久在前;msg_id=该明细首段,长短信代表值)。 func (p *PairService) Pending(ctx context.Context, q PairQuery) ([]PairPendingRow, int64, error) { page, size := q.Page, q.PageSize if page < 1 { page = 1 } if size < 1 || size > 1000 { size = 100 } scope := p.pendingScope(ctx). Joins("JOIN message_task t ON t.id = d.task_id") if q.Mobile != "" { scope = scope.Where("d.mobile LIKE ?", "%"+q.Mobile) } if q.TaskNo != "" { scope = scope.Where("t.task_no = ?", q.TaskNo) } // Count 独立构造:列表查询带 ORDER BY 别名(sent_at),Count 继承会在 // sqlite 报 no such column(gorm 不剥离 ORDER BY)。 var total int64 cnt := p.pendingScope(ctx). Joins("JOIN message_task t ON t.id = d.task_id") if q.Mobile != "" { cnt = cnt.Where("d.mobile LIKE ?", "%"+q.Mobile) } if q.TaskNo != "" { cnt = cnt.Where("t.task_no = ?", q.TaskNo) } if err := cnt.Session(&gorm.Session{}).Count(&total).Error; err != nil { return nil, 0, err } var rows []struct { DetailID int64 TaskNo string MsgID *string Mobile string Content string SentAt string // sqlite 下 COALESCE 结果退化 string(MySQL 侧兼容),Go 侧解析 } if err := scope.Session(&gorm.Session{}). Select(`d.id AS detail_id, t.task_no AS task_no, (SELECT MIN(s2.msg_id) FROM message_report_seg s2 WHERE s2.detail_id = d.id) AS msg_id, d.mobile AS mobile, d.content AS content, COALESCE(d.send_at, d.created_at) AS sent_at`). Order("sent_at ASC"). Limit(int(size)).Offset(int((page - 1) * size)). Scan(&rows).Error; err != nil { return nil, 0, err } parseSentAt := func(s string) time.Time { for _, layout := range []string{time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05.999999999-07:00", "2006-01-02 15:04:05.999999999", "2006-01-02 15:04:05"} { if t, err := time.ParseInLocation(layout, s, time.Local); err == nil { return t } } return time.Time{} } now := time.Now() out := make([]PairPendingRow, 0, len(rows)) for _, r := range rows { msgID := "" if r.MsgID != nil { msgID = *r.MsgID } sentAt := parseSentAt(r.SentAt) var age int64 if !sentAt.IsZero() { age = int64(now.Sub(sentAt).Hours()) } out = append(out, PairPendingRow{ DetailID: r.DetailID, TaskNo: r.TaskNo, MsgID: msgID, Mobile: r.Mobile, Content: r.Content, SentAt: sentAt, AgeHours: age, }) } return out, total, nil } // statusFor 终态 int8 → Day55 三态词。 func statusFor(status int8) Status { switch status { case 2: return StatusSuccess case 3: return StatusFailure default: return StatusUnknown } } // Pair 手动配对:四方式圈中挂起明细→逐条 finalizeDetail(首锁语义, // 重复配对/并发终态走锁定跳过=skipped;资金动作至多一次)。 func (p *PairService) Pair(ctx context.Context, req PairRequest) (PairResult, error) { // 受理即落账(与 Repush 同口径):断开不中止终态链;单条事务原子性 // 由 gorm 保证,重试幂等(首锁跳过)。 ctx = context.WithoutCancel(ctx) var res PairResult switch req.Mode { case "msg_mobile", "detail", "task_time", "time_mobile": default: return res, fmt.Errorf("%w: 配对方式非法", ErrPairParam) } if req.TargetStatus < 2 || req.TargetStatus > 4 { return res, fmt.Errorf("%w: 目标状态须为 2/3/4", ErrPairParam) } scope := p.pendingScope(ctx) switch req.Mode { case "msg_mobile": if req.MsgID == "" || req.Mobile == "" { return res, fmt.Errorf("%w: msg_id/mobile 必填", ErrPairParam) } scope = scope.Where( "d.id IN (SELECT s.detail_id FROM message_report_seg s WHERE s.msg_id = ? AND s.mobile = ?)", req.MsgID, req.Mobile) case "detail": if req.DetailID <= 0 { return res, fmt.Errorf("%w: detail_id 非法", ErrPairParam) } scope = scope.Where("d.id = ?", req.DetailID) case "task_time": if req.TaskNo == "" { return res, fmt.Errorf("%w: task_no 必填", ErrPairParam) } var taskID int64 if err := p.db.WithContext(ctx). Table("message_task").Select("id"). Where("task_no = ?", req.TaskNo).Scan(&taskID).Error; err != nil || taskID == 0 { return res, fmt.Errorf("%w: 任务号不存在", ErrPairParam) } scope = scope.Where("d.task_id = ?", taskID) default: // time_mobile if req.Mobile == "" { return res, fmt.Errorf("%w: mobile 必填", ErrPairParam) } scope = scope.Where("d.mobile = ?", req.Mobile) } if req.Mode == "task_time" || req.Mode == "time_mobile" { if req.Start != nil { scope = scope.Where("COALESCE(d.send_at, d.created_at) >= ?", *req.Start) } if req.End != nil { scope = scope.Where("COALESCE(d.send_at, d.created_at) <= ?", *req.End) } } var ids []int64 if err := scope.Limit(1000).Pluck("d.id", &ids).Error; err != nil { return res, err } res.Matched = int64(len(ids)) st := statusFor(req.TargetStatus) now := time.Now() for _, id := range ids { var d struct { ChannelID int64 Mobile string } if err := p.db.WithContext(ctx).Table("message_detail"). Select("channel_id, mobile").Where("id = ?", id).Scan(&d).Error; err != nil { continue // 行消失(并发删除等):计入 skipped } locked, err := finalizeDetail(ctx, p.db, p.push, id, d.ChannelID, req.TargetStatus, "MANUAL", now, st, d.Mobile) if err != nil { logger.L().Warn("pair_finalize_failed", zap.Int64("detail_id", id), zap.Error(err)) res.Skipped++ continue } if locked { res.Updated++ // 计费确认在终态锁定成功后触发(与 Consumer 回执链同语义)。 if p.bill != nil { p.bill.Confirm(ctx, id, req.TargetStatus) } // S4·C1:HTTP 回调入队(与 Consumer 回执链同挂点;吞错 Warn)。 if p.cb != nil { if err := p.cb.EnqueueReport(ctx, id, req.TargetStatus, string(st), "MANUAL", d.Mobile, now); err != nil { logger.L().Warn("callback_report_enqueue_failed", zap.Int64("detail_id", id), zap.Error(err)) } } } else { res.Skipped++ // 圈中窗口与执行窗口间被回执/并发配对锁定 } } return res, nil } // statusInt8From 三态词 → 终态 int8(重推反向映射)。 func statusInt8From(s string) int8 { switch s { case string(StatusSuccess): return 2 case string(StatusFailure): return 3 default: return 4 } } // Repush 30 天窗口回执重推:命中 report 行(detail JOIN 取 account/mobile)→ // 重投 DeliverEvent(与首推同 payload 口径)→ push_status/pushed_at 回写。 // 同步执行并返回 (受理号, 命中数);受理号雪花生成(D29 任务表落地后即任务主键)。 func (p *PairService) Repush(ctx context.Context, req RepushRequest) (int64, int64, error) { // 受理即落账:执行段脱离请求取消链(客户端超时断开不中止投递/回写, // Day66 实机验收发现逐条回写随 ctx canceled 全部丢失)。 ctx = context.WithoutCancel(ctx) sess := p.db.WithContext(ctx). Table("message_report AS r"). Select("r.id AS report_id, r.detail_id, r.status, r.raw_code, d.account_id, d.mobile"). Joins("JOIN message_detail d ON d.id = r.detail_id"). Where("r.report_at >= ? AND r.report_at <= ?", req.Start, req.End) if req.AccountID > 0 { sess = sess.Where("d.account_id = ?", req.AccountID) } if len(req.Mobiles) > 0 { sess = sess.Where("d.mobile IN ?", req.Mobiles) } var rows []struct { ReportID int64 DetailID int64 Status string RawCode string AccountID int64 Mobile string } if err := sess.Limit(RepushBatchMax + 1).Scan(&rows).Error; err != nil { return 0, 0, err } if int64(len(rows)) > RepushBatchMax { rows = rows[:RepushBatchMax] logger.L().Warn("repush_batch_truncated", zap.Int("cap", RepushBatchMax), zap.String("hint", "收窄时间窗/账号分批重推")) } now := time.Now() // 批量回写:投递与回写按结果分组,2 次批量 UPDATE 替代逐条往返(千条窗 // 25s+ → 秒级);失败仅记日志不中断(重推幂等:重复圈中重投无害)。 pushed, failed := make([]int64, 0, len(rows)), make([]int64, 0, len(rows)) for _, r := range rows { ev := &DeliverEvent{ AccountID: r.AccountID, DetailID: r.DetailID, Mobile: r.Mobile, Stat: statForDeliver(statusInt8From(r.Status), r.RawCode), SubmitAt: cmppTimeMMDDHHMMSS(now), DoneAt: cmppTimeMMDDHHMMSS(now), } // 注:重推不做 source=CMPP 短路——操作者圈中的即需重推的 //(非 CMPP 源投递后网关消费侧按账号反查无会话自然丢弃,尽力而为同首推口径)。 var pushErr error if p.push != nil { pushErr = p.push.PushDeliver(ctx, ev) } if pushErr != nil { failed = append(failed, r.ReportID) } else { pushed = append(pushed, r.ReportID) } } writeback := func(ids []int64, ps int8) { if len(ids) == 0 { return } if err := p.db.WithContext(ctx). Table("message_report").Where("id IN ?", ids). Updates(map[string]any{"push_status": ps, "pushed_at": now}).Error; err != nil { logger.L().Warn("repush_status_writeback_failed", zap.Int("count", len(ids)), zap.Int8("push_status", ps), zap.Error(err)) } } writeback(pushed, 1) writeback(failed, 2) var taskID int64 if p.sf != nil { taskID = p.sf.NextID() } else { taskID = now.UnixMilli() } return taskID, int64(len(rows)), nil }