All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m46s
【核心变更】
1. 停复机逻辑统一(StopResumeService)
- 新增 EvaluateAndAct 统一入口,封装三条件停复机判断
- 停机条件:无套餐(no_package) / 流量耗尽(traffic_exhausted) / 未实名(not_realname)
- 复机条件:stop_reason 合规 + 有套餐且未耗尽 + 已实名或行业卡
- 修复设备套餐 Bug:hasValidPackage 按 device_id 查套餐,而非仅 iot_card_id
- 设备维度停复机加幂等锁(Redis SetNX,TTL 30s),防止多卡并发重复调 Gateway
2. Redis 分片队列(PollingQueueManager)
- 新建 queue_manager.go,封装所有轮询 Redis 操作
- 16 分片 Sorted Set,Key 格式:polling:shard:{shardID}:queue:{taskType}
- Lua 脚本原子出队(ZRANGEBYSCORE + 分批 ZREM),消除竞态窗口
- 新增背压检测:队列深度超 50 万时 Scheduler 跳过该分片
- RemoveFromAllQueues 覆盖 4 种任务类型(含 protect)
3. Handler 拆分(polling_handler.go 1360行 → 5个专注文件)
- polling_base.go:共享基类(并发控制/卡缓存/重入队)
- polling_realname_handler.go:实名采集,实名 0→1 时立即触发复机
- polling_carddata_handler.go:流量采集,保留跨月边界检测逻辑
- polling_package_handler.go:套餐采集,委托 EvaluateAndAct 决策
- polling_protect_handler.go:保护期一致性检查,保护期内强制修正
4. 配置管理(PollingConfigManager)
- 新建 config_manager.go,从 scheduler.go 提取配置职责
- 内存缓存 + 5 分钟定时刷新,刷新失败保留原缓存
- 修复 getCardCondition:停机卡返回 suspended,不再错配 activated 配置
5. 渐进式初始化(CardInitializer)
- 新建 initializer.go,分批加载(每批 10 万),批次间 sleep 500ms
- 过滤 enable_polling=false 的卡,初始化完成前 Scheduler 不出队
6. 卡生命周期服务(PollingLifecycleService)
- 新建 lifecycle_service.go,替代已删除的 callbacks.go 和 api_callback.go
- OnCardCreated/OnCardEnabled/OnCardStatusChanged 入队前检查 enable_polling
7. Scheduler 精简(1000+行 → 227行)
- 保留纯调度循环:scheduleLoop + processShardSchedule + enqueueBatch
- 保留每 10 秒触发套餐过期检测和流量重置
- 移除所有 DB 操作、配置加载、卡初始化逻辑
8. 轮询管控 API(enable_polling)
- 新增 PUT /api/admin/assets/:id/polling-status 接口
- 支持对设备/卡维度开关轮询,关闭后从所有分片队列移除
9. 数据库迁移
- 000103:tb_device 新增 enable_polling 字段(boolean, NOT NULL, DEFAULT true)
- 000104:新增 suspended 轮询配置,为 activated 配置补全 protect_check_interval
【文件统计】
- 新增:19 个文件(handler × 5、polling 组件 × 4、迁移 × 3 等)
- 修改:20 个文件(bootstrap 注入、store 接口、monitoring 适配分片等)
- 删除:3 个文件(polling_handler.go、callbacks.go、api_callback.go)
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
153 lines
4.3 KiB
Go
153 lines
4.3 KiB
Go
package polling
|
||
|
||
import (
|
||
"context"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/bytedance/sonic"
|
||
"github.com/redis/go-redis/v9"
|
||
"go.uber.org/zap"
|
||
|
||
"github.com/break/junhong_cmp_fiber/internal/model"
|
||
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
|
||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||
)
|
||
|
||
// PollingConfigManager 轮询配置管理器
|
||
// 从 DB 加载 tb_polling_config,同步到 Redis Hash,内存缓存(读写锁)
|
||
// 5 分钟定时自动刷新;加载失败时保留原缓存不清空
|
||
type PollingConfigManager struct {
|
||
configStore *postgres.PollingConfigStore
|
||
redis *redis.Client
|
||
logger *zap.Logger
|
||
|
||
mu sync.RWMutex
|
||
configs []*model.PollingConfig
|
||
refreshOnce sync.Once
|
||
}
|
||
|
||
// NewPollingConfigManager 创建配置管理器
|
||
func NewPollingConfigManager(configStore *postgres.PollingConfigStore, redisClient *redis.Client, logger *zap.Logger) *PollingConfigManager {
|
||
return &PollingConfigManager{
|
||
configStore: configStore,
|
||
redis: redisClient,
|
||
logger: logger,
|
||
}
|
||
}
|
||
|
||
// Load 加载配置到内存缓存并同步到 Redis
|
||
// 加载失败时保留原缓存不清空,确保可用性
|
||
func (m *PollingConfigManager) Load(ctx context.Context) error {
|
||
configs, err := m.configStore.ListEnabled(ctx)
|
||
if err != nil {
|
||
m.logger.Error("加载轮询配置失败", zap.Error(err))
|
||
return err
|
||
}
|
||
|
||
m.mu.Lock()
|
||
m.configs = configs
|
||
m.mu.Unlock()
|
||
|
||
if syncErr := m.syncToRedis(ctx, configs); syncErr != nil {
|
||
m.logger.Warn("同步配置到 Redis 失败", zap.Error(syncErr))
|
||
}
|
||
|
||
m.logger.Info("轮询配置已加载", zap.Int("count", len(configs)))
|
||
return nil
|
||
}
|
||
|
||
// Start 启动定时刷新(每 5 分钟自动 Load 一次)
|
||
// 使用 sync.Once 确保只启动一个刷新 goroutine
|
||
func (m *PollingConfigManager) Start(ctx context.Context) {
|
||
m.refreshOnce.Do(func() {
|
||
go func() {
|
||
ticker := time.NewTicker(5 * time.Minute)
|
||
defer ticker.Stop()
|
||
m.logger.Info("配置管理器已启动,5分钟自动刷新")
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
case <-ticker.C:
|
||
if err := m.Load(ctx); err != nil {
|
||
m.logger.Warn("定时刷新轮询配置失败,保留原配置", zap.Error(err))
|
||
}
|
||
}
|
||
}
|
||
}()
|
||
})
|
||
}
|
||
|
||
// MatchConfig 按优先级匹配第一个符合条件的轮询配置
|
||
// 配置按 priority ASC 排序(DB 层保证),数字越小优先级越高
|
||
func (m *PollingConfigManager) MatchConfig(card *model.IotCard) *model.PollingConfig {
|
||
m.mu.RLock()
|
||
defer m.mu.RUnlock()
|
||
|
||
for _, cfg := range m.configs {
|
||
if matchConfigConditions(cfg, card) {
|
||
return cfg
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// matchConfigConditions 检查卡是否满足配置的匹配条件
|
||
func matchConfigConditions(cfg *model.PollingConfig, card *model.IotCard) bool {
|
||
if cfg.CardCondition != "" {
|
||
if cfg.CardCondition != getCardCondition(card) {
|
||
return false
|
||
}
|
||
}
|
||
if cfg.CardCategory != "" {
|
||
if cfg.CardCategory != card.CardCategory {
|
||
return false
|
||
}
|
||
}
|
||
if cfg.CarrierID != nil {
|
||
if *cfg.CarrierID != card.CarrierID {
|
||
return false
|
||
}
|
||
}
|
||
return true
|
||
}
|
||
|
||
// getCardCondition 获取卡的状态条件(用于匹配轮询配置)
|
||
// ⚠️ 注意判断顺序:停机优先,避免停机卡错误匹配 activated 或 not_real_name 配置
|
||
// 停机卡需要继续轮询 carddata/package 以检测复机条件(套餐购买、流量重置、实名完成)
|
||
func getCardCondition(card *model.IotCard) string {
|
||
if card.NetworkStatus == constants.NetworkStatusOffline {
|
||
return "suspended"
|
||
}
|
||
if card.RealNameStatus != constants.RealNameStatusVerified {
|
||
return "not_real_name"
|
||
}
|
||
return "activated"
|
||
}
|
||
|
||
// syncToRedis 将配置同步到 Redis Hash(TTL 24h)
|
||
func (m *PollingConfigManager) syncToRedis(ctx context.Context, configs []*model.PollingConfig) error {
|
||
if len(configs) == 0 {
|
||
return nil
|
||
}
|
||
key := constants.RedisPollingConfigsCacheKey()
|
||
configData := make([]interface{}, 0, len(configs)*2)
|
||
for _, cfg := range configs {
|
||
jsonData, err := sonic.Marshal(cfg)
|
||
if err != nil {
|
||
m.logger.Warn("序列化轮询配置失败", zap.Uint("config_id", cfg.ID), zap.Error(err))
|
||
continue
|
||
}
|
||
configData = append(configData, cfg.ID, string(jsonData))
|
||
}
|
||
if len(configData) == 0 {
|
||
return nil
|
||
}
|
||
pipe := m.redis.Pipeline()
|
||
pipe.HSet(ctx, key, configData...)
|
||
pipe.Expire(ctx, key, 24*time.Hour)
|
||
_, err := pipe.Exec(ctx)
|
||
return err
|
||
}
|