package cardobservation import ( "context" "encoding/json" "time" "go.uber.org/zap" cardflow "github.com/break/junhong_cmp_fiber/internal/domain/cardflow" domain "github.com/break/junhong_cmp_fiber/internal/domain/cardobservation" "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" ) // collectionRecordTimeout 是事务提交后写采集记录的超时;采集记录只用于排查,写失败只告警。 const collectionRecordTimeout = 3 * time.Second // collectionRecord 是一次采集的留痕内容;HasPackage 在观测事务内判断,读数无效的观测写记录前再查。 type collectionRecord struct { model.CardTrafficCollection HasPackage bool } func newCollectionRecord(observation domain.TrafficObservation) *collectionRecord { record := &collectionRecord{CardTrafficCollection: model.CardTrafficCollection{ IotCardID: observation.CardID, ObservedAt: observation.Metadata.ObservedAt, ObservationID: observation.Metadata.ObservationID, Source: observation.Metadata.Source, Scene: observation.Metadata.Scene, Result: domain.ResolveReadingResult(observation), }} if record.Result == constants.TrafficCollectionResultOK { reading := observation.GatewayReadingMB record.VendorUsedMB = &reading } return record } func (r *collectionRecord) setQueue(points []cardflow.QueuePoint) { if encoded, err := json.Marshal(points); err == nil { r.QueuePoints = encoded } } func (r *collectionRecord) applyOutcome(outcome *flowOutcome) { r.Decision = outcome.Decision if !outcome.Written { return } monthUsed, delta, stale := outcome.MonthUsedMB, outcome.DeltaMB, outcome.StaleGuarded r.MonthUsedMB, r.DeltaMB, r.StaleGuarded, r.EventID = &monthUsed, &delta, &stale, outcome.EventID } // writeCollectionRecord 在观测事务之外为采集时刻有套餐的卡写采集记录;没套餐的卡不写。 func (s *Service) writeCollectionRecord(ctx context.Context, record *collectionRecord, observedAt time.Time) { writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), collectionRecordTimeout) defer cancel() hasPackage := record.HasPackage if record.Result != constants.TrafficCollectionResultOK { packages, err := postgres.FindEffectivePackagesAt(writeCtx, s.db, record.IotCardID, observedAt, false) if err != nil { s.logTrafficWarn("查询卡采集时刻有效套餐失败,跳过采集记录", zap.Uint("card_id", record.IotCardID), zap.Error(err)) return } hasPackage = len(packages.Packages) > 0 } if !hasPackage { return } if err := postgres.NewCardTrafficCollectionStore(s.db).Create(writeCtx, &record.CardTrafficCollection); err != nil { s.logTrafficWarn("写卡流量采集记录失败", zap.Uint("card_id", record.IotCardID), zap.String("observation_id", record.ObservationID), zap.Error(err)) } }