feat: 轮询观测入库异步化,调网关与入库分离,采集记录经消息攒批写入
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 16m2s
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:
@@ -82,6 +82,18 @@ type Service struct {
|
||||
logger *zap.Logger
|
||||
// commandGrace 返回停复机成功后的状态保护窗口;未注入时不保护。
|
||||
commandGrace func(ctx context.Context) time.Duration
|
||||
// collectionSink 把采集记录发布到批量写入消息;未注入或发布失败时同步写库。
|
||||
collectionSink CollectionSink
|
||||
}
|
||||
|
||||
// CollectionSink 发布一条采集记录(成功表或失败表二选一),由批量消费者写库。
|
||||
type CollectionSink interface {
|
||||
PublishCollection(ctx context.Context, success *model.CardTrafficCollection, failure *model.CardTrafficCollectionFailure) error
|
||||
}
|
||||
|
||||
// SetCollectionSink 注入采集记录发布器(Worker 启用 card.collection 批量写入时使用)。
|
||||
func (s *Service) SetCollectionSink(sink CollectionSink) {
|
||||
s.collectionSink = sink
|
||||
}
|
||||
|
||||
// SetCommandGrace 注入停复机成功后的状态保护窗口(受控系统配置 polling.stop_resume.status_grace_seconds)。
|
||||
@@ -144,6 +156,7 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
|
||||
}
|
||||
var decision domain.RealnameDecision
|
||||
var auditedCard *model.IotCard
|
||||
stale := false
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var card model.IotCard
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", observation.CardID).First(&card).Error; err != nil {
|
||||
@@ -153,6 +166,15 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "锁定IoT卡失败")
|
||||
}
|
||||
auditedCard = &card
|
||||
if staleObservation(card.LastRealNameCheckAt, observation.Metadata.ObservedAt) {
|
||||
// 异步入库可能乱序:早于已应用观测的实名结果不改卡事实,只记录。
|
||||
s.warnLogger().Info("实名观测早于卡上最近一次已应用的检查,忽略",
|
||||
zap.Uint("card_id", card.ID), zap.String("observation_id", observation.Metadata.ObservationID),
|
||||
zap.Time("observed_at", observation.Metadata.ObservedAt), zap.Timep("last_checked_at", card.LastRealNameCheckAt),
|
||||
zap.String("metric", "card_observation.realname_stale"))
|
||||
stale = true
|
||||
return nil
|
||||
}
|
||||
nextDecision, decisionErr := domain.ApplyRealname(domain.CardRealnameSnapshot{
|
||||
CardID: card.ID, Status: card.RealNameStatus, FirstRealnameAt: card.FirstRealnameAt,
|
||||
ReversalCount: card.RealnameReversalCount, ReversalStartedAt: card.RealnameReversalStartedAt,
|
||||
@@ -275,6 +297,9 @@ func (s *Service) ApplyCardObservation(ctx context.Context, observation domain.R
|
||||
}
|
||||
return domain.RealnameDecision{}, err
|
||||
}
|
||||
if stale {
|
||||
return domain.RealnameDecision{}, nil
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Invalidate(ctx, observation.CardID)
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ func (s *Service) ApplyNetworkObservation(ctx context.Context, observation domai
|
||||
}
|
||||
var decision domain.NetworkDecision
|
||||
var auditedCard *model.IotCard
|
||||
stale := false
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var card model.IotCard
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", observation.CardID).First(&card).Error; err != nil {
|
||||
@@ -46,6 +47,15 @@ func (s *Service) ApplyNetworkObservation(ctx context.Context, observation domai
|
||||
return errors.Wrap(errors.CodeDatabaseError, err, "锁定IoT卡网络事实失败")
|
||||
}
|
||||
auditedCard = &card
|
||||
if staleObservation(card.LastCardStatusCheckAt, observation.Metadata.ObservedAt) {
|
||||
// 异步入库可能乱序:早于已应用观测的网络状态不改卡事实,只记录。
|
||||
s.warnLogger().Info("网络状态观测早于卡上最近一次已应用的检查,忽略",
|
||||
zap.Uint("card_id", card.ID), zap.String("observation_id", observation.Metadata.ObservationID),
|
||||
zap.Time("observed_at", observation.Metadata.ObservedAt), zap.Timep("last_checked_at", card.LastCardStatusCheckAt),
|
||||
zap.String("metric", "card_observation.network_stale"))
|
||||
stale = true
|
||||
return nil
|
||||
}
|
||||
nextDecision, decisionErr := domain.ApplyNetwork(domain.CardNetworkSnapshot{
|
||||
CardID: card.ID, NetworkStatus: card.NetworkStatus, StopReason: card.StopReason,
|
||||
EnablePolling: card.EnablePolling, StoppedAt: card.StoppedAt, ResumedAt: card.ResumedAt,
|
||||
@@ -176,8 +186,16 @@ func (s *Service) ApplyNetworkObservation(ctx context.Context, observation domai
|
||||
}
|
||||
return domain.NetworkDecision{}, err
|
||||
}
|
||||
if stale {
|
||||
return domain.NetworkDecision{}, nil
|
||||
}
|
||||
if s.cache != nil {
|
||||
s.cache.Invalidate(ctx, observation.CardID)
|
||||
}
|
||||
return decision, nil
|
||||
}
|
||||
|
||||
// staleObservation 判断观测时间是否早于卡上最近一次已应用的同类检查时间(异步入库乱序保护)。
|
||||
func staleObservation(lastChecked *time.Time, observedAt time.Time) bool {
|
||||
return lastChecked != nil && !observedAt.IsZero() && observedAt.Before(*lastChecked)
|
||||
}
|
||||
|
||||
@@ -231,6 +231,10 @@ func (s *Service) writeTrafficFailureAudit(ctx context.Context, observation doma
|
||||
if !workerObservationAudited(ctx) || s.auditWriter == nil {
|
||||
return
|
||||
}
|
||||
// 观测失败常因上下文已超时,失败审计改用独立短超时上下文,避免连带报错。
|
||||
auditCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx = auditCtx
|
||||
var card model.IotCard
|
||||
if loadErr := s.db.WithContext(ctx).Where("id = ?", observation.CardID).First(&card).Error; loadErr != nil {
|
||||
return
|
||||
|
||||
@@ -16,9 +16,6 @@ import (
|
||||
"github.com/break/junhong_cmp_fiber/pkg/constants"
|
||||
)
|
||||
|
||||
// collectionRecordTimeout 是事务提交后写采集记录的超时;采集记录只用于排查,写失败只告警。
|
||||
const collectionRecordTimeout = 3 * time.Second
|
||||
|
||||
// rawResponseMaxBytes 是原始响应体保存上限,超过时截断并标记。
|
||||
const rawResponseMaxBytes = 4096
|
||||
|
||||
@@ -27,6 +24,7 @@ type collectionRecord struct {
|
||||
model.CardTrafficCollection
|
||||
HasPackage bool
|
||||
failure *domain.CollectionFailure
|
||||
iccid string
|
||||
}
|
||||
|
||||
func newCollectionRecord(observation domain.TrafficObservation) *collectionRecord {
|
||||
@@ -34,8 +32,8 @@ func newCollectionRecord(observation domain.TrafficObservation) *collectionRecor
|
||||
IotCardID: observation.CardID, ObservedAt: observation.Metadata.ObservedAt,
|
||||
ObservationID: observation.Metadata.ObservationID, Source: observation.Metadata.Source,
|
||||
Scene: observation.Metadata.Scene, Result: domain.ResolveReadingResult(observation),
|
||||
CollectionRaw: buildCollectionRaw(observation.Raw),
|
||||
}, failure: observation.Failure}
|
||||
CollectionRaw: buildCollectionRaw(observation.Raw), CarrierID: observation.CarrierID,
|
||||
}, failure: observation.Failure, iccid: observation.ICCID}
|
||||
if record.Result == constants.TrafficCollectionResultOK {
|
||||
reading := observation.GatewayReadingMB
|
||||
record.VendorUsedMB = &reading
|
||||
@@ -59,18 +57,28 @@ func (r *collectionRecord) applyOutcome(outcome *flowOutcome) {
|
||||
}
|
||||
|
||||
// writeCollectionRecord 在观测事务之外写采集记录:成功读数只为采集时刻有套餐的卡写成功表;
|
||||
// 失败读数不判断有无套餐,写失败表。
|
||||
// 失败读数不判断有无套餐,写失败表。注入发布器时发布到批量写入消息,由消费者攒批写库并失败重投;
|
||||
// 未注入或发布失败时同步写库。
|
||||
func (s *Service) writeCollectionRecord(ctx context.Context, record *collectionRecord, _ time.Time) {
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), collectionRecordTimeout)
|
||||
defer cancel()
|
||||
if record.Result != constants.TrafficCollectionResultOK {
|
||||
s.writeCollectionFailure(writeCtx, record)
|
||||
s.writeCollectionFailure(ctx, record)
|
||||
return
|
||||
}
|
||||
if !record.HasPackage {
|
||||
return
|
||||
}
|
||||
if err := postgres.NewCardTrafficCollectionStore(s.db).Create(writeCtx, &record.CardTrafficCollection); err != nil {
|
||||
row := &record.CardTrafficCollection
|
||||
if s.collectionSink != nil {
|
||||
err := s.collectionSink.PublishCollection(ctx, row, nil)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
s.logTrafficWarn("发布卡流量采集记录消息失败,改为同步写库", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), constants.PollingIngestSyncCollectionTimeout)
|
||||
defer cancel()
|
||||
if err := postgres.NewCardTrafficCollectionStore(s.db).Create(writeCtx, row); err != nil {
|
||||
s.logTrafficWarn("写卡流量采集记录失败", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
@@ -80,16 +88,29 @@ func (s *Service) writeCollectionFailure(ctx context.Context, record *collection
|
||||
row := &model.CardTrafficCollectionFailure{
|
||||
IotCardID: record.IotCardID, ObservedAt: record.ObservedAt, ObservationID: record.ObservationID,
|
||||
Source: record.Source, Scene: record.Scene, Result: record.Result, CollectionRaw: record.CollectionRaw,
|
||||
ICCID: record.iccid, CarrierID: record.CarrierID,
|
||||
}
|
||||
if failure := record.failure; failure != nil {
|
||||
row.ErrorCategory, row.ProviderCode = failure.ErrorCategory, failure.ProviderCode
|
||||
row.ProviderMessage, row.DurationMS = truncateText(failure.ProviderMessage, 500), failure.DurationMS
|
||||
}
|
||||
var card model.IotCard
|
||||
if err := s.db.WithContext(ctx).Unscoped().Select("iccid", "carrier_id").Where("id = ?", record.IotCardID).Take(&card).Error; err == nil {
|
||||
row.ICCID, row.CarrierID = card.ICCID, card.CarrierID
|
||||
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), constants.PollingIngestSyncCollectionTimeout)
|
||||
defer cancel()
|
||||
if row.ICCID == "" || row.CarrierID == 0 {
|
||||
var card model.IotCard
|
||||
if err := s.db.WithContext(writeCtx).Unscoped().Select("iccid", "carrier_id").Where("id = ?", record.IotCardID).Take(&card).Error; err == nil {
|
||||
row.ICCID, row.CarrierID = card.ICCID, card.CarrierID
|
||||
}
|
||||
}
|
||||
if err := postgres.NewCardTrafficCollectionFailureStore(s.db).Create(ctx, row); err != nil {
|
||||
if s.collectionSink != nil {
|
||||
err := s.collectionSink.PublishCollection(ctx, nil, row)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
s.logTrafficWarn("发布卡流量采集失败记录消息失败,改为同步写库", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
if err := postgres.NewCardTrafficCollectionFailureStore(s.db).Create(writeCtx, row); err != nil {
|
||||
s.logTrafficWarn("写卡流量采集失败记录失败", zap.Uint("card_id", record.IotCardID),
|
||||
zap.String("observation_id", record.ObservationID), zap.Error(err))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user