收口七月卡状态回调与系列授权兼容契约
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Has been cancelled
完成运营商实名回调、业务事件观测序列与受控配置装配,同时恢复 UR43 已交付的 packages[].remove 字段及旧响应兼容,统一更新 OpenSpec、OpenAPI 和交付文档。 Constraint: 七月测试环境里程碑不新增或运行自动化测试 Rejected: 以必填 operation_type 替换 packages[].remove | 会破坏已交付前端契约 Confidence: high Scope-risk: broad Directive: 后续修改系列套餐管理接口必须保持 packages[].remove 和 ShopSeriesGrantResponse 兼容 Tested: go run ./cmd/gendocs;go build -buildvcs=false ./...;openspec validate complete-july-iteration-test-release --strict;git diff --check Not-tested: 按本 Change 约定未运行 go test,真实运营商与 Gateway 联调延期
This commit is contained in:
@@ -3,6 +3,7 @@ package task
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/bytedance/sonic"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
cardObservationApp "github.com/break/junhong_cmp_fiber/internal/application/cardobservation"
|
||||
packagedomain "github.com/break/junhong_cmp_fiber/internal/domain/package"
|
||||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||||
packagepkg "github.com/break/junhong_cmp_fiber/internal/service/package"
|
||||
@@ -41,6 +43,7 @@ type AutoPurchaseHandler struct {
|
||||
redis *redis.Client
|
||||
asynqClient *asynq.Client // 用于事务提交成功后触发佣金计算任务
|
||||
logger *zap.Logger
|
||||
observationSeriesEvents cardObservationApp.SeriesEventWriter
|
||||
}
|
||||
|
||||
// NewAutoPurchaseHandler 创建充值后自动购包处理器
|
||||
@@ -55,6 +58,7 @@ func NewAutoPurchaseHandler(
|
||||
redisClient *redis.Client,
|
||||
asynqClient *asynq.Client,
|
||||
logger *zap.Logger,
|
||||
observationSeriesEvents cardObservationApp.SeriesEventWriter,
|
||||
) *AutoPurchaseHandler {
|
||||
if orderStore == nil {
|
||||
orderStore = postgres.NewOrderStore(db, redisClient)
|
||||
@@ -89,6 +93,7 @@ func NewAutoPurchaseHandler(
|
||||
redis: redisClient,
|
||||
asynqClient: asynqClient,
|
||||
logger: logger,
|
||||
observationSeriesEvents: observationSeriesEvents,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +253,23 @@ func (h *AutoPurchaseHandler) ProcessTask(ctx context.Context, task *asynq.Task)
|
||||
if err = h.activatePackages(ctx, tx, order, packages, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if h.observationSeriesEvents == nil {
|
||||
return pkgerrors.New(pkgerrors.CodeInternalError, "自动购包观测 Outbox Writer 未配置")
|
||||
}
|
||||
resourceType, resourceID := orderObservationResource(order)
|
||||
if resourceID == 0 {
|
||||
return pkgerrors.New(pkgerrors.CodeInvalidParam, "自动购包观测事件缺少载体")
|
||||
}
|
||||
requestID := "card-observation:auto-purchase:" + strconv.FormatUint(uint64(order.ID), 10)
|
||||
if err = h.observationSeriesEvents.AppendSeriesRequested(ctx, tx, cardObservationApp.SeriesRequestedEvent{
|
||||
EventID: requestID, Scene: constants.CardObservationScenePackageChanged,
|
||||
ResourceType: resourceType, ResourceID: resourceID,
|
||||
SyncTypes: []string{constants.CardObservationSyncTypeRealname, constants.CardObservationSyncTypeTraffic, constants.CardObservationSyncTypeNetwork},
|
||||
Source: constants.CardObservationSourceBusinessEvent, OccurredAt: now,
|
||||
RequestID: requestID, CorrelationID: requestID,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = tx.Model(&model.RechargeOrder{}).
|
||||
Where("id = ?", rechargeOrder.ID).
|
||||
@@ -289,6 +311,16 @@ func (h *AutoPurchaseHandler) ProcessTask(ctx context.Context, task *asynq.Task)
|
||||
return nil
|
||||
}
|
||||
|
||||
func orderObservationResource(order *model.Order) (string, uint) {
|
||||
if order != nil && order.DeviceID != nil {
|
||||
return constants.CardObservationResourceTypeDevice, *order.DeviceID
|
||||
}
|
||||
if order != nil && order.IotCardID != nil {
|
||||
return constants.CardObservationResourceTypeCard, *order.IotCardID
|
||||
}
|
||||
return "", 0
|
||||
}
|
||||
|
||||
// NewAutoPurchaseTask 创建充值后自动购包任务
|
||||
func NewAutoPurchaseTask(rechargeOrderID uint) (*asynq.Task, error) {
|
||||
payloadBytes, err := sonic.Marshal(AutoPurchasePayload{RechargeOrderID: rechargeOrderID})
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/break/junhong_cmp_fiber/internal/infrastructure/cardtrafficlock"
|
||||
"github.com/break/junhong_cmp_fiber/internal/polling"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
@@ -28,7 +29,6 @@ var acquireConcurrencyScript = redis.NewScript(`
|
||||
return current
|
||||
`)
|
||||
|
||||
const cardTrafficSyncLockTTL = 10 * time.Minute
|
||||
const pollingFallbackOperationTimeout = 5 * time.Second
|
||||
|
||||
// pollingFallbackContext 创建轮询兜底操作使用的独立短超时上下文。
|
||||
@@ -47,6 +47,7 @@ type PollingBase struct {
|
||||
iotCardStore *postgres.IotCardStore
|
||||
logger *zap.Logger
|
||||
verboseLog bool
|
||||
trafficLock *cardtrafficlock.Lock
|
||||
}
|
||||
|
||||
// NewPollingBase 创建轮询共享基类
|
||||
@@ -65,6 +66,7 @@ func NewPollingBase(
|
||||
iotCardStore: iotCardStore,
|
||||
logger: logger,
|
||||
verboseLog: verboseLog,
|
||||
trafficLock: cardtrafficlock.New(redisClient),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,26 +107,16 @@ func (b *PollingBase) releaseConcurrency(_ context.Context, taskType string) {
|
||||
}
|
||||
|
||||
// acquireCardTrafficSyncLock 获取卡流量同步锁,避免轮询与手动刷新重复统计同一上游读数。
|
||||
func (b *PollingBase) acquireCardTrafficSyncLock(ctx context.Context, cardID uint) (bool, error) {
|
||||
if b.redis == nil {
|
||||
return true, nil
|
||||
}
|
||||
locked, err := b.redis.SetNX(ctx, constants.RedisCardTrafficSyncLockKey(cardID), "1", cardTrafficSyncLockTTL).Result()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return locked, nil
|
||||
func (b *PollingBase) acquireCardTrafficSyncLock(ctx context.Context, cardID uint) (string, bool, error) {
|
||||
return b.trafficLock.Acquire(ctx, cardID)
|
||||
}
|
||||
|
||||
// releaseCardTrafficSyncLock 释放卡流量同步锁。
|
||||
func (b *PollingBase) releaseCardTrafficSyncLock(_ context.Context, cardID uint) {
|
||||
if b.redis == nil {
|
||||
return
|
||||
}
|
||||
func (b *PollingBase) releaseCardTrafficSyncLock(_ context.Context, cardID uint, token string) {
|
||||
ctx, cancel := pollingFallbackContext()
|
||||
defer cancel()
|
||||
|
||||
if err := b.redis.Del(ctx, constants.RedisCardTrafficSyncLockKey(cardID)).Err(); err != nil {
|
||||
if err := b.trafficLock.Release(ctx, cardID, token); err != nil {
|
||||
b.logger.Warn("释放卡流量同步锁失败", zap.Uint("card_id", cardID), zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,12 @@ func (h *PollingCarddataHandler) Handle(ctx context.Context, task *asynq.Task) e
|
||||
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingCarddata)
|
||||
}
|
||||
defer h.base.releaseConcurrency(ctx, constants.TaskTypePollingCarddata)
|
||||
locked, err := h.base.acquireCardTrafficSyncLock(ctx, cardID)
|
||||
lockToken, 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)
|
||||
defer h.base.releaseCardTrafficSyncLock(ctx, cardID, lockToken)
|
||||
|
||||
h.base.invalidateCardCache(ctx, cardID)
|
||||
card, err := h.base.iotCardStore.GetByID(ctx, cardID)
|
||||
|
||||
@@ -2,15 +2,20 @@ package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
cardObservationApp "github.com/break/junhong_cmp_fiber/internal/application/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"
|
||||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||||
)
|
||||
|
||||
// PollingProtectHandler 保护期一致性检查任务处理器
|
||||
@@ -18,15 +23,19 @@ import (
|
||||
// 保护期结束:调 EvaluateAndAct 重新评估正常停复机条件
|
||||
// 两种路径不可混淆:保护期内=强制修正;保护期结束=重新评估
|
||||
type PollingProtectHandler struct {
|
||||
base *PollingBase
|
||||
gateway *gateway.Client
|
||||
iotCardStore *postgres.IotCardStore
|
||||
deviceSimBindingStore *postgres.DeviceSimBindingStore
|
||||
stopResumeSvc iot_card_svc.StopResumeServiceInterface
|
||||
db *gorm.DB
|
||||
observationSeriesEvents cardObservationApp.SeriesEventWriter
|
||||
base *PollingBase
|
||||
gateway *gateway.Client
|
||||
iotCardStore *postgres.IotCardStore
|
||||
deviceSimBindingStore *postgres.DeviceSimBindingStore
|
||||
stopResumeSvc iot_card_svc.StopResumeServiceInterface
|
||||
}
|
||||
|
||||
// NewPollingProtectHandler 创建保护期一致性检查任务处理器
|
||||
func NewPollingProtectHandler(
|
||||
db *gorm.DB,
|
||||
observationSeriesEvents cardObservationApp.SeriesEventWriter,
|
||||
base *PollingBase,
|
||||
gw *gateway.Client,
|
||||
iotCardStore *postgres.IotCardStore,
|
||||
@@ -34,11 +43,13 @@ func NewPollingProtectHandler(
|
||||
stopResumeSvc iot_card_svc.StopResumeServiceInterface,
|
||||
) *PollingProtectHandler {
|
||||
return &PollingProtectHandler{
|
||||
base: base,
|
||||
gateway: gw,
|
||||
iotCardStore: iotCardStore,
|
||||
deviceSimBindingStore: deviceSimBindingStore,
|
||||
stopResumeSvc: stopResumeSvc,
|
||||
db: db,
|
||||
observationSeriesEvents: observationSeriesEvents,
|
||||
base: base,
|
||||
gateway: gw,
|
||||
iotCardStore: iotCardStore,
|
||||
deviceSimBindingStore: deviceSimBindingStore,
|
||||
stopResumeSvc: stopResumeSvc,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,8 +93,10 @@ func (h *PollingProtectHandler) Handle(ctx context.Context, t *asynq.Task) error
|
||||
}
|
||||
deviceID := binding.DeviceID
|
||||
|
||||
stopProtect := h.base.redis.Exists(ctx, constants.RedisDeviceProtectKey(deviceID, "stop")).Val() > 0
|
||||
startProtect := h.base.redis.Exists(ctx, constants.RedisDeviceProtectKey(deviceID, "start")).Val() > 0
|
||||
stopProtectGeneration := h.base.redis.Get(ctx, constants.RedisDeviceProtectKey(deviceID, "stop")).Val()
|
||||
startProtectGeneration := h.base.redis.Get(ctx, constants.RedisDeviceProtectKey(deviceID, "start")).Val()
|
||||
stopProtect := stopProtectGeneration != ""
|
||||
startProtect := startProtectGeneration != ""
|
||||
|
||||
actionTaken := "no_action"
|
||||
|
||||
@@ -101,15 +114,18 @@ func (h *PollingProtectHandler) Handle(ctx context.Context, t *asynq.Task) error
|
||||
h.base.updateStats(ctx, constants.TaskTypePollingProtect, false, time.Since(startTime))
|
||||
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingProtect)
|
||||
}
|
||||
if updateErr := h.iotCardStore.UpdateFields(ctx, cardID, map[string]any{
|
||||
if updateErr := h.updateCardAndAppendNetworkSeries(ctx, cardID, map[string]any{
|
||||
"network_status": constants.NetworkStatusOffline,
|
||||
"stopped_at": time.Now(),
|
||||
"stop_reason": constants.StopReasonProtectPeriod,
|
||||
}); updateErr != nil {
|
||||
}, constants.CardObservationSceneBusinessStop, "offline", "stop", stopProtectGeneration); updateErr != nil {
|
||||
h.base.logger.Warn("保护期停机 DB 更新失败", zap.Uint("card_id", cardID), zap.Error(updateErr))
|
||||
h.base.invalidateCardCache(ctx, cardID)
|
||||
h.base.updateStats(ctx, constants.TaskTypePollingProtect, false, time.Since(startTime))
|
||||
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingProtect)
|
||||
if requeueErr := h.base.requeueCard(ctx, cardID, constants.TaskTypePollingProtect); requeueErr != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, requeueErr, "保护期停机事务失败且重入队失败")
|
||||
}
|
||||
return updateErr
|
||||
}
|
||||
h.base.updateCardCache(ctx, cardID, map[string]any{"network_status": constants.NetworkStatusOffline})
|
||||
actionTaken = "forced_stop"
|
||||
@@ -127,15 +143,18 @@ func (h *PollingProtectHandler) Handle(ctx context.Context, t *asynq.Task) error
|
||||
h.base.updateStats(ctx, constants.TaskTypePollingProtect, false, time.Since(startTime))
|
||||
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingProtect)
|
||||
}
|
||||
if updateErr := h.iotCardStore.UpdateFields(ctx, cardID, map[string]any{
|
||||
if updateErr := h.updateCardAndAppendNetworkSeries(ctx, cardID, map[string]any{
|
||||
"network_status": constants.NetworkStatusOnline,
|
||||
"resumed_at": time.Now(),
|
||||
"stop_reason": "",
|
||||
}); updateErr != nil {
|
||||
}, constants.CardObservationSceneBusinessResume, "online", "start", startProtectGeneration); updateErr != nil {
|
||||
h.base.logger.Warn("保护期复机 DB 更新失败", zap.Uint("card_id", cardID), zap.Error(updateErr))
|
||||
h.base.invalidateCardCache(ctx, cardID)
|
||||
h.base.updateStats(ctx, constants.TaskTypePollingProtect, false, time.Since(startTime))
|
||||
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingProtect)
|
||||
if requeueErr := h.base.requeueCard(ctx, cardID, constants.TaskTypePollingProtect); requeueErr != nil {
|
||||
return errors.Wrap(errors.CodeInternalError, requeueErr, "保护期复机事务失败且重入队失败")
|
||||
}
|
||||
return updateErr
|
||||
}
|
||||
h.base.updateCardCache(ctx, cardID, map[string]any{"network_status": constants.NetworkStatusOnline})
|
||||
actionTaken = "forced_resume"
|
||||
@@ -170,3 +189,35 @@ func (h *PollingProtectHandler) Handle(ctx context.Context, t *asynq.Task) error
|
||||
h.base.updateStats(ctx, constants.TaskTypePollingProtect, true, time.Since(startTime))
|
||||
return h.base.requeueCard(ctx, cardID, constants.TaskTypePollingProtect)
|
||||
}
|
||||
|
||||
// updateCardAndAppendNetworkSeries 在同一事务中更新卡状态并写入网络观测请求。
|
||||
func (h *PollingProtectHandler) updateCardAndAppendNetworkSeries(
|
||||
ctx context.Context,
|
||||
cardID uint,
|
||||
fields map[string]any,
|
||||
scene string,
|
||||
expected string,
|
||||
operation string,
|
||||
protectGeneration string,
|
||||
) error {
|
||||
if h.db == nil || h.observationSeriesEvents == nil {
|
||||
return errors.New(errors.CodeInternalError, "保护期停复机观测 Outbox 能力未配置")
|
||||
}
|
||||
if protectGeneration == "" {
|
||||
return errors.New(errors.CodeInvalidParam, "保护期停复机事件缺少保护期标识")
|
||||
}
|
||||
requestID := "card-observation:polling-protect:" + operation + ":" +
|
||||
strconv.FormatUint(uint64(cardID), 10) + ":" + protectGeneration
|
||||
return h.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&model.IotCard{}).Where("id = ?", cardID).Updates(fields).Error; err != nil {
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "更新保护期停复机卡状态失败")
|
||||
}
|
||||
return h.observationSeriesEvents.AppendSeriesRequested(ctx, tx, cardObservationApp.SeriesRequestedEvent{
|
||||
EventID: requestID, Scene: scene,
|
||||
ResourceType: constants.CardObservationResourceTypeCard, ResourceID: cardID,
|
||||
SyncTypes: []string{constants.CardObservationSyncTypeNetwork}, ExpectedValue: expected,
|
||||
Source: constants.CardObservationSourceBusinessEvent, OccurredAt: time.Now().UTC(),
|
||||
RequestID: requestID, CorrelationID: requestID,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user