All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m37s
- 轮询配置新增套餐状态、资产状态、重置日前窗口与窗口内流量间隔(迁移 248),间隔三态:正数按间隔、0 不检查、空继承 - 配置按 priority, id 排序合并;在库与已销售无套餐未匹配时告警不入队 - 新增优先级整体重排、匹配预览、立即重算到期时间(异步只提前)、分层统计与重置日前加密统计接口 - 已切换日快照计量的卡流量按观测时间归属,激活前用量只记已结算 - 订单购买与实名激活补齐资产级激活锁,激活前对已切换卡结算一次流量,失败只告警不阻塞,结算不触发通道阈值判定
172 lines
6.4 KiB
Go
172 lines
6.4 KiB
Go
package cardobservation
|
||
|
||
import (
|
||
"time"
|
||
|
||
"context"
|
||
"strconv"
|
||
"strings"
|
||
|
||
"go.uber.org/zap"
|
||
"gorm.io/gorm"
|
||
|
||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||
"github.com/break/junhong_cmp_fiber/pkg/config"
|
||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||
)
|
||
|
||
// 灰度名单中扣减载体的前缀。
|
||
const (
|
||
trafficCalcCarrierDevice = "device"
|
||
trafficCalcCarrierIotCard = "iot_card"
|
||
)
|
||
|
||
// TrafficCalcPolicy 判定卡是否走日快照计量算法,以及未切换卡是否写快照。
|
||
//
|
||
// 名单在进程启动时展开为内存卡集合,观测事务内只查内存、不查库;API 与全部 Worker 必须使用一致的配置。
|
||
// 零值策略等同于 off 模式且不写快照。
|
||
type TrafficCalcPolicy struct {
|
||
mode string
|
||
cards map[uint]struct{}
|
||
snapshotEnabled bool
|
||
}
|
||
|
||
// Switched 判定卡是否走日快照算法。
|
||
func (p *TrafficCalcPolicy) Switched(cardID uint) bool {
|
||
if p == nil {
|
||
return false
|
||
}
|
||
switch p.mode {
|
||
case config.TrafficCalcModeFull:
|
||
return true
|
||
case config.TrafficCalcModeGray:
|
||
_, ok := p.cards[cardID]
|
||
return ok
|
||
default:
|
||
return false
|
||
}
|
||
}
|
||
|
||
// SnapshotEnabled 判定未切换卡是否写日快照。
|
||
func (p *TrafficCalcPolicy) SnapshotEnabled() bool {
|
||
return p != nil && p.snapshotEnabled
|
||
}
|
||
|
||
// BuildTrafficCalcPolicy 按配置展开灰度名单:device 展开为当前绑定的全部卡;iot_card 实际使用设备套餐时
|
||
// 记录错误并跳过该项(不阻止启动)。展开查询失败时整体退回 off 模式,保证判定出错一律走卡表基线算法。
|
||
func BuildTrafficCalcPolicy(ctx context.Context, db *gorm.DB, cfg config.TrafficCalcConfig, logger *zap.Logger) *TrafficCalcPolicy {
|
||
if logger == nil {
|
||
logger = zap.NewNop()
|
||
}
|
||
policy := &TrafficCalcPolicy{mode: cfg.Mode, cards: map[uint]struct{}{}, snapshotEnabled: cfg.FlowSnapshotEnabled}
|
||
if cfg.Mode != config.TrafficCalcModeGray {
|
||
logger.Info("卡流量计量模式", zap.String("mode", cfg.Mode), zap.Bool("flow_snapshot_enabled", cfg.FlowSnapshotEnabled))
|
||
return policy
|
||
}
|
||
for _, item := range strings.Split(cfg.Cards, ",") {
|
||
item = strings.TrimSpace(item)
|
||
if item == "" {
|
||
continue
|
||
}
|
||
if err := policy.expandItem(ctx, db, item, logger); err != nil {
|
||
logger.Error("展开卡流量计量灰度名单失败,本进程全部卡走卡表基线算法", zap.String("item", item), zap.Error(err))
|
||
return &TrafficCalcPolicy{mode: config.TrafficCalcModeOff, snapshotEnabled: cfg.FlowSnapshotEnabled}
|
||
}
|
||
}
|
||
logger.Info("卡流量计量灰度名单已展开", zap.String("cards", cfg.Cards), zap.Int("card_count", len(policy.cards)))
|
||
return policy
|
||
}
|
||
|
||
// expandItem 展开一项扣减载体;格式非法或单卡实际用设备套餐时只记录错误并跳过,查询失败时返回错误。
|
||
func (p *TrafficCalcPolicy) expandItem(ctx context.Context, db *gorm.DB, item string, logger *zap.Logger) error {
|
||
kind, rawID, found := strings.Cut(item, ":")
|
||
id, parseErr := strconv.ParseUint(strings.TrimSpace(rawID), 10, 64)
|
||
if !found || parseErr != nil || id == 0 {
|
||
logger.Error("卡流量计量灰度名单项格式非法,已跳过", zap.String("item", item))
|
||
return nil
|
||
}
|
||
switch strings.TrimSpace(kind) {
|
||
case trafficCalcCarrierDevice:
|
||
var cardIDs []uint
|
||
if err := db.WithContext(ctx).Model(&model.DeviceSimBinding{}).
|
||
Where("device_id = ? AND bind_status = ?", id, constants.BindStatusBound).
|
||
Pluck("iot_card_id", &cardIDs).Error; err != nil {
|
||
return err
|
||
}
|
||
for _, cardID := range cardIDs {
|
||
p.cards[cardID] = struct{}{}
|
||
}
|
||
return nil
|
||
case trafficCalcCarrierIotCard:
|
||
usesDevice, err := cardUsesDevicePackage(ctx, db, uint(id))
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if usesDevice {
|
||
logger.Error("灰度名单中的单卡实际从设备套餐扣减,已跳过;请改为按设备整台切换", zap.String("item", item))
|
||
return nil
|
||
}
|
||
p.cards[uint(id)] = struct{}{}
|
||
return nil
|
||
default:
|
||
logger.Error("卡流量计量灰度名单项载体类型非法,已跳过", zap.String("item", item))
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// cardUsesDevicePackage 与套餐扣减的载体解析同口径:卡自身没有生效中套餐、且当前绑定设备有生效中套餐时,
|
||
// 卡的流量扣到设备套餐上。
|
||
func cardUsesDevicePackage(ctx context.Context, db *gorm.DB, cardID uint) (bool, error) {
|
||
ownActive, err := countActivePackages(ctx, db, "iot_card_id = ?", cardID, time.Time{})
|
||
if err != nil || ownActive > 0 {
|
||
return false, err
|
||
}
|
||
deviceID, bound, err := activeBoundDeviceID(ctx, db, cardID)
|
||
if err != nil || !bound {
|
||
return false, err
|
||
}
|
||
deviceActive, err := countActivePackages(ctx, db, "device_id = ?", deviceID, time.Time{})
|
||
return deviceActive > 0, err
|
||
}
|
||
|
||
// hasActivePackageForCard 判定卡本次增量是否有可扣的生效中套餐:卡自身或当前绑定设备存在生效中套餐。
|
||
// observedAt 非零时只认激活时间不晚于观测时间的生效套餐(流量按观测时间归属):
|
||
// 观测早于套餐激活的用量属于激活前,只记已结算、不扣新套餐;激活时间为空的历史套餐视为早已生效。
|
||
func hasActivePackageForCard(ctx context.Context, db *gorm.DB, cardID uint, observedAt time.Time) (bool, error) {
|
||
ownActive, err := countActivePackages(ctx, db, "iot_card_id = ?", cardID, observedAt)
|
||
if err != nil || ownActive > 0 {
|
||
return ownActive > 0, err
|
||
}
|
||
deviceID, bound, err := activeBoundDeviceID(ctx, db, cardID)
|
||
if err != nil || !bound {
|
||
return false, err
|
||
}
|
||
deviceActive, err := countActivePackages(ctx, db, "device_id = ?", deviceID, observedAt)
|
||
return deviceActive > 0, err
|
||
}
|
||
|
||
func countActivePackages(ctx context.Context, db *gorm.DB, carrierCondition string, carrierID uint, observedAt time.Time) (int64, error) {
|
||
var count int64
|
||
query := db.WithContext(ctx).Model(&model.PackageUsage{}).
|
||
Where(carrierCondition, carrierID).
|
||
Where("status = ?", constants.PackageUsageStatusActive)
|
||
if !observedAt.IsZero() {
|
||
query = query.Where("activated_at IS NULL OR activated_at <= ?", observedAt)
|
||
}
|
||
err := query.Count(&count).Error
|
||
return count, err
|
||
}
|
||
|
||
func activeBoundDeviceID(ctx context.Context, db *gorm.DB, cardID uint) (uint, bool, error) {
|
||
var deviceIDs []uint
|
||
if err := db.WithContext(ctx).Model(&model.DeviceSimBinding{}).
|
||
Where("iot_card_id = ? AND bind_status = ?", cardID, constants.BindStatusBound).
|
||
Limit(1).Pluck("device_id", &deviceIDs).Error; err != nil {
|
||
return 0, false, err
|
||
}
|
||
if len(deviceIDs) == 0 {
|
||
return 0, false, nil
|
||
}
|
||
return deviceIDs[0], true, nil
|
||
}
|