Files
junhong_cmp_fiber/internal/infrastructure/gatewaylimit/terminal_polling.go
邹进 af8249158d
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 9m26s
feat: 停复机规则演练与终态自动关闭轮询
统一停复机规则转正的第一次发布:总开关仍关闭,现有停复机行为不变。

- 新增停复机规则演练:GET /stop-resume-rule/dry-run 按新规则对开机与停机卡只判断不执行,返回运营商账户 × 停机原因 × 判断结果汇总与分页明细,可假设通道实名管控配置;POST /stop-resume-rule/dry-run/export 导出明细(场景 stop_resume_rule_dry_run);仅超级管理员与平台账号
- 风险停机、已销户关闭轮询不再限于独立卡,只关该卡自身轮询,不级联设备
- 错误分类规则增加 auto_disable_polling,仅终态类别可勾选;停复机(含设备停复机)命中该规则时不重试、关闭该卡轮询、回写网关扩展状态并写审计 iot_card.terminal_disable_polling
- 迁移 000250 加列与约束,并为"已销户""仅支持风险复机"置位
2026-10-25 17:52:40 +09:00

114 lines
4.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gatewaylimit
import (
"context"
"strconv"
"strings"
"time"
"go.uber.org/zap"
"gorm.io/gorm"
"github.com/break/junhong_cmp_fiber/internal/gateway"
auditinfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/constants"
)
// TerminalPollingDisabler 在停复机调用命中"自动关闭轮询"的终态规则时关闭该卡自身轮询:
// 不级联设备与设备下其他卡;同事务回写网关扩展状态并写审计。
type TerminalPollingDisabler struct {
db *gorm.DB
classifier *Classifier
audit *auditinfra.Writer
logger *zap.Logger
}
// NewTerminalPollingDisabler 创建终态关闭轮询处理器;db 或 classifier 为 nil 时不处理。
func NewTerminalPollingDisabler(db *gorm.DB, classifier *Classifier, logger *zap.Logger) *TerminalPollingDisabler {
if logger == nil {
logger = zap.NewNop()
}
return &TerminalPollingDisabler{db: db, classifier: classifier, logger: logger}
}
// SetAuditWriter 注入统一审计;未注入时只关闭轮询并记日志。
func (d *TerminalPollingDisabler) SetAuditWriter(writer *auditinfra.Writer) {
if d != nil {
d.audit = writer
}
}
// HandleCommandError 判断停复机上游失败是否命中"自动关闭轮询"规则;命中时关闭该卡轮询并返回 true,
// 调用方据此不再重试。action 为 constants.StopResumeActionStop / StopResumeActionStart。
func (d *TerminalPollingDisabler) HandleCommandError(ctx context.Context, card *model.IotCard, action string, callErr error) bool {
if d == nil || d.db == nil || d.classifier == nil || card == nil || card.ID == 0 || callErr == nil {
return false
}
gwErr, ok := gateway.AsGatewayError(callErr)
if !ok || gwErr.Category != constants.GatewayErrorUpstream {
return false
}
op := constants.GatewayOpStop
if action == constants.StopResumeActionStart {
op = constants.GatewayOpStart
}
classification := d.classifier.Classify(ctx, op, gwErr.ProviderMessage)
if !classification.AutoDisablePolling {
return false
}
extend := terminalGatewayExtend(gwErr.ProviderMessage, card.GatewayExtend)
if err := d.disable(ctx, card, extend, classification, gwErr.ProviderMessage); err != nil {
d.logger.Error("上游终态自动关闭卡轮询失败", zap.Uint("card_id", card.ID), zap.String("iccid", card.ICCID),
zap.String("metric", "stop_resume.terminal_disable_polling.failed"), zap.Error(err))
return true
}
d.logger.Warn("停复机命中终态规则,已关闭该卡轮询",
zap.Uint("card_id", card.ID), zap.String("iccid", card.ICCID), zap.String("action", action),
zap.Uint("rule_id", classification.RuleID), zap.String("keyword", classification.Keyword),
zap.String("gateway_extend", extend), zap.String("metric", "stop_resume.terminal_disable_polling"))
return true
}
func (d *TerminalPollingDisabler) disable(ctx context.Context, card *model.IotCard, extend string, classification Classification, message string) error {
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
return d.db.WithContext(writeCtx).Transaction(func(tx *gorm.DB) error {
updates := map[string]any{"enable_polling": false, "gateway_extend": extend, "updated_at": time.Now()}
if err := tx.Model(&model.IotCard{}).Where("id = ?", card.ID).Updates(updates).Error; err != nil {
return err
}
if d.audit == nil {
return nil
}
id := strconv.FormatUint(uint64(card.ID), 10)
return d.audit.Append(ctx, tx, auditinfra.AppendInput{
ActionCode: constants.AuditActionIotCardTerminalPollingDisabled,
Summary: "上游返回终态,自动关闭 IoT 卡轮询",
Result: constants.AuditResultSuccess,
Metadata: map[string]any{"rule_id": classification.RuleID, "keyword": classification.Keyword,
"provider_message": message},
Resources: []auditinfra.ResourceInput{{
Type: constants.AuditResourceIotCard, ID: &id, Key: auditinfra.IotCardResourceKey(card), DisplayName: card.ICCID,
Relation: constants.AuditResourceRelationPrimary, Role: constants.AuditResourceRoleIotCardTarget,
IdentitySnapshot: auditinfra.IotCardIdentitySnapshot(card),
BeforeData: map[string]any{"enable_polling": card.EnablePolling, "gateway_extend": card.GatewayExtend},
AfterData: map[string]any{"enable_polling": false, "gateway_extend": extend},
SubjectVisibility: constants.AuditSubjectResult, SubjectSummary: "IoT 卡已因上游终态关闭轮询",
}},
})
})
}
// terminalGatewayExtend 按上游返回推断网关扩展状态:已销户、风险停机;无法推断时保留原值。
func terminalGatewayExtend(message, current string) string {
switch {
case strings.Contains(message, "销户"):
return constants.GatewayCardExtendCancelled
case strings.Contains(message, "风险"):
return constants.GatewayCardExtendRiskStop
default:
return current
}
}