All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 14m13s
新增 000228 成对迁移 tb_polling_priority_item:卡、任务类型、状态、触发类型、来源订单/套餐使用记录、
触发次数与来源集合、尝试次数、失败原因、人工原因与操作者、店铺快照与各时间列;以活动项部分唯一索引
uq_polling_priority_item_active(仅 deleted_at IS NULL AND status IN ('pending','processing') 占键位)
表达「同卡同任务类型至多一条活动项」,另有状态/时间索引与全列注释;down 守卫在存在活动项或未终态行时
拒绝回滚并给出中文原因。
新增优先轮询请求可靠事件 polling.priority.requested(载荷版本 v1、事件键前缀 prio:)与消费者:只在原
业务事务内追加、幂等键稳定;消费者按卡 × 纳入任务类型(realname/carddata/card_status/package)逐条
建项并在提交后下发执行提示,重复投递只合并触发次数、来源集合与最近触发时间,不新建行也不重复调用。
触发点为四类自动场景 purchase_activated / renewal_activated(按同载体更早套餐使用记录判定)/
queue_activated / addon_activated 与「无有效套餐」no_valid_package(仅在普通套餐轮询来源且存在待生效
套餐使用记录时追加;事件通道显式拒绝 manual_trigger);入队对象恒为卡,绑定设备资产在触发事务内冻结
在用卡快照逐卡建项,不使用设备当前卡槽口径。
轮询共享基类新增认领接缝:四个 Handler(realname/carddata/card_status/package)在并发信号量之后、调用
上游之前探测活动项——待执行条件认领、执行中且 90 秒租约未到期则跳过并延后、无活动项时行为与既有完全
等价;超租约允许相邻执行接管,尝试次数只在真正发起执行后累加,未达上限(3)回到活动态按既有间隔重排,
达上限或业务校验类失败进入失败终态并保留可安全展示原因;执行前校验卡自身与绑定设备的轮询开关。未引入
通用卡级锁与 Redis 活动标记,分片队列的出队、入队与移除路径未改动。
提示通道按任务类型独立键(polling:priority:{taskType}),与既有手动触发队列分离;调度器在同一周期内先
排空优先提示、再排空手动触发队列,提示排空不受分片背压跳过影响;未新建调度设施或异步任务类型。
新增人工优先入队与只读查询三条路由 POST /api/admin/polling-priority-items、
GET /api/admin/polling-priority-items、GET /api/admin/polling-priority-items/:id:人工入队复用既有轮询
权限判定(抽取为同包共享函数),原因必填,不受每日 500 次上限与 24 小时去重约束,重复抑制由活动项合并
承担;读侧按店铺快照下推数据范围,越权与不存在不可区分,不提供优先级分级、有效期或人工重触发入口。
新增 7 个审计动作(enqueue/claim/fail/retry/complete/dequeue/manual_denied)与资源
polling_priority_item,并按(操作者类型,来源)注册,人工侧与 Worker 侧均通过来源校验。
同步 OpenAPI 文档装配三处与路由注册;归档 Change 至
openspec/changes/archive/2026-09-17-add-priority-polling-queue/ 并同步主 Spec(新增
priority-polling-queue、polling-operations 追加单次执行互斥 Requirement 与三条路由索引)与上下文健康
证据(requirement-evidence 150 行、入口矩阵 http 403 / async 56)。
本机验证:junhong_cmp_test 与隔离 Redis DB 15,未连生产、未启动 Worker/API、未调用运营商上游;迁移
up/down/up 与 down 守卫实测(含 dirty=true 记账口径与 force 恢复),A–F 批 94 PASS、接缝 63 PASS、
提示通道 12 PASS、清理零残留 20 PASS。成功路径 Complete、真并发互斥、尝试上限第 3 次判定、HTTP 层权限
矩阵、通道阈值持锁复机边界与三类生效触发点生产集成留待测试部署验证(见
docs/verification/add-priority-polling-queue-verification.md 第 4 节)。自动化测试按项目决策为 N/A,
未新增 *_test.go。
558 lines
22 KiB
Go
558 lines
22 KiB
Go
package polling
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"time"
|
||
|
||
"github.com/redis/go-redis/v9"
|
||
"go.uber.org/zap"
|
||
"gorm.io/gorm"
|
||
|
||
auditinfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/audit"
|
||
"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"
|
||
"github.com/break/junhong_cmp_fiber/pkg/errors"
|
||
"github.com/break/junhong_cmp_fiber/pkg/middleware"
|
||
)
|
||
|
||
// ManualTriggerService 手动触发服务
|
||
type ManualTriggerService struct {
|
||
logStore *postgres.PollingManualTriggerLogStore
|
||
iotCardStore *postgres.IotCardStore
|
||
db *gorm.DB
|
||
auditWriter *auditinfra.Writer
|
||
redis *redis.Client
|
||
logger *zap.Logger
|
||
}
|
||
|
||
// SetAudit 注入手动轮询任务事务与统一审计 Writer。
|
||
func (s *ManualTriggerService) SetAudit(db *gorm.DB, writer *auditinfra.Writer) {
|
||
s.db = db
|
||
s.auditWriter = writer
|
||
}
|
||
|
||
// NewManualTriggerService 创建手动触发服务实例
|
||
func NewManualTriggerService(
|
||
logStore *postgres.PollingManualTriggerLogStore,
|
||
iotCardStore *postgres.IotCardStore,
|
||
redis *redis.Client,
|
||
logger *zap.Logger,
|
||
) *ManualTriggerService {
|
||
return &ManualTriggerService{
|
||
logStore: logStore,
|
||
iotCardStore: iotCardStore,
|
||
redis: redis,
|
||
logger: logger,
|
||
}
|
||
}
|
||
|
||
// TriggerSingle 单卡手动触发
|
||
func (s *ManualTriggerService) TriggerSingle(ctx context.Context, cardID uint, taskType string, triggeredBy uint) error {
|
||
// 验证任务类型
|
||
if !isValidTaskType(taskType) {
|
||
return errors.New(errors.CodeInvalidParam, "无效的任务类型")
|
||
}
|
||
|
||
// 权限验证:检查用户是否有权管理该卡(与人工优先入队共用同包共享判定)
|
||
if err := canManagePollingCard(ctx, s.iotCardStore, cardID); err != nil {
|
||
return err
|
||
}
|
||
cards, err := s.iotCardStore.GetByIDs(ctx, []uint{cardID})
|
||
if err != nil {
|
||
return errors.Wrap(errors.CodeInternalError, err, "查询手动轮询卡失败")
|
||
}
|
||
|
||
// 检查每日触发限制
|
||
todayCount, err := s.logStore.CountTodayTriggers(ctx, triggeredBy)
|
||
if err != nil {
|
||
s.logger.Error("查询今日触发次数失败",
|
||
zap.Uint("triggered_by", triggeredBy),
|
||
zap.String("task_type", taskType),
|
||
zap.Error(err))
|
||
return err
|
||
}
|
||
if todayCount >= 500 { // 每日最多触发500次
|
||
appErr := errors.New(errors.CodeInvalidParam, "已达到每日触发次数上限")
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerSingle, Summary: "拒绝超过每日上限的单卡手动触发",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger,
|
||
ResourceKey: pollingManualAttemptKey(taskType, "single", triggeredBy), DisplayName: "单卡手动触发",
|
||
OperatorID: triggeredBy, Result: constants.AuditResultDenied,
|
||
IdentitySnapshot: pollingManualAttemptIdentity(taskType, "single", 1, triggeredBy), Cards: cards,
|
||
}, appErr)
|
||
return appErr
|
||
}
|
||
|
||
// 检查去重
|
||
dedupeKey := constants.RedisPollingManualDedupeKey(taskType)
|
||
added, err := s.redis.SAdd(ctx, dedupeKey, cardID).Result()
|
||
if err != nil {
|
||
s.logger.Error("Redis去重操作失败",
|
||
zap.Uint("card_id", cardID),
|
||
zap.String("task_type", taskType),
|
||
zap.Error(err))
|
||
return err
|
||
}
|
||
if added == 0 {
|
||
appErr := errors.New(errors.CodeInvalidParam, "该卡已在手动触发队列中")
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerSingle, Summary: "拒绝重复加入手动触发队列",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger,
|
||
ResourceKey: pollingManualAttemptKey(taskType, "single", triggeredBy), DisplayName: "单卡手动触发",
|
||
OperatorID: triggeredBy, Result: constants.AuditResultDenied,
|
||
IdentitySnapshot: pollingManualAttemptIdentity(taskType, "single", 1, triggeredBy), Cards: cards,
|
||
}, appErr)
|
||
return appErr
|
||
}
|
||
// 设置去重 key 过期时间(24小时,与日限制周期对齐)
|
||
s.redis.Expire(ctx, dedupeKey, 24*time.Hour)
|
||
|
||
// 创建触发日志
|
||
cardIDsJSON, _ := json.Marshal([]uint{cardID})
|
||
triggerLog := &model.PollingManualTriggerLog{
|
||
TaskType: taskType,
|
||
TriggerType: "single",
|
||
CardIDs: string(cardIDsJSON),
|
||
TotalCount: 1,
|
||
Status: constants.PollingManualTriggerStatusProcessing,
|
||
TriggeredBy: triggeredBy,
|
||
TriggeredAt: time.Now(),
|
||
}
|
||
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
||
if err := s.logStore.WithTx(tx).Create(ctx, triggerLog); err != nil {
|
||
return err
|
||
}
|
||
return writePollingAudit(ctx, tx, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerSingle, Summary: "单卡手动触发",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger, ResourceID: triggerLog.ID,
|
||
ResourceKey: pollingManualTriggerKey(triggerLog.ID), DisplayName: "手动轮询任务",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualTriggerIdentity(triggerLog),
|
||
AfterData: map[string]any{"status": triggerLog.Status, "task_type": taskType, "trigger_type": triggerLog.TriggerType},
|
||
Cards: cards,
|
||
})
|
||
})
|
||
if err != nil {
|
||
_ = s.redis.SRem(ctx, dedupeKey, cardID).Err()
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerSingle, Summary: "单卡手动触发失败",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger,
|
||
ResourceKey: pollingManualAttemptKey(taskType, "single", triggeredBy), DisplayName: "单卡手动触发",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualAttemptIdentity(taskType, "single", 1, triggeredBy), Cards: cards,
|
||
}, err)
|
||
s.logger.Error("创建触发日志失败",
|
||
zap.Uint("card_id", cardID),
|
||
zap.Uint("triggered_by", triggeredBy),
|
||
zap.Error(err))
|
||
return err
|
||
}
|
||
|
||
// 加入手动触发队列(使用 List,优先级高于定时轮询)
|
||
queueKey := constants.RedisPollingManualQueueKey(taskType)
|
||
if err := s.redis.LPush(ctx, queueKey, cardID).Err(); err != nil {
|
||
_ = s.redis.SRem(ctx, dedupeKey, cardID).Err()
|
||
s.logger.Error("写入手动触发队列失败",
|
||
zap.Uint("card_id", cardID),
|
||
zap.String("task_type", taskType),
|
||
zap.Error(err))
|
||
return err
|
||
}
|
||
|
||
// 更新日志状态
|
||
_ = s.logStore.UpdateProgress(ctx, triggerLog.ID, 1, 1, 0)
|
||
_ = s.logStore.UpdateStatus(ctx, triggerLog.ID, constants.PollingManualTriggerStatusCompleted)
|
||
|
||
s.logger.Info("单卡手动触发成功",
|
||
zap.Uint("card_id", cardID),
|
||
zap.String("task_type", taskType),
|
||
zap.Uint("triggered_by", triggeredBy))
|
||
|
||
return nil
|
||
}
|
||
|
||
// TriggerBatch 批量手动触发
|
||
func (s *ManualTriggerService) TriggerBatch(ctx context.Context, cardIDs []uint, taskType string, triggeredBy uint) (*model.PollingManualTriggerLog, error) {
|
||
// 验证任务类型
|
||
if !isValidTaskType(taskType) {
|
||
return nil, errors.New(errors.CodeInvalidParam, "无效的任务类型")
|
||
}
|
||
|
||
// 单次最多1000张卡
|
||
if len(cardIDs) > 1000 {
|
||
return nil, errors.New(errors.CodeInvalidParam, "单次最多触发1000张卡")
|
||
}
|
||
|
||
// 权限验证:检查用户是否有权管理所有卡(与人工优先入队共用同包共享判定)
|
||
if err := canManagePollingCards(ctx, s.iotCardStore, cardIDs); err != nil {
|
||
return nil, err
|
||
}
|
||
cards, err := s.iotCardStore.GetByIDs(ctx, cardIDs)
|
||
if err != nil {
|
||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询手动轮询卡失败")
|
||
}
|
||
|
||
// 检查每日触发限制
|
||
todayCount, err := s.logStore.CountTodayTriggers(ctx, triggeredBy)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if todayCount >= 500 { // 每日最多触发500次
|
||
appErr := errors.New(errors.CodeInvalidParam, "已达到每日触发次数上限")
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerBatch, Summary: "拒绝超过每日上限的批量手动触发",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger,
|
||
ResourceKey: pollingManualAttemptKey(taskType, "batch", triggeredBy), DisplayName: "批量手动触发",
|
||
OperatorID: triggeredBy, Result: constants.AuditResultDenied,
|
||
IdentitySnapshot: pollingManualAttemptIdentity(taskType, "batch", len(cardIDs), triggeredBy), Cards: cards,
|
||
}, appErr)
|
||
return nil, appErr
|
||
}
|
||
|
||
// 创建触发日志
|
||
cardIDsJSON, _ := json.Marshal(cardIDs)
|
||
triggerLog := &model.PollingManualTriggerLog{
|
||
TaskType: taskType,
|
||
TriggerType: "batch",
|
||
CardIDs: string(cardIDsJSON),
|
||
TotalCount: len(cardIDs),
|
||
Status: constants.PollingManualTriggerStatusProcessing,
|
||
TriggeredBy: triggeredBy,
|
||
TriggeredAt: time.Now(),
|
||
}
|
||
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
||
if err := s.logStore.WithTx(tx).Create(ctx, triggerLog); err != nil {
|
||
return err
|
||
}
|
||
return writePollingAudit(ctx, tx, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerBatch, Summary: "批量手动触发",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger, ResourceID: triggerLog.ID,
|
||
ResourceKey: pollingManualTriggerKey(triggerLog.ID), DisplayName: "手动轮询任务",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualTriggerIdentity(triggerLog),
|
||
AfterData: map[string]any{"status": triggerLog.Status, "task_type": taskType, "trigger_type": triggerLog.TriggerType},
|
||
Cards: cards,
|
||
})
|
||
})
|
||
if err != nil {
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerBatch, Summary: "批量手动触发失败",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger,
|
||
ResourceKey: pollingManualAttemptKey(taskType, "batch", triggeredBy), DisplayName: "批量手动触发",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualAttemptIdentity(taskType, "batch", len(cardIDs), triggeredBy), Cards: cards,
|
||
}, err)
|
||
return nil, err
|
||
}
|
||
|
||
// 异步处理批量触发
|
||
go s.processBatchTrigger(context.Background(), triggerLog.ID, cardIDs, taskType)
|
||
|
||
return triggerLog, nil
|
||
}
|
||
|
||
// processBatchTrigger 异步处理批量触发
|
||
func (s *ManualTriggerService) processBatchTrigger(ctx context.Context, logID uint, cardIDs []uint, taskType string) {
|
||
dedupeKey := constants.RedisPollingManualDedupeKey(taskType)
|
||
queueKey := constants.RedisPollingManualQueueKey(taskType)
|
||
|
||
var processedCount, successCount, failedCount int
|
||
|
||
for _, cardID := range cardIDs {
|
||
// 检查去重
|
||
added, err := s.redis.SAdd(ctx, dedupeKey, cardID).Result()
|
||
if err != nil {
|
||
failedCount++
|
||
processedCount++
|
||
continue
|
||
}
|
||
|
||
if added == 0 {
|
||
// 已在队列中,跳过
|
||
failedCount++
|
||
processedCount++
|
||
continue
|
||
}
|
||
|
||
// 加入队列
|
||
if err := s.redis.LPush(ctx, queueKey, cardID).Err(); err != nil {
|
||
failedCount++
|
||
} else {
|
||
successCount++
|
||
}
|
||
processedCount++
|
||
|
||
// 每处理100条更新一次进度
|
||
if processedCount%100 == 0 {
|
||
_ = s.logStore.UpdateProgress(ctx, logID, processedCount, successCount, failedCount)
|
||
}
|
||
}
|
||
|
||
// 设置去重 key 过期时间(24小时,与日限制周期对齐)
|
||
s.redis.Expire(ctx, dedupeKey, 24*time.Hour)
|
||
|
||
// 更新最终状态
|
||
_ = s.logStore.UpdateProgress(ctx, logID, processedCount, successCount, failedCount)
|
||
_ = s.logStore.UpdateStatus(ctx, logID, constants.PollingManualTriggerStatusCompleted)
|
||
|
||
s.logger.Info("批量手动触发完成",
|
||
zap.Uint("log_id", logID),
|
||
zap.Int("total", len(cardIDs)),
|
||
zap.Int("success", successCount),
|
||
zap.Int("failed", failedCount))
|
||
}
|
||
|
||
// ConditionFilter 条件筛选参数
|
||
type ConditionFilter struct {
|
||
CardStatus string `json:"card_status,omitempty"` // 卡状态
|
||
CarrierCode string `json:"carrier_code,omitempty"` // 运营商代码
|
||
CardType string `json:"card_type,omitempty"` // 卡类型
|
||
ShopID *uint `json:"shop_id,omitempty"` // 店铺ID
|
||
PackageIDs []uint `json:"package_ids,omitempty"` // 套餐ID列表
|
||
EnablePolling *bool `json:"enable_polling,omitempty"` // 是否启用轮询
|
||
Limit int `json:"limit,omitempty"` // 限制数量
|
||
}
|
||
|
||
// TriggerByCondition 条件筛选触发
|
||
func (s *ManualTriggerService) TriggerByCondition(ctx context.Context, filter *ConditionFilter, taskType string, triggeredBy uint) (*model.PollingManualTriggerLog, error) {
|
||
// 验证任务类型
|
||
if !isValidTaskType(taskType) {
|
||
return nil, errors.New(errors.CodeInvalidParam, "无效的任务类型")
|
||
}
|
||
|
||
// 设置默认限制
|
||
if filter.Limit <= 0 || filter.Limit > 1000 {
|
||
filter.Limit = 1000
|
||
}
|
||
|
||
// 权限验证:代理只能筛选自己管理的店铺的卡
|
||
if err := s.applyShopPermissionFilter(ctx, filter); err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
// 检查每日触发限制
|
||
todayCount, err := s.logStore.CountTodayTriggers(ctx, triggeredBy)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if todayCount >= 500 { // 每日最多触发500次
|
||
appErr := errors.New(errors.CodeInvalidParam, "已达到每日触发次数上限")
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerByCondition, Summary: "拒绝超过每日上限的条件筛选触发",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger,
|
||
ResourceKey: pollingManualAttemptKey(taskType, "by_condition", triggeredBy), DisplayName: "条件筛选触发",
|
||
OperatorID: triggeredBy, Result: constants.AuditResultDenied,
|
||
IdentitySnapshot: pollingManualAttemptIdentity(taskType, "by_condition", 0, triggeredBy),
|
||
Metadata: map[string]any{"condition_filter_configured": true},
|
||
}, appErr)
|
||
return nil, appErr
|
||
}
|
||
|
||
// 查询符合条件的卡(已应用权限过滤)
|
||
cardIDs, err := s.queryCardsByCondition(ctx, filter)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
if len(cardIDs) == 0 {
|
||
return nil, errors.New(errors.CodeInvalidParam, "没有符合条件的卡")
|
||
}
|
||
cards, err := s.iotCardStore.GetByIDs(ctx, cardIDs)
|
||
if err != nil {
|
||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询手动轮询卡失败")
|
||
}
|
||
|
||
// 创建触发日志
|
||
filterJSON, _ := json.Marshal(filter)
|
||
cardIDsJSON, _ := json.Marshal(cardIDs)
|
||
triggerLog := &model.PollingManualTriggerLog{
|
||
TaskType: taskType,
|
||
TriggerType: "by_condition",
|
||
CardIDs: string(cardIDsJSON),
|
||
ConditionFilter: string(filterJSON),
|
||
TotalCount: len(cardIDs),
|
||
Status: constants.PollingManualTriggerStatusProcessing,
|
||
TriggeredBy: triggeredBy,
|
||
TriggeredAt: time.Now(),
|
||
}
|
||
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
||
if err := s.logStore.WithTx(tx).Create(ctx, triggerLog); err != nil {
|
||
return err
|
||
}
|
||
return writePollingAudit(ctx, tx, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerByCondition, Summary: "条件筛选触发",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger, ResourceID: triggerLog.ID,
|
||
ResourceKey: pollingManualTriggerKey(triggerLog.ID), DisplayName: "手动轮询任务",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualTriggerIdentity(triggerLog),
|
||
AfterData: map[string]any{"status": triggerLog.Status, "task_type": taskType, "trigger_type": triggerLog.TriggerType},
|
||
Metadata: map[string]any{"condition_filter_configured": true}, Cards: cards,
|
||
})
|
||
})
|
||
if err != nil {
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualTriggerByCondition, Summary: "条件筛选触发失败",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger,
|
||
ResourceKey: pollingManualAttemptKey(taskType, "by_condition", triggeredBy), DisplayName: "条件筛选触发",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualAttemptIdentity(taskType, "by_condition", len(cardIDs), triggeredBy),
|
||
Metadata: map[string]any{"condition_filter_configured": true}, Cards: cards,
|
||
}, err)
|
||
return nil, err
|
||
}
|
||
|
||
// 异步处理批量触发
|
||
go s.processBatchTrigger(context.Background(), triggerLog.ID, cardIDs, taskType)
|
||
|
||
return triggerLog, nil
|
||
}
|
||
|
||
// queryCardsByCondition 根据条件查询卡ID
|
||
func (s *ManualTriggerService) queryCardsByCondition(ctx context.Context, filter *ConditionFilter) ([]uint, error) {
|
||
// 构建查询条件并查询卡
|
||
queryFilter := &postgres.IotCardQueryFilter{
|
||
ShopID: filter.ShopID,
|
||
EnablePolling: filter.EnablePolling,
|
||
Limit: filter.Limit,
|
||
}
|
||
|
||
// 映射其他过滤条件
|
||
if filter.CardStatus != "" {
|
||
queryFilter.CardStatus = &filter.CardStatus
|
||
}
|
||
if filter.CarrierCode != "" {
|
||
queryFilter.CarrierCode = &filter.CarrierCode
|
||
}
|
||
if filter.CardType != "" {
|
||
queryFilter.CardType = &filter.CardType
|
||
}
|
||
|
||
// 调用 IotCardStore 查询
|
||
cardIDs, err := s.iotCardStore.QueryIDsByFilter(ctx, queryFilter)
|
||
if err != nil {
|
||
return nil, errors.Wrap(errors.CodeInternalError, err, "查询符合条件的卡失败")
|
||
}
|
||
|
||
return cardIDs, nil
|
||
}
|
||
|
||
// GetStatus 获取触发状态
|
||
func (s *ManualTriggerService) GetStatus(ctx context.Context, logID uint) (*model.PollingManualTriggerLog, error) {
|
||
return s.logStore.GetByID(ctx, logID)
|
||
}
|
||
|
||
// ListHistory 获取触发历史
|
||
func (s *ManualTriggerService) ListHistory(ctx context.Context, page, pageSize int, taskType string, triggeredBy *uint) ([]*model.PollingManualTriggerLog, int64, error) {
|
||
if page < 1 {
|
||
page = 1
|
||
}
|
||
if pageSize < 1 || pageSize > 100 {
|
||
pageSize = 20
|
||
}
|
||
return s.logStore.List(ctx, page, pageSize, taskType, triggeredBy)
|
||
}
|
||
|
||
// CancelTrigger 取消触发任务
|
||
func (s *ManualTriggerService) CancelTrigger(ctx context.Context, logID uint, triggeredBy uint) error {
|
||
log, err := s.logStore.GetByID(ctx, logID)
|
||
if err != nil {
|
||
return errors.Wrap(errors.CodeNotFound, err, "触发任务不存在")
|
||
}
|
||
|
||
if log.TriggeredBy != triggeredBy {
|
||
appErr := errors.New(errors.CodeForbidden, "无权限取消该任务")
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualCancelled, Summary: "拒绝取消其他账号的手动触发任务",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger, ResourceID: log.ID,
|
||
ResourceKey: pollingManualTriggerKey(log.ID), DisplayName: "手动轮询任务",
|
||
OperatorID: triggeredBy, Result: constants.AuditResultDenied, IdentitySnapshot: pollingManualTriggerIdentity(log),
|
||
}, appErr)
|
||
return appErr
|
||
}
|
||
|
||
if log.Status != constants.PollingManualTriggerStatusPending && log.Status != constants.PollingManualTriggerStatusProcessing {
|
||
appErr := errors.New(errors.CodeInvalidParam, "任务已完成或已取消")
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualCancelled, Summary: "拒绝取消已结束的手动触发任务",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger, ResourceID: log.ID,
|
||
ResourceKey: pollingManualTriggerKey(log.ID), DisplayName: "手动轮询任务",
|
||
OperatorID: triggeredBy, Result: constants.AuditResultDenied, IdentitySnapshot: pollingManualTriggerIdentity(log),
|
||
}, appErr)
|
||
return appErr
|
||
}
|
||
|
||
var cardIDs []uint
|
||
_ = json.Unmarshal([]byte(log.CardIDs), &cardIDs)
|
||
cards, _ := s.iotCardStore.GetByIDs(ctx, cardIDs)
|
||
err = runPollingTransaction(ctx, s.db, s.auditWriter, func(tx *gorm.DB) error {
|
||
if err := s.logStore.WithTx(tx).UpdateStatus(ctx, logID, constants.PollingManualTriggerStatusCancelled); err != nil {
|
||
return err
|
||
}
|
||
before := log.Status
|
||
log.Status = constants.PollingManualTriggerStatusCancelled
|
||
return writePollingAudit(ctx, tx, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualCancelled, Summary: "人工取消轮询任务",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger, ResourceID: log.ID,
|
||
ResourceKey: pollingManualTriggerKey(log.ID), DisplayName: "手动轮询任务",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualTriggerIdentity(log),
|
||
BeforeData: map[string]any{"status": before}, AfterData: map[string]any{"status": log.Status}, Cards: cards,
|
||
})
|
||
})
|
||
if err != nil {
|
||
recordPollingFailure(ctx, s.db, s.auditWriter, auditinfra.PollingInput{
|
||
ActionCode: constants.AuditActionPollingManualCancelled, Summary: "取消手动触发任务失败",
|
||
ResourceType: constants.AuditResourcePollingManualTrigger, ResourceID: log.ID,
|
||
ResourceKey: pollingManualTriggerKey(log.ID), DisplayName: "手动轮询任务",
|
||
OperatorID: triggeredBy, IdentitySnapshot: pollingManualTriggerIdentity(log), Cards: cards,
|
||
}, err)
|
||
}
|
||
return err
|
||
}
|
||
|
||
// GetRunningTasks 获取正在运行的任务
|
||
func (s *ManualTriggerService) GetRunningTasks(ctx context.Context, triggeredBy uint) ([]*model.PollingManualTriggerLog, error) {
|
||
return s.logStore.GetRunning(ctx, triggeredBy)
|
||
}
|
||
|
||
// GetQueueSize 获取手动触发队列大小
|
||
func (s *ManualTriggerService) GetQueueSize(ctx context.Context, taskType string) (int64, error) {
|
||
queueKey := constants.RedisPollingManualQueueKey(taskType)
|
||
return s.redis.LLen(ctx, queueKey).Result()
|
||
}
|
||
|
||
func isValidTaskType(taskType string) bool {
|
||
switch taskType {
|
||
case constants.TaskTypePollingRealname,
|
||
constants.TaskTypePollingCarddata,
|
||
constants.TaskTypePollingPackage:
|
||
return true
|
||
default:
|
||
return false
|
||
}
|
||
}
|
||
|
||
// applyShopPermissionFilter 应用店铺权限过滤(代理只能筛选自己管理的卡)
|
||
func (s *ManualTriggerService) applyShopPermissionFilter(ctx context.Context, filter *ConditionFilter) error {
|
||
skip, err := pollingUserTypePermission(ctx)
|
||
if err != nil || skip {
|
||
return err
|
||
}
|
||
|
||
// 代理账号:限制只能查询自己店铺及下级店铺的卡
|
||
currentShopID := middleware.GetShopIDFromContext(ctx)
|
||
if currentShopID == 0 {
|
||
return errors.New(errors.CodeForbidden, "无权限操作")
|
||
}
|
||
|
||
// 如果用户指定了 ShopID,验证是否在可管理范围内
|
||
if filter.ShopID != nil {
|
||
if err := middleware.CanManageShop(ctx, *filter.ShopID); err != nil {
|
||
return err
|
||
}
|
||
// 已指定有效的 ShopID,无需修改
|
||
return nil
|
||
}
|
||
|
||
// 用户未指定 ShopID,限制为当前用户的店铺(代理只能查自己店铺的卡)
|
||
// 注意:这里限制为当前店铺,而不是所有下级店铺,以避免返回过多数据
|
||
filter.ShopID = ¤tShopID
|
||
|
||
return nil
|
||
}
|