feat: 轮询观测入库异步化,调网关与入库分离,采集记录经消息攒批写入
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 16m2s

- 轮询步骤异步模式下只调网关并发布 card.ingest 入库消息,入库消费者固定并发 30、按采集 ID 去重、可重试错误不限次数退避重投
- 采集记录经 card.collection 攒批写入,失败整批重投,新增 (observation_id, observed_at) 唯一索引
- 网络、实名观测增加乱序保护;轮询读查询走缓存,套餐状态查询各自计时且失败不缓存
- 入库积压告警与反压;系统配置 polling.ingest.mode 默认 sync 可回退;测试环境 nsqd 消息全部落盘

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
邹进
2026-11-06 16:33:29 +09:00
parent 7e0e37933e
commit 1214181e78
41 changed files with 2007 additions and 46 deletions

View File

@@ -110,6 +110,12 @@ func (d *Dispatcher) Ready(ctx context.Context) bool {
return err == nil && state == InitStateDone
}
// ingestPaused 判断入库积压是否已触发反压:置位时暂停领取新卡任务(停复机指令照常分发)。
func (d *Dispatcher) ingestPaused(ctx context.Context) bool {
exists, err := d.store.redis.Exists(ctx, constants.RedisPollingIngestPausedKey).Result()
return err == nil && exists > 0
}
func (d *Dispatcher) tick(ctx context.Context, interval time.Duration) {
defer func() {
if r := recover(); r != nil {
@@ -118,7 +124,7 @@ func (d *Dispatcher) tick(ctx context.Context, interval time.Duration) {
}()
// 停复机指令与设备判断的分发只看停复机出口开关,不受 scheduler_mode 限制;卡任务只在新调度就绪时领取。
stopResumeOn := d.settings.Current(ctx).StopResumeQueueEnabled
cardsReady := d.Ready(ctx)
cardsReady := d.Ready(ctx) && !d.ingestPaused(ctx)
if !stopResumeOn && !cardsReady {
return
}

View File

@@ -27,6 +27,7 @@ func RegisterConfigDefinitions(registry *systemconfig.Registry, logger *zap.Logg
return
}
minZero, minOne, maxSeconds, maxCount := int64(0), int64(1), int64(86400*7), int64(100000)
maxDepth := int64(100000000)
definitions := []systemconfig.Definition{
{Key: constants.SystemConfigPollingSchedulerMode, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeString,
DefaultValue: constants.PollingSchedulerModeLegacy, Description: "卡轮询调度模式:legacy 旧分片调度,carrier 按运营商账户调度(整体切换)",
@@ -61,6 +62,13 @@ func RegisterConfigDefinitions(registry *systemconfig.Registry, logger *zap.Logg
DefaultValue: "5", Description: "停复机连续失败告警阈值", Min: &minOne, Max: &maxCount},
{Key: constants.SystemConfigStopResumeStatusGrace, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeInt,
DefaultValue: "300", Description: "停复机成功后的状态保护窗口(秒):窗口内查卡状态返回操作前的状态视为上游滞后,不回写;0 不保护", Min: &minZero, Max: &maxSeconds},
{Key: constants.SystemConfigPollingIngestMode, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeString,
DefaultValue: constants.PollingIngestModeSync, Description: "轮询观测入库模式:sync 卡任务内同步入库,async 只调网关并发布入库消息",
EnumValues: []string{constants.PollingIngestModeSync, constants.PollingIngestModeAsync}},
{Key: constants.SystemConfigPollingIngestAlertDepth, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeInt,
DefaultValue: strconv.Itoa(constants.PollingIngestDefaultAlertDepth), Description: "入库消息积压告警阈值(条)", Min: &minOne, Max: &maxDepth},
{Key: constants.SystemConfigPollingIngestPauseDepth, Module: constants.SystemConfigModulePolling, ValueType: constants.SystemConfigTypeInt,
DefaultValue: strconv.Itoa(constants.PollingIngestDefaultPauseDepth), Description: "入库消息积压反压阈值(条):超过时暂停派发新卡任务,降到一半以下恢复;须大于告警阈值", Min: &minOne, Max: &maxDepth},
}
for _, definition := range definitions {
if _, exists := registry.Get(definition.Key); exists {
@@ -205,6 +213,16 @@ type Settings struct {
SRBackoff []time.Duration
SRAlertFailCount int
SRStatusGrace time.Duration
// 轮询观测入库(add-polling-async-ingest)。
IngestMode string
IngestAlertDepth int
IngestPauseDepth int
}
// IngestAsync 判断轮询观测是否按异步入库执行。
func (s Settings) IngestAsync() bool {
return s.IngestMode == constants.PollingIngestModeAsync
}
// SRBackoffFor 返回停复机第 n 次连续失败(n 从 1 起)的退避间隔;超过序列长度取最后一项。
@@ -297,6 +315,9 @@ func DefaultSettings() Settings {
SRBackoff: []time.Duration{10 * time.Minute, 15 * time.Minute, 30 * time.Minute, time.Hour},
SRAlertFailCount: 5,
SRStatusGrace: 5 * time.Minute,
IngestMode: constants.PollingIngestModeSync,
IngestAlertDepth: constants.PollingIngestDefaultAlertDepth,
IngestPauseDepth: constants.PollingIngestDefaultPauseDepth,
}
}
@@ -421,6 +442,8 @@ func (p *SettingsProvider) load(ctx context.Context) (Settings, error) {
{constants.SystemConfigStopResumeUnknownAlert, func(v int) { s.SRUnknownAlert = v }},
{constants.SystemConfigStopResumeAlertFailCount, func(v int) { s.SRAlertFailCount = v }},
{constants.SystemConfigStopResumeStatusGrace, func(v int) { s.SRStatusGrace = time.Duration(v) * time.Second }},
{constants.SystemConfigPollingIngestAlertDepth, func(v int) { s.IngestAlertDepth = v }},
{constants.SystemConfigPollingIngestPauseDepth, func(v int) { s.IngestPauseDepth = v }},
}
for _, item := range ints {
raw, err := get(item.key)
@@ -448,6 +471,16 @@ func (p *SettingsProvider) load(ctx context.Context) (Settings, error) {
for _, value := range srBackoff {
s.SRBackoff = append(s.SRBackoff, time.Duration(value)*time.Second)
}
if raw, err = get(constants.SystemConfigPollingIngestMode); err != nil {
return s, err
}
s.IngestMode = raw
if s.IngestPauseDepth <= s.IngestAlertDepth {
// 反压阈值须大于告警阈值:配置不满足时按告警阈值的 2 倍执行并告警,避免还没告警就先停派发。
p.logger.Warn("入库反压阈值不大于告警阈值,按告警阈值的 2 倍执行",
zap.Int("alert_depth", s.IngestAlertDepth), zap.Int("pause_depth", s.IngestPauseDepth))
s.IngestPauseDepth = s.IngestAlertDepth * 2
}
return s, nil
}

View File

@@ -188,9 +188,8 @@ func (m *PollingConfigManager) lazyTierFacts(card *model.IotCard) func() TierFac
return func() TierFacts {
once.Do(func() {
if m.tier != nil {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
facts = m.tier.Resolve(ctx, card)
// 每次查询在解析器内单独计时,避免一张绑定设备的卡连查多次时共用一个超时。
facts = m.tier.Resolve(context.Background(), card)
}
})
return facts

View File

@@ -156,6 +156,16 @@ func (m *PollingQueueManager) EnqueueManual(ctx context.Context, cardID uint, ta
// 使用 RPUSH 与调度器的 LPopCount 组成先进先出;提示通道不是权威,丢失或缓存服务重启时
// 库内活动优先项仍在,后续普通轮询执行按条件认领仍会执行,只退化为延迟一个普通轮询周期。
func (m *PollingQueueManager) EnqueuePriority(ctx context.Context, cardID uint, taskType string) error {
// 同时登记活动优先项索引(轮询步骤据此跳过无优先项卡的查库);recent 集合供索引重建时并入,避免重建期间漏掉新项。
member := constants.PollingPriorityIndexMember(cardID, taskType)
pipe := m.redis.Pipeline()
pipe.SAdd(ctx, constants.RedisPollingPriorityActiveKey, member)
pipe.SAdd(ctx, constants.RedisPollingPriorityRecentKey, member)
pipe.Expire(ctx, constants.RedisPollingPriorityRecentKey, constants.PollingPriorityIndexRecentTTL)
if _, err := pipe.Exec(ctx); err != nil {
m.logger.Warn("登记活动优先项索引失败,轮询步骤将在索引重建后发现该项", zap.Uint("card_id", cardID),
zap.String("task_type", taskType), zap.Error(err))
}
key := constants.RedisPollingPriorityQueueKey(taskType)
return m.redis.RPush(ctx, key, fmt.Sprintf("%d", cardID)).Err()
}

View File

@@ -76,7 +76,7 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
}
results := make(map[uint]TierFacts, len(cards))
if len(standaloneIDs) > 0 {
states, err := r.usage.PackageStatesByCarriers(ctx, constants.AssetTypeIotCard, standaloneIDs)
states, err := r.packageStates(ctx, constants.AssetTypeIotCard, standaloneIDs)
if err != nil {
r.logger.Warn("批量查询卡套餐状态失败,相关卡本次不按套餐状态匹配", zap.Error(err))
}
@@ -87,7 +87,9 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
}
}
if len(boundCardIDs) > 0 && r.bindings != nil {
bindings, err := r.bindings.GetActiveBindingsByCardIDs(ctx, boundCardIDs)
bindCtx, cancel := context.WithTimeout(ctx, constants.PollingTierQueryTimeout)
bindings, err := r.bindings.GetActiveBindingsByCardIDs(bindCtx, boundCardIDs)
cancel()
if err != nil {
r.logger.Warn("批量查询卡绑定设备失败,相关卡本次不按套餐状态匹配", zap.Error(err))
} else {
@@ -97,8 +99,8 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
deviceOf[binding.IotCardID] = binding.DeviceID
deviceIDs = append(deviceIDs, binding.DeviceID)
}
deviceStates, devErr := r.usage.PackageStatesByCarriers(ctx, constants.AssetTypeDevice, deviceIDs)
cardStates, cardErr := r.usage.PackageStatesByCarriers(ctx, constants.AssetTypeIotCard, boundCardIDs)
deviceStates, devErr := r.packageStates(ctx, constants.AssetTypeDevice, deviceIDs)
cardStates, cardErr := r.packageStates(ctx, constants.AssetTypeIotCard, boundCardIDs)
for _, id := range boundCardIDs {
// 有有效设备绑定按设备计算;绑定已失效的卡按卡自身计算(与 resolvePackageCarrier 口径一致)。
if deviceID, bound := deviceOf[id]; bound {
@@ -111,17 +113,22 @@ func (r *TierResolver) Prefill(ctx context.Context, cards []*model.IotCard) {
}
}
}
// 只缓存查询成功的卡:查询失败的卡本次按未知处理,下次重新查询,不把"未知"留在缓存里。
now := time.Now()
r.mu.Lock()
for _, card := range cards {
if card == nil {
continue
}
r.cache[card.ID] = tierCacheEntry{facts: results[card.ID], loadedAt: now}
for id, facts := range results {
r.cache[id] = tierCacheEntry{facts: facts, loadedAt: now}
}
r.mu.Unlock()
}
// packageStates 以单独的超时查询一批载体的套餐状态,避免多次查询共用一个超时。
func (r *TierResolver) packageStates(ctx context.Context, carrierType string, ids []uint) (map[uint]string, error) {
queryCtx, cancel := context.WithTimeout(ctx, constants.PollingTierQueryTimeout)
defer cancel()
return r.usage.PackageStatesByCarriers(queryCtx, carrierType, ids)
}
// Invalidate 清除某卡的分层事实缓存(套餐变化后可调用,未调用时最迟缓存过期后更新)。
func (r *TierResolver) Invalidate(cardID uint) {
if r == nil {