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

@@ -47,6 +47,10 @@ func (p *Producer) Stop() {
// Handler 处理一条消息;返回后由管理器 FIN。消息处理期间可调用 touch 延长 NSQ 消息超时。
type Handler func(ctx context.Context, body []byte, touch func())
// RetryHandler 处理一条消息并决定是否重投:返回 0 表示 FIN,返回正数表示按该延迟重投(REQ,不计 NSQ 退避)。
// attempts 是 NSQ 记录的投递次数(含本次,从 1 起)。
type RetryHandler func(ctx context.Context, body []byte, attempts uint16, touch func()) time.Duration
// ConsumerConfig 是消费者参数。
type ConsumerConfig struct {
NSQDAddress string
@@ -55,14 +59,17 @@ type ConsumerConfig struct {
MaxAttempts uint16
// LookupdPollInterval 消费者向 nsqlookupd 查询 nsqd 的间隔;0 表示 15 秒。
LookupdPollInterval time.Duration
// UnlimitedAttempts 为 true 时不限投递次数(忽略 MaxAttempts),用于不允许丢弃的入库消息。
UnlimitedAttempts bool
}
// ConsumerManager 按 topic 动态订阅与取消订阅;每个 topic 一个消费者,max_in_flight 控制本进程对该 topic 的并发。
type ConsumerManager struct {
cfg ConsumerConfig
channel string
handler Handler
logger *zap.Logger
cfg ConsumerConfig
channel string
handler Handler
retryHandler RetryHandler
logger *zap.Logger
mu sync.Mutex
consumers map[string]*subscription
@@ -86,6 +93,13 @@ func NewConsumerManager(cfg ConsumerConfig, channel string, handler Handler, log
consumers: map[string]*subscription{}, ctx: ctx, cancel: cancel}
}
// NewRetryConsumerManager 创建由处理结果决定 FIN 或延迟重投的消费者管理器。
func NewRetryConsumerManager(cfg ConsumerConfig, channel string, handler RetryHandler, logger *zap.Logger) *ConsumerManager {
manager := NewConsumerManager(cfg, channel, nil, logger)
manager.retryHandler = handler
return manager
}
// Sync 使订阅集合与 desired(topic → max_in_flight)一致:新增订阅、取消多余订阅、调整 max_in_flight。
func (m *ConsumerManager) Sync(desired map[string]int) {
m.mu.Lock()
@@ -97,7 +111,7 @@ func (m *ConsumerManager) Sync(desired map[string]int) {
if _, keep := desired[topic]; !keep {
sub.consumer.Stop()
delete(m.consumers, topic)
m.logger.Info("取消订阅卡任务 topic", zap.String("topic", topic))
m.logger.Info("取消订阅 NSQ topic", zap.String("topic", topic))
}
}
for topic, maxInFlight := range desired {
@@ -113,11 +127,11 @@ func (m *ConsumerManager) Sync(desired map[string]int) {
}
consumer, err := m.subscribe(topic, maxInFlight)
if err != nil {
m.logger.Warn("订阅卡任务 topic 失败,下一轮重试", zap.String("topic", topic), zap.Error(err))
m.logger.Warn("订阅 NSQ topic 失败,下一轮重试", zap.String("topic", topic), zap.Error(err))
continue
}
m.consumers[topic] = &subscription{consumer: consumer, maxInFlight: maxInFlight}
m.logger.Info("订阅卡任务 topic", zap.String("topic", topic), zap.Int("max_in_flight", maxInFlight))
m.logger.Info("订阅 NSQ topic", zap.String("topic", topic), zap.Int("max_in_flight", maxInFlight))
}
}
@@ -130,6 +144,9 @@ func (m *ConsumerManager) subscribe(topic string, maxInFlight int) (*nsq.Consume
if m.cfg.MaxAttempts > 0 {
cfg.MaxAttempts = m.cfg.MaxAttempts
}
if m.cfg.UnlimitedAttempts {
cfg.MaxAttempts = 0
}
cfg.LookupdPollInterval = 15 * time.Second
if m.cfg.LookupdPollInterval > 0 {
cfg.LookupdPollInterval = m.cfg.LookupdPollInterval
@@ -146,6 +163,14 @@ func (m *ConsumerManager) subscribe(topic string, maxInFlight int) (*nsq.Consume
message.DisableAutoResponse()
m.inflight.Add(1)
defer m.inflight.Done()
if m.retryHandler != nil {
if delay := m.retryHandler(handlerCtx, message.Body, message.Attempts, message.Touch); delay > 0 {
message.RequeueWithoutBackoff(delay)
return nil
}
message.Finish()
return nil
}
defer message.Finish()
m.handler(handlerCtx, message.Body, message.Touch)
return nil

View File

@@ -0,0 +1,60 @@
package nsqbus
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
type nsqdStats struct {
Topics []struct {
TopicName string `json:"topic_name"`
Depth int64 `json:"depth"`
Channels []struct {
Depth int64 `json:"depth"`
DeferredCount int64 `json:"deferred_count"`
} `json:"channels"`
} `json:"topics"`
}
// TopicBacklog 读取 nsqd 上某 topic 的积压量:topic 未分发量 + 各 channel 待消费量与延迟重投量(不含处理中)。
// topic 不存在时返回 0。
func TopicBacklog(ctx context.Context, nsqdTCPAddress, topic string) (int64, error) {
httpAddress := nsqdHTTPAddress(nsqdTCPAddress)
if httpAddress == "" {
return 0, fmt.Errorf("nsqd 地址无效:%s", nsqdTCPAddress)
}
requestCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
endpoint := "http://" + httpAddress + "/stats?format=json&topic=" + url.QueryEscape(topic)
request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, endpoint, nil)
if err != nil {
return 0, err
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return 0, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return 0, fmt.Errorf("读取 nsqd 统计失败,HTTP %d", response.StatusCode)
}
var stats nsqdStats
if err := json.NewDecoder(response.Body).Decode(&stats); err != nil {
return 0, err
}
var backlog int64
for _, item := range stats.Topics {
if item.TopicName != topic {
continue
}
backlog += item.Depth
for _, channel := range item.Channels {
backlog += channel.Depth + channel.DeferredCount
}
}
return backlog, nil
}