暂存一下,防止丢失

This commit is contained in:
2026-07-24 16:07:18 +08:00
parent 5d6e23f1a5
commit a18ed8bc8d
180 changed files with 13597 additions and 1986 deletions

View File

@@ -0,0 +1,41 @@
package task
import (
"context"
"github.com/bytedance/sonic"
"github.com/hibiken/asynq"
"go.uber.org/zap"
cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
"github.com/break/junhong_cmp_fiber/pkg/errors"
)
// CardObservationSeriesHandler 处理固定零重试的卡观测序列尝试。
type CardObservationSeriesHandler struct {
service *cardapp.SeriesAttemptService
logger *zap.Logger
}
// NewCardObservationSeriesHandler 创建卡观测序列任务处理器。
func NewCardObservationSeriesHandler(service *cardapp.SeriesAttemptService, logger *zap.Logger) *CardObservationSeriesHandler {
return &CardObservationSeriesHandler{service: service, logger: logger}
}
// Handle 解析结构化载荷并执行单次观测。
func (h *CardObservationSeriesHandler) Handle(ctx context.Context, task *asynq.Task) error {
if h == nil || h.service == nil {
return errors.New(errors.CodeInternalError, "卡观测序列任务服务未配置")
}
var payload cardapp.SeriesTaskPayload
if err := sonic.Unmarshal(task.Payload(), &payload); err != nil {
h.logger.Error("解析卡观测序列任务载荷失败", zap.Error(err))
return errors.Wrap(errors.CodeInvalidParam, err, "卡观测序列任务载荷无法解析")
}
if err := h.service.Execute(ctx, payload); err != nil {
h.logger.Warn("卡观测序列当前尝试失败",
zap.String("series_id", payload.SeriesID), zap.Int("attempt", payload.Attempt), zap.Error(err))
return err
}
return nil
}

View File

@@ -0,0 +1,31 @@
package task
import (
"context"
"github.com/hibiken/asynq"
"go.uber.org/zap"
notificationinfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/notification"
)
// NotificationCleanupHandler 处理低峰通知保留清理任务。
type NotificationCleanupHandler struct {
service *notificationinfra.CleanupService
logger *zap.Logger
}
// NewNotificationCleanupHandler 创建通知保留清理任务处理器。
func NewNotificationCleanupHandler(service *notificationinfra.CleanupService, logger *zap.Logger) *NotificationCleanupHandler {
return &NotificationCleanupHandler{service: service, logger: logger}
}
// Handle 执行有界、可重入的通知分批清理。
func (h *NotificationCleanupHandler) Handle(ctx context.Context, _ *asynq.Task) error {
h.logger.Info("开始执行站内通知保留清理")
if err := h.service.Run(ctx); err != nil {
h.logger.Error("站内通知保留清理失败", zap.String("failure_category", "database"), zap.Error(err))
return err
}
return nil
}

View File

@@ -2,211 +2,110 @@ package task
import (
"context"
"strings"
"time"
"github.com/hibiken/asynq"
"go.uber.org/zap"
"gorm.io/gorm"
cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
carddomain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
"github.com/break/junhong_cmp_fiber/internal/gateway"
"github.com/break/junhong_cmp_fiber/internal/model"
iot_card_svc "github.com/break/junhong_cmp_fiber/internal/service/iot_card"
packagepkg "github.com/break/junhong_cmp_fiber/internal/service/package"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
)
// PollingCarddataHandler 流量检查任务处理器
// 职责:调 Gateway 查流量 → 写 DB → 扣减套餐流量 → 调 EvaluateAndAct 判断停复机
// 不做:直接停复机决策,委托给 StopResumeService.EvaluateAndAct
// PollingCarddataHandler 负责流量轮询编排,查询结果统一交给卡观测应用服务。
type PollingCarddataHandler struct {
base *PollingBase
gateway *gateway.Client
iotCardStore *postgres.IotCardStore
carrierStore *postgres.CarrierStore
usageService *packagepkg.UsageService
stopResumeSvc iot_card_svc.StopResumeServiceInterface
base *PollingBase
gateway *gateway.Client
carrier *postgres.CarrierStore
observation *cardapp.Service
integration *integrationlog.Repository
}
// NewPollingCarddataHandler 创建流量检查任务处理器
func NewPollingCarddataHandler(
base *PollingBase,
gw *gateway.Client,
iotCardStore *postgres.IotCardStore,
carrierStore *postgres.CarrierStore,
usageService *packagepkg.UsageService,
stopResumeSvc iot_card_svc.StopResumeServiceInterface,
) *PollingCarddataHandler {
return &PollingCarddataHandler{
base: base,
gateway: gw,
iotCardStore: iotCardStore,
carrierStore: carrierStore,
usageService: usageService,
stopResumeSvc: stopResumeSvc,
}
// NewPollingCarddataHandler 创建流量检查任务处理器
func NewPollingCarddataHandler(base *PollingBase, gw *gateway.Client, carrier *postgres.CarrierStore, observation *cardapp.Service, integration *integrationlog.Repository) *PollingCarddataHandler {
return &PollingCarddataHandler{base: base, gateway: gw, carrier: carrier, observation: observation, integration: integration}
}
// Handle 处理流量检查任务
func (h *PollingCarddataHandler) Handle(ctx context.Context, t *asynq.Task) error {
startTime := time.Now()
cardID, ok := parseTaskPayload(t.Payload(), h.base.logger)
// Handle 处理流量检查任务
func (h *PollingCarddataHandler) Handle(ctx context.Context, task *asynq.Task) error {
startedAt := time.Now()
cardID, ok := parseTaskPayload(task.Payload(), h.base.logger)
if !ok {
return nil
}
if !h.base.acquireConcurrency(ctx, constants.TaskTypePollingCarddata) {
h.base.logger.Debug("并发已满,重新入队", zap.Uint("card_id", cardID))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCarddata)
}
defer h.base.releaseConcurrency(ctx, constants.TaskTypePollingCarddata)
locked, lockErr := h.base.acquireCardTrafficSyncLock(ctx, cardID)
if lockErr != nil {
h.base.logger.Warn("获取卡流量同步锁失败,延迟重入队", zap.Uint("card_id", cardID), zap.Error(lockErr))
return h.base.queueMgr.Requeue(ctx, cardID, constants.TaskTypePollingCarddata, time.Now().Add(5*time.Second))
}
if !locked {
h.base.logger.Info("卡流量同步正在执行,延迟重入队", zap.Uint("card_id", cardID))
locked, err := h.base.acquireCardTrafficSyncLock(ctx, cardID)
if err != nil || !locked {
h.base.logger.Warn("卡流量同步锁不可用,延迟重入队", zap.Uint("card_id", cardID), zap.Error(err))
return h.base.queueMgr.Requeue(ctx, cardID, constants.TaskTypePollingCarddata, time.Now().Add(5*time.Second))
}
defer h.base.releaseCardTrafficSyncLock(ctx, cardID)
h.base.invalidateCardCache(ctx, cardID)
card, err := h.iotCardStore.GetByID(ctx, cardID)
card, err := h.base.iotCardStore.GetByID(ctx, cardID)
if err != nil {
if isNotFound(err) {
return nil
}
h.base.logger.Error("获取卡信息失败", zap.Uint("card_id", cardID), zap.Error(err))
h.base.updateStats(ctx, constants.TaskTypePollingCarddata, false, time.Since(startTime))
return h.failAndRequeue(ctx, cardID, startedAt, "获取卡信息失败", err)
}
if h.gateway == nil {
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCarddata)
}
var gatewayFlowMB float64
if h.gateway != nil {
result, gwErr := h.gateway.QueryFlow(ctx, &gateway.FlowQueryReq{CardNo: card.ICCID})
if gwErr != nil {
h.base.logger.Warn("查询流量失败",
zap.Uint("card_id", cardID), zap.String("iccid", card.ICCID), zap.Error(gwErr))
h.base.updateStats(ctx, constants.TaskTypePollingCarddata, false, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCarddata)
}
gatewayFlowMB = float64(result.Used)
} else {
gatewayFlowMB = card.CurrentMonthUsageMB
attemptStartedAt := time.Now()
attempt, err := startGatewayAttempt(ctx, h.integration, cardID, constants.IntegrationOperationGatewayTraffic, constants.CardObservationSceneTrafficPolling)
if err != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "建立 Gateway 流量 Integration Log 失败", err)
}
result, err := h.gateway.QueryFlow(ctx, &gateway.FlowQueryReq{CardNo: card.ICCID})
if err != nil {
_ = completeGatewayAttempt(ctx, h.integration, attempt, false, attemptStartedAt)
return h.failAndRequeue(ctx, cardID, startedAt, "查询流量失败", err)
}
if strings.TrimSpace(result.ICCID) == "" {
_ = completeGatewayAttempt(ctx, h.integration, attempt, false, attemptStartedAt)
return h.failAndRequeue(ctx, cardID, startedAt, "流量查询响应缺少 ICCID", nil)
}
if logErr := completeGatewayAttempt(ctx, h.integration, attempt, true, attemptStartedAt); logErr != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "完成 Gateway 流量 Integration Log 失败", logErr)
}
if h.observation == nil || h.carrier == nil {
return h.failAndRequeue(ctx, cardID, startedAt, "卡流量观测能力未配置", nil)
}
now := time.Now()
resetDay := h.carrierStore.GetDataResetDay(ctx, card.CarrierID)
updates, flowIncrementMB, isCrossMonth := h.calculateFlowUpdates(card, gatewayFlowMB, now, resetDay)
updates["last_data_check_at"] = now
if h.gateway != nil {
updates["last_sync_time"] = now
decision, err := h.observation.ApplyTrafficObservation(ctx, carddomain.TrafficObservation{
CardID: cardID, GatewayReadingMB: float64(result.Used), ResetDay: h.carrier.GetDataResetDay(ctx, card.CarrierID),
Metadata: carddomain.ObservationMetadata{
ObservationID: attempt.IntegrationID, Source: constants.CardObservationSourcePolling,
Scene: constants.CardObservationSceneTrafficPolling, ObservedAt: now, CorrelationID: attempt.IntegrationID,
},
})
if err != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "应用流量观测失败", err)
}
if h.base.verboseLog && h.gateway != nil {
h.base.logger.Info("流量轮询详情",
zap.Uint("card_id", cardID),
zap.String("iccid", card.ICCID),
zap.Float64("gateway_flow_mb", gatewayFlowMB),
zap.Float64("increment_mb", flowIncrementMB),
zap.Bool("is_cross_month", isCrossMonth))
if h.base.verboseLog {
h.base.logger.Info("流量轮询详情", zap.Uint("card_id", cardID), zap.String("iccid", card.ICCID),
zap.Float64("gateway_flow_mb", float64(result.Used)), zap.Float64("increment_mb", decision.IncrementMB),
zap.Bool("is_cross_month", decision.CrossMonth), zap.Bool("reading_accepted", decision.ReadingAccepted))
}
if updateErr := h.iotCardStore.UpdateFields(ctx, cardID, updates); updateErr != nil {
h.base.logger.Error("更新卡流量信息失败", zap.Uint("card_id", cardID), zap.Error(updateErr))
h.base.updateStats(ctx, constants.TaskTypePollingCarddata, false, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCarddata)
}
go h.base.insertDataUsageRecord(context.Background(), cardID, flowIncrementMB, now)
if refreshedCard, loadErr := h.iotCardStore.GetByID(ctx, cardID); loadErr == nil {
writeCardToCache(h.base, constants.RedisPollingCardInfoKey(cardID), refreshedCard)
} else {
h.base.invalidateCardCache(ctx, cardID)
h.base.logger.Warn("刷新卡缓存失败", zap.Uint("card_id", cardID), zap.Error(loadErr))
}
if flowIncrementMB > 0 && h.usageService != nil {
if deductErr := h.usageService.DeductDataUsage(ctx, constants.AssetTypeIotCard, cardID, flowIncrementMB); deductErr != nil {
h.base.logger.Warn("套餐流量扣减失败",
zap.Uint("card_id", cardID), zap.Float64("increment_mb", flowIncrementMB), zap.Error(deductErr))
}
}
if h.stopResumeSvc != nil {
freshCard, loadErr := h.iotCardStore.GetByID(ctx, cardID)
if loadErr == nil {
if evalErr := h.stopResumeSvc.EvaluateAndAct(ctx, freshCard); evalErr != nil {
h.base.logger.Warn("流量检查后停复机评估失败",
zap.Uint("card_id", cardID), zap.Error(evalErr))
}
}
}
h.base.updateStats(ctx, constants.TaskTypePollingCarddata, true, time.Since(startTime))
h.base.updateStats(ctx, constants.TaskTypePollingCarddata, true, time.Since(startedAt))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCarddata)
}
// calculateFlowUpdates 计算流量更新字段、增量和是否跨月
// 决策13完整迁移跨月流量边界检测逻辑月份切换检测、上月总量保存、当月计数器重置
// 第三个返回值 isCrossMonth 供调用方同步更新 Redis 缓存,避免下次误判跨月
func (h *PollingCarddataHandler) calculateFlowUpdates(card *model.IotCard, gatewayFlowMB float64, now time.Time, resetDay int) (map[string]any, float64, bool) {
updates := make(map[string]any)
increment := gatewayFlowMB - card.LastGatewayReadingMB
shouldUpdateGatewayReading := true
if increment < 0 {
if isResetWindow(now, resetDay) {
increment = gatewayFlowMB
h.base.logger.Info("检测到上游运营商重置",
zap.Uint("card_id", card.ID),
zap.Float64("gateway_flow", gatewayFlowMB),
zap.Float64("last_reading", card.LastGatewayReadingMB),
zap.Int("reset_day", resetDay))
} else {
h.base.logger.Warn("流量异常:非重置日出现值下降",
zap.Uint("card_id", card.ID),
zap.Float64("gateway_flow", gatewayFlowMB),
zap.Float64("last_reading", card.LastGatewayReadingMB))
increment = 0
shouldUpdateGatewayReading = false
}
func (h *PollingCarddataHandler) failAndRequeue(ctx context.Context, cardID uint, startedAt time.Time, message string, err error) error {
fields := []zap.Field{zap.Uint("card_id", cardID)}
if err != nil {
fields = append(fields, zap.Error(err))
}
if shouldUpdateGatewayReading {
updates["last_gateway_reading_mb"] = gatewayFlowMB
}
currentMonthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
isCrossMonth := card.CurrentMonthStartDate == nil ||
card.CurrentMonthStartDate.Before(currentMonthStart)
if isCrossMonth {
h.base.logger.Info("检测到跨月,重置流量计数",
zap.Uint("card_id", card.ID),
zap.Float64("last_month_total", card.CurrentMonthUsageMB))
updates["last_month_total_mb"] = card.CurrentMonthUsageMB
updates["current_month_start_date"] = currentMonthStart
if increment > 0 {
updates["current_month_usage_mb"] = increment
} else {
updates["current_month_usage_mb"] = float64(0)
}
} else if increment > 0 {
updates["current_month_usage_mb"] = gorm.Expr("current_month_usage_mb + ?", increment)
}
if increment > 0 {
updates["data_usage_mb"] = gorm.Expr("data_usage_mb + ?", int64(increment))
}
if card.CurrentMonthStartDate == nil {
updates["current_month_start_date"] = currentMonthStart
}
return updates, increment, isCrossMonth
h.base.logger.Warn(message, fields...)
h.base.updateStats(ctx, constants.TaskTypePollingCarddata, false, time.Since(startedAt))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCarddata)
}

View File

@@ -8,181 +8,108 @@ import (
"github.com/hibiken/asynq"
"go.uber.org/zap"
cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
carddomain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
"github.com/break/junhong_cmp_fiber/internal/gateway"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
"github.com/break/junhong_cmp_fiber/internal/model"
iot_card_svc "github.com/break/junhong_cmp_fiber/internal/service/iot_card"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
)
// shouldStopPollingForRisk 判断轮询到风险 gateway_extend 时是否应停止该卡的轮询
// 仅独立卡is_standalone=true命中风险状态时才停止绑定设备的卡不受此逻辑约束
func shouldStopPollingForRisk(card *model.IotCard, newGatewayExtend string) bool {
if !card.IsStandalone {
// PollingCardStatusHandler 负责网络状态轮询编排,查询结果统一交给卡观测应用服务。
type PollingCardStatusHandler struct {
base *PollingBase
gateway *gateway.Client
observation *cardapp.Service
integration *integrationlog.Repository
}
// shouldStopPollingForRisk 保留旧测试与调用方的纯判断兼容入口,规则权威在卡观测领域层。
func shouldStopPollingForRisk(card *model.IotCard, extend string) bool {
if card == nil {
return false
}
extend := strings.TrimSpace(newGatewayExtend)
return extend == constants.GatewayCardExtendRiskStop ||
extend == constants.GatewayCardExtendCancelled
return carddomain.ShouldStopPollingForRisk(card.IsStandalone, strings.TrimSpace(extend))
}
// PollingCardStatusHandler 卡开停机状态轮询任务处理器
// 职责:调 Gateway 查卡状态(正常/停机/准备)→ 映射为 network_status → 写 DB → 触发停复机评估
// 不做:直接停复机决策,委托给 StopResumeService.EvaluateAndAct
type PollingCardStatusHandler struct {
base *PollingBase
gateway *gateway.Client
iotCardStore *postgres.IotCardStore
stopResumeSvc iot_card_svc.StopResumeServiceInterface
// NewPollingCardStatusHandler 创建卡状态轮询任务处理器
func NewPollingCardStatusHandler(base *PollingBase, gw *gateway.Client, observation *cardapp.Service, integration *integrationlog.Repository) *PollingCardStatusHandler {
return &PollingCardStatusHandler{base: base, gateway: gw, observation: observation, integration: integration}
}
// NewPollingCardStatusHandler 创建卡状态轮询任务处理器
func NewPollingCardStatusHandler(
base *PollingBase,
gw *gateway.Client,
iotCardStore *postgres.IotCardStore,
stopResumeSvc iot_card_svc.StopResumeServiceInterface,
) *PollingCardStatusHandler {
return &PollingCardStatusHandler{
base: base,
gateway: gw,
iotCardStore: iotCardStore,
stopResumeSvc: stopResumeSvc,
}
}
// Handle 处理卡状态轮询任务
func (h *PollingCardStatusHandler) Handle(ctx context.Context, t *asynq.Task) error {
startTime := time.Now()
cardID, ok := parseTaskPayload(t.Payload(), h.base.logger)
// Handle 处理卡状态轮询任务
func (h *PollingCardStatusHandler) Handle(ctx context.Context, task *asynq.Task) error {
startedAt := time.Now()
cardID, ok := parseTaskPayload(task.Payload(), h.base.logger)
if !ok {
return nil
}
if !h.base.acquireConcurrency(ctx, constants.TaskTypePollingCardStatus) {
h.base.logger.Debug("并发已满,重新入队", zap.Uint("card_id", cardID))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCardStatus)
}
defer h.base.releaseConcurrency(ctx, constants.TaskTypePollingCardStatus)
card, err := h.base.getCardWithCache(ctx, cardID)
if err != nil {
if isNotFound(err) {
return nil
}
h.base.logger.Error("获取卡信息失败", zap.Uint("card_id", cardID), zap.Error(err))
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, false, time.Since(startTime))
return h.failAndRequeue(ctx, cardID, startedAt, "获取卡信息失败", err)
}
if h.gateway == nil {
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCardStatus)
}
newNetworkStatus := card.NetworkStatus
gatewayCardStatus := ""
gatewayExtend := card.GatewayExtend
gatewayCardIMEI := ""
statusQueried := false
if h.gateway != nil {
result, gwErr := h.gateway.QueryCardStatus(ctx, &gateway.CardStatusReq{CardNo: card.ICCID})
if gwErr != nil {
h.base.logger.Warn("查询卡状态失败",
zap.Uint("card_id", cardID), zap.String("iccid", card.ICCID), zap.Error(gwErr))
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, false, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCardStatus)
}
gatewayCardStatus = result.CardStatus
gatewayExtend = strings.TrimSpace(result.Extend)
gatewayCardIMEI = strings.TrimSpace(result.IMEI)
statusQueried = true
parsedStatus, ok := gateway.ParseCardNetworkStatus(result.CardStatus, gatewayExtend)
if !ok {
h.base.logger.Warn("卡状态轮询:未知 Gateway 卡状态",
zap.Uint("card_id", cardID),
zap.String("iccid", card.ICCID),
zap.String("card_status", result.CardStatus),
zap.String("extend", gatewayExtend))
} else {
newNetworkStatus = parsedStatus
}
if h.base.verboseLog {
h.base.logger.Info("卡状态轮询详情",
zap.Uint("card_id", cardID),
zap.String("iccid", card.ICCID),
zap.String("card_status", result.CardStatus),
zap.String("extend", gatewayExtend),
zap.Int("new_network_status", newNetworkStatus),
zap.Bool("changed", newNetworkStatus != card.NetworkStatus))
}
attemptStartedAt := time.Now()
attempt, err := startGatewayAttempt(ctx, h.integration, cardID, constants.IntegrationOperationGatewayNetwork, constants.CardObservationSceneNetworkPolling)
if err != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "建立 Gateway 网络 Integration Log 失败", err)
}
result, err := h.gateway.QueryCardStatus(ctx, &gateway.CardStatusReq{CardNo: card.ICCID})
if err != nil {
_ = completeGatewayAttempt(ctx, h.integration, attempt, false, attemptStartedAt)
return h.failAndRequeue(ctx, cardID, startedAt, "查询卡状态失败", err)
}
if strings.TrimSpace(result.ICCID) == "" {
_ = completeGatewayAttempt(ctx, h.integration, attempt, false, attemptStartedAt)
return h.failAndRequeue(ctx, cardID, startedAt, "卡状态查询响应缺少 ICCID", nil)
}
if logErr := completeGatewayAttempt(ctx, h.integration, attempt, true, attemptStartedAt); logErr != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "完成 Gateway 网络 Integration Log 失败", logErr)
}
if h.observation == nil {
return h.failAndRequeue(ctx, cardID, startedAt, "卡网络观测能力未配置", nil)
}
statusChanged := newNetworkStatus != card.NetworkStatus
now := time.Now()
// 无论状态是否变化,都更新最后一次检查时间
fields := map[string]any{"last_card_status_check_at": now}
if statusQueried {
fields["gateway_extend"] = gatewayExtend
fields["last_sync_time"] = now
if gatewayCardIMEI != "" {
fields["gateway_card_imei"] = gatewayCardIMEI
}
decision, err := h.observation.ApplyNetworkObservation(ctx, carddomain.NetworkObservation{
CardID: cardID, GatewayStatus: result.CardStatus, GatewayExtend: result.Extend, GatewayIMEI: result.IMEI,
Metadata: carddomain.ObservationMetadata{
ObservationID: attempt.IntegrationID, Source: constants.CardObservationSourcePolling,
Scene: constants.CardObservationSceneNetworkPolling, ObservedAt: now, CorrelationID: attempt.IntegrationID,
},
})
if err != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "应用网络状态观测失败", err)
}
if statusChanged {
fields["network_status"] = newNetworkStatus
// 网关侧停机事件:补写 stop_reason便于状态追踪和区分手动停机
if newNetworkStatus == constants.NetworkStatusOffline &&
card.StopReason == "" &&
gateway.IsGatewayCardStopped(gatewayCardStatus) {
fields["stop_reason"] = constants.StopReasonCarrierStopped
}
if h.base.verboseLog || !decision.StatusKnown {
h.base.logger.Info("卡状态轮询详情", zap.Uint("card_id", cardID), zap.String("iccid", card.ICCID),
zap.String("card_status", result.CardStatus), zap.String("extend", strings.TrimSpace(result.Extend)),
zap.Int("new_network_status", decision.AfterStatus), zap.Bool("status_known", decision.StatusKnown),
zap.Bool("changed", decision.StatusChanged), zap.Bool("stop_polling", decision.StopPolling))
}
if updateErr := h.iotCardStore.UpdateFields(ctx, cardID, fields); updateErr != nil {
h.base.logger.Warn("更新卡状态信息失败", zap.Uint("card_id", cardID), zap.Error(updateErr))
h.base.invalidateCardCache(ctx, cardID)
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, false, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCardStatus)
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, true, time.Since(startedAt))
if decision.StopPolling {
h.base.logger.Info("独立卡命中风险状态,已关闭轮询", zap.Uint("card_id", cardID), zap.String("gateway_extend", decision.GatewayExtend))
return nil
}
if statusQueried || statusChanged {
cacheUpdates := map[string]any{}
if statusQueried {
cacheUpdates["gateway_extend"] = gatewayExtend
}
if statusChanged {
cacheUpdates["network_status"] = newNetworkStatus
}
h.base.updateCardCache(ctx, cardID, cacheUpdates)
}
// 独立卡写入风险 gateway_extend 后:关闭轮询,终止循环
if statusQueried && shouldStopPollingForRisk(card, gatewayExtend) {
if updateErr := h.iotCardStore.UpdatePollingStatus(ctx, cardID, false); updateErr != nil {
h.base.logger.Warn("关闭风险卡轮询状态失败",
zap.Uint("card_id", cardID), zap.String("gateway_extend", gatewayExtend), zap.Error(updateErr))
} else {
h.base.logger.Info("独立卡命中风险状态,已关闭轮询",
zap.Uint("card_id", cardID), zap.String("gateway_extend", gatewayExtend))
}
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, true, time.Since(startTime))
return nil // 不再入队,终止轮询循环
}
if statusChanged {
h.base.logger.Info("卡状态已变化",
zap.Uint("card_id", cardID),
zap.Int("old_status", card.NetworkStatus),
zap.Int("new_status", newNetworkStatus))
if h.stopResumeSvc != nil {
freshCard, loadErr := h.iotCardStore.GetByID(ctx, cardID)
if loadErr == nil {
if evalErr := h.stopResumeSvc.EvaluateAndAct(ctx, freshCard); evalErr != nil {
h.base.logger.Warn("卡状态变化后停复机评估失败",
zap.Uint("card_id", cardID), zap.Error(evalErr))
}
}
}
}
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, true, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCardStatus)
}
func (h *PollingCardStatusHandler) failAndRequeue(ctx context.Context, cardID uint, startedAt time.Time, message string, err error) error {
fields := []zap.Field{zap.Uint("card_id", cardID)}
if err != nil {
fields = append(fields, zap.Error(err))
}
h.base.logger.Warn(message, fields...)
h.base.updateStats(ctx, constants.TaskTypePollingCardStatus, false, time.Since(startedAt))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCardStatus)
}

View File

@@ -0,0 +1,45 @@
package task
import (
"context"
"strconv"
"time"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/errors"
)
// startGatewayAttempt 在实际调用 Gateway 前建立 Integration Log 尝试事实。
func startGatewayAttempt(ctx context.Context, repository *integrationlog.Repository, cardID uint, operation, scene string) (*model.IntegrationLog, error) {
if repository == nil {
return nil, errors.New(errors.CodeInternalError, "Gateway Integration Log 未配置")
}
resourceID := strconv.FormatUint(uint64(cardID), 10)
triggerSource := constants.CardObservationSourcePolling
triggerScene := scene
return repository.Start(ctx, integrationlog.Attempt{
Provider: constants.IntegrationProviderGateway, Direction: constants.IntegrationDirectionOutbound,
Operation: operation, ResourceType: constants.AssetTypeIotCard, ResourceID: &resourceID,
TriggerSource: &triggerSource, TriggerScene: &triggerScene,
RequestSummary: map[string]any{"card_id": cardID}, Metadata: map[string]any{"scene": scene},
InitialResult: constants.IntegrationResultPending,
})
}
// completeGatewayAttempt 记录 Gateway 查询成功或明确失败,不把响应正文写入日志。
func completeGatewayAttempt(ctx context.Context, repository *integrationlog.Repository, attempt *model.IntegrationLog, success bool, startedAt time.Time) error {
if repository == nil || attempt == nil {
return errors.New(errors.CodeInternalError, "Gateway Integration Log 尝试不存在")
}
result := constants.IntegrationResultFailed
if success {
result = constants.IntegrationResultSuccess
}
_, err := repository.Complete(ctx, attempt.IntegrationID, integrationlog.Completion{
Result: result, DurationMS: time.Since(startedAt).Milliseconds(), StateChanged: false,
ResponseSummary: map[string]any{"success": success},
})
return err
}

View File

@@ -2,58 +2,39 @@ package task
import (
"context"
"strings"
"time"
"github.com/bytedance/sonic"
"github.com/hibiken/asynq"
"go.uber.org/zap"
cardapp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
carddomain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation"
"github.com/break/junhong_cmp_fiber/internal/gateway"
iot_card_svc "github.com/break/junhong_cmp_fiber/internal/service/iot_card"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/internal/infrastructure/integrationlog"
"github.com/break/junhong_cmp_fiber/pkg/constants"
)
// PollingRealnameHandler 实名检查任务处理器
// 职责:调 Gateway 查实名状态 → 写 DB → 触发首次实名激活任务
// 不做:停复机决策(实名状态 0→1 时通过 EvaluateAndAct 触发 not_realname 复机)
// PollingRealnameHandler 负责实名轮询编排,查询结果统一交给卡观测应用服务。
type PollingRealnameHandler struct {
base *PollingBase
gateway *gateway.Client
iotCardStore *postgres.IotCardStore
asynqClient *asynq.Client
stopResumeSvc iot_card_svc.StopResumeServiceInterface
deviceSimBindingStore *postgres.DeviceSimBindingStore
base *PollingBase
gateway *gateway.Client
observation *cardapp.Service
integration *integrationlog.Repository
}
// NewPollingRealnameHandler 创建实名检查任务处理器
func NewPollingRealnameHandler(
base *PollingBase,
gw *gateway.Client,
iotCardStore *postgres.IotCardStore,
asynqClient *asynq.Client,
stopResumeSvc iot_card_svc.StopResumeServiceInterface,
deviceSimBindingStore *postgres.DeviceSimBindingStore,
) *PollingRealnameHandler {
return &PollingRealnameHandler{
base: base,
gateway: gw,
iotCardStore: iotCardStore,
asynqClient: asynqClient,
stopResumeSvc: stopResumeSvc,
deviceSimBindingStore: deviceSimBindingStore,
}
// NewPollingRealnameHandler 创建实名检查任务处理器
func NewPollingRealnameHandler(base *PollingBase, gw *gateway.Client, observation *cardapp.Service, integration *integrationlog.Repository) *PollingRealnameHandler {
return &PollingRealnameHandler{base: base, gateway: gw, observation: observation, integration: integration}
}
// Handle 处理实名检查任务
func (h *PollingRealnameHandler) Handle(ctx context.Context, t *asynq.Task) error {
startTime := time.Now()
cardID, ok := parseTaskPayload(t.Payload(), h.base.logger)
// Handle 处理实名检查任务
func (h *PollingRealnameHandler) Handle(ctx context.Context, task *asynq.Task) error {
startedAt := time.Now()
cardID, ok := parseTaskPayload(task.Payload(), h.base.logger)
if !ok {
return nil
}
if !h.base.acquireConcurrency(ctx, constants.TaskTypePollingRealname) {
h.base.logger.Debug("并发已满,重新入队", zap.Uint("card_id", cardID))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
@@ -65,192 +46,57 @@ func (h *PollingRealnameHandler) Handle(ctx context.Context, t *asynq.Task) erro
if isNotFound(err) {
return nil
}
h.base.logger.Error("获取卡信息失败", zap.Uint("card_id", cardID), zap.Error(err))
h.base.updateStats(ctx, constants.TaskTypePollingRealname, false, time.Since(startTime))
return h.failAndRequeue(ctx, cardID, startedAt, "获取卡信息失败", err)
}
if card.CardCategory == constants.CardCategoryIndustry || h.gateway == nil {
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
}
if card.CardCategory == constants.CardCategoryIndustry {
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
attemptStartedAt := time.Now()
attempt, err := startGatewayAttempt(ctx, h.integration, cardID, constants.IntegrationOperationGatewayRealname, constants.CardObservationSceneRealnamePolling)
if err != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "建立 Gateway 实名 Integration Log 失败", err)
}
var newStatus int
var realStatusBool bool
if h.gateway != nil {
result, gwErr := h.gateway.QueryRealnameStatus(ctx, &gateway.CardStatusReq{CardNo: card.ICCID})
if gwErr != nil {
h.base.logger.Warn("查询实名状态失败",
zap.Uint("card_id", cardID), zap.String("iccid", card.ICCID), zap.Error(gwErr))
h.base.updateStats(ctx, constants.TaskTypePollingRealname, false, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
}
// 上游接口故障时 Gateway 可能返回 data=null
// sonic 将其解析为零值结构体ICCID="" RealStatus=false
// 需通过 ICCID 是否回填来判断响应是否有效。
if result.ICCID == "" {
h.base.logger.Warn("实名查询响应异常ICCID 为空,疑似上游接口故障,跳过本次同步",
zap.Uint("card_id", cardID),
zap.String("iccid", card.ICCID))
h.base.updateStats(ctx, constants.TaskTypePollingRealname, false, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
}
realStatusBool = result.RealStatus
if result.RealStatus {
newStatus = constants.RealNameStatusVerified
} else {
newStatus = constants.RealNameStatusNotVerified
}
if h.base.verboseLog {
h.base.logger.Info("实名状态轮询详情",
zap.Uint("card_id", cardID),
zap.String("iccid", card.ICCID),
zap.Bool("real_status", realStatusBool),
zap.Int("new_status", newStatus),
zap.Bool("changed", newStatus != card.RealNameStatus))
}
} else {
newStatus = card.RealNameStatus
result, err := h.gateway.QueryRealnameStatus(ctx, &gateway.CardStatusReq{CardNo: card.ICCID})
if err != nil {
_ = completeGatewayAttempt(ctx, h.integration, attempt, false, attemptStartedAt)
return h.failAndRequeue(ctx, cardID, startedAt, "查询实名状态失败", err)
}
if strings.TrimSpace(result.ICCID) == "" {
_ = completeGatewayAttempt(ctx, h.integration, attempt, false, attemptStartedAt)
return h.failAndRequeue(ctx, cardID, startedAt, "实名查询响应缺少 ICCID", nil)
}
if logErr := completeGatewayAttempt(ctx, h.integration, attempt, true, attemptStartedAt); logErr != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "完成 Gateway 实名 Integration Log 失败", logErr)
}
if h.observation == nil {
return h.failAndRequeue(ctx, cardID, startedAt, "卡实名观测能力未配置", nil)
}
statusChanged := newStatus != card.RealNameStatus
isFirstRealname := statusChanged &&
card.RealNameStatus != constants.RealNameStatusVerified &&
newStatus == constants.RealNameStatusVerified
now := time.Now()
fields := map[string]any{"last_real_name_check_at": now}
if h.gateway != nil {
fields["last_sync_time"] = now
decision, err := h.observation.ApplyCardObservation(ctx, carddomain.RealnameObservation{
CardID: cardID, Verified: result.RealStatus,
Metadata: carddomain.ObservationMetadata{
ObservationID: attempt.IntegrationID, Source: constants.CardObservationSourcePolling,
Scene: constants.CardObservationSceneRealnamePolling, ObservedAt: now, CorrelationID: attempt.IntegrationID,
},
})
if err != nil {
return h.failAndRequeue(ctx, cardID, startedAt, "应用实名观测失败", err)
}
if statusChanged {
fields["real_name_status"] = newStatus
if h.base.verboseLog {
h.base.logger.Info("实名状态轮询详情", zap.Uint("card_id", cardID), zap.String("iccid", card.ICCID),
zap.Bool("real_status", result.RealStatus), zap.Int("new_status", decision.AfterStatus),
zap.Bool("changed", decision.StatusChanged), zap.Bool("reversal_pending", decision.ReversalPending))
}
if isFirstRealname {
fields["first_realname_at"] = now
}
if err := h.iotCardStore.UpdateFields(ctx, cardID, fields); err != nil {
h.base.logger.Error("更新卡实名信息失败", zap.Uint("card_id", cardID), zap.Error(err))
h.base.invalidateCardCache(ctx, cardID)
h.base.updateStats(ctx, constants.TaskTypePollingRealname, false, time.Since(startTime))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
}
if statusChanged {
h.base.updateCardCache(ctx, cardID, map[string]any{"real_name_status": newStatus})
h.base.logger.Info("实名状态已变化",
zap.Uint("card_id", cardID),
zap.Int("old_status", card.RealNameStatus),
zap.Int("new_status", newStatus))
if isFirstRealname {
// 0→1 时清除逆转计数器
h.base.redis.Del(ctx, constants.RedisPollingRealnameReversalCountKey(cardID))
// 0→1首次实名触发套餐激活并立即复机评估不等待下一个 carddata/package 周期)
h.triggerFirstRealnameActivation(ctx, cardID)
h.triggerDeviceRealnameActivation(ctx, cardID)
if h.stopResumeSvc != nil {
freshCard, loadErr := h.iotCardStore.GetByID(ctx, cardID)
if loadErr == nil {
if evalErr := h.stopResumeSvc.EvaluateAndAct(ctx, freshCard); evalErr != nil {
h.base.logger.Warn("实名完成后触发复机评估失败",
zap.Uint("card_id", cardID), zap.Error(evalErr))
}
}
}
} else if newStatus == constants.RealNameStatusNotVerified {
reversalKey := constants.RedisPollingRealnameReversalCountKey(cardID)
count, incrErr := h.base.redis.Incr(ctx, reversalKey).Result()
if incrErr == nil {
h.base.redis.Expire(ctx, reversalKey, 10*time.Minute)
}
h.base.logger.Warn("检测到实名逆转",
zap.Uint("card_id", cardID),
zap.Int64("reversal_count", count),
zap.Int("threshold", constants.PollingRealnameReversalThreshold))
if count >= int64(constants.PollingRealnameReversalThreshold) {
h.base.redis.Del(ctx, reversalKey)
h.base.logger.Warn("实名逆转达到阈值,触发停机评估",
zap.Uint("card_id", cardID))
if h.stopResumeSvc != nil {
freshCard, loadErr := h.iotCardStore.GetByID(ctx, cardID)
if loadErr == nil {
if evalErr := h.stopResumeSvc.EvaluateAndAct(ctx, freshCard); evalErr != nil {
h.base.logger.Warn("实名逆转后触发停机评估失败",
zap.Uint("card_id", cardID), zap.Error(evalErr))
}
}
}
}
}
}
h.base.updateStats(ctx, constants.TaskTypePollingRealname, true, time.Since(startTime))
h.base.updateStats(ctx, constants.TaskTypePollingRealname, true, time.Since(startedAt))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
}
// triggerFirstRealnameActivation 首次实名后触发套餐激活任务
func (h *PollingRealnameHandler) triggerFirstRealnameActivation(ctx context.Context, cardID uint) {
if h.asynqClient == nil {
return
}
payload := map[string]any{
"carrier_type": "iot_card",
"carrier_id": cardID,
"activation_type": "realname",
"timestamp": time.Now().Unix(),
}
payloadBytes, err := sonic.Marshal(payload)
func (h *PollingRealnameHandler) failAndRequeue(ctx context.Context, cardID uint, startedAt time.Time, message string, err error) error {
fields := []zap.Field{zap.Uint("card_id", cardID)}
if err != nil {
h.base.logger.Warn("序列化首次实名激活任务载荷失败", zap.Uint("card_id", cardID), zap.Error(err))
return
}
task := asynq.NewTask(constants.TaskTypePackageFirstActivation, payloadBytes,
asynq.MaxRetry(3),
asynq.Timeout(60*time.Second),
asynq.Queue(constants.QueueForTaskType(constants.TaskTypePackageFirstActivation)),
)
if _, err := h.asynqClient.EnqueueContext(ctx, task); err != nil {
h.base.logger.Warn("提交首次实名激活任务失败", zap.Uint("card_id", cardID), zap.Error(err))
}
}
// triggerDeviceRealnameActivation 卡首次实名后,触发其所属设备的设备级套餐激活任务
// 若卡不属于任何设备(独立卡),静默跳过
func (h *PollingRealnameHandler) triggerDeviceRealnameActivation(ctx context.Context, cardID uint) {
if h.asynqClient == nil || h.deviceSimBindingStore == nil {
return
}
binding, err := h.deviceSimBindingStore.GetActiveBindingByCardID(ctx, cardID)
if err != nil {
if isNotFound(err) {
return
}
h.base.logger.Warn("查询卡绑定设备失败,跳过设备级套餐激活",
zap.Uint("card_id", cardID), zap.Error(err))
return
}
deviceID := binding.DeviceID
payload := map[string]any{
"carrier_type": "device",
"carrier_id": deviceID,
"activation_type": "realname",
"timestamp": time.Now().Unix(),
}
payloadBytes, err := sonic.Marshal(payload)
if err != nil {
h.base.logger.Warn("序列化设备实名激活任务载荷失败",
zap.Uint("card_id", cardID), zap.Uint("device_id", deviceID), zap.Error(err))
return
}
task := asynq.NewTask(constants.TaskTypePackageFirstActivation, payloadBytes,
asynq.MaxRetry(3),
asynq.Timeout(60*time.Second),
asynq.Queue(constants.QueueForTaskType(constants.TaskTypePackageFirstActivation)),
)
if _, err := h.asynqClient.EnqueueContext(ctx, task); err != nil {
h.base.logger.Warn("提交设备实名激活任务失败",
zap.Uint("card_id", cardID), zap.Uint("device_id", deviceID), zap.Error(err))
fields = append(fields, zap.Error(err))
}
h.base.logger.Warn(message, fields...)
h.base.updateStats(ctx, constants.TaskTypePollingRealname, false, time.Since(startedAt))
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingRealname)
}