继续补齐核心模块 Context 超时控制

This commit is contained in:
yml2213
2026-06-10 11:50:27 +08:00
parent 334436f381
commit d2858c529d
26 changed files with 552 additions and 515 deletions
@@ -37,7 +37,7 @@ func (h *Handler) List(c *gin.Context) {
return
}
resp, err := h.service.List(query)
resp, err := h.service.List(c.Request.Context(), query)
if err != nil {
response.Error(c, http.StatusInternalServerError, "internal_error", "查询失败")
return
@@ -62,7 +62,7 @@ func (h *Handler) Get(c *gin.Context) {
includeSecret := c.Query("include_secret") == "true"
config, err := h.service.Get(id, includeSecret)
config, err := h.service.Get(c.Request.Context(), id, includeSecret)
if err == ErrConfigNotFound {
response.NotFound(c, "配置不存在")
return
@@ -87,7 +87,7 @@ func (h *Handler) ExportBackup(c *gin.Context) {
return
}
backup, err := h.service.ExportBackup(adminID, auditMeta(c))
backup, err := h.service.ExportBackup(c.Request.Context(), adminID, auditMeta(c))
if err == ErrDecryptionFailed {
response.Error(c, http.StatusInternalServerError, "decrypt_failed", "密钥解密失败")
return
@@ -128,7 +128,7 @@ func (h *Handler) ImportBackup(c *gin.Context) {
return
}
result, err := h.service.ImportBackup(backup, adminID, auditMeta(c))
result, err := h.service.ImportBackup(c.Request.Context(), backup, adminID, auditMeta(c))
if err == ErrInvalidBackup || err == ErrEmptyBackup || err == ErrInvalidProvider ||
err == ErrNameRequired || err == ErrMerchantIDRequired || err == ErrGatewayURLRequired ||
err == ErrSignKeyRequired || err == ErrNotifyKeyRequired || err == ErrNotifyURLRequired ||
@@ -168,7 +168,7 @@ func (h *Handler) Create(c *gin.Context) {
return
}
config, err := h.service.Create(req, adminID, auditMeta(c))
config, err := h.service.Create(c.Request.Context(), req, adminID, auditMeta(c))
if err == ErrNameRequired || err == ErrMerchantIDRequired || err == ErrGatewayURLRequired ||
err == ErrSignKeyRequired || err == ErrNotifyKeyRequired || err == ErrInvalidProvider ||
err == ErrNotifyURLRequired || err == ErrInvalidSignType || err == ErrAppIDRequired ||
@@ -210,7 +210,7 @@ func (h *Handler) Update(c *gin.Context) {
return
}
config, err := h.service.Update(id, req, adminID, auditMeta(c))
config, err := h.service.Update(c.Request.Context(), id, req, adminID, auditMeta(c))
if err == ErrConfigNotFound {
response.NotFound(c, "配置不存在")
return
@@ -246,7 +246,7 @@ func (h *Handler) Delete(c *gin.Context) {
return
}
err = h.service.Delete(id, adminID, auditMeta(c))
err = h.service.Delete(c.Request.Context(), id, adminID, auditMeta(c))
if err == ErrConfigNotFound {
response.NotFound(c, "配置不存在")
return
@@ -1,6 +1,7 @@
package paymentconfig
import (
"context"
"encoding/json"
"errors"
"hfb_sys/backend/internal/auditlog"
@@ -26,11 +27,11 @@ func NewRepository(db *gorm.DB, encryptor Encryptor) *Repository {
}
// List 获取配置列表
func (r *Repository) List(query ListQuery) ([]ConfigDTO, int64, error) {
func (r *Repository) List(ctx context.Context, query ListQuery) ([]ConfigDTO, int64, error) {
var items []model.PaymentMerchantConfig
var total int64
db := r.db.Model(&model.PaymentMerchantConfig{})
db := r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{})
// 过滤条件
if query.Provider != "" {
@@ -79,9 +80,9 @@ func (r *Repository) List(query ListQuery) ([]ConfigDTO, int64, error) {
}
// FindByID 根据 ID 查询配置
func (r *Repository) FindByID(id uint64, includeSecret bool) (*ConfigDTO, error) {
func (r *Repository) FindByID(ctx context.Context, id uint64, includeSecret bool) (*ConfigDTO, error) {
var item model.PaymentMerchantConfig
if err := r.db.Where("id = ?", id).First(&item).Error; err != nil {
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&item).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrConfigNotFound
}
@@ -95,9 +96,9 @@ func (r *Repository) FindByID(id uint64, includeSecret bool) (*ConfigDTO, error)
}
// FindDefault 查询默认配置
func (r *Repository) FindDefault(provider string) (*model.PaymentMerchantConfig, error) {
func (r *Repository) FindDefault(ctx context.Context, provider string) (*model.PaymentMerchantConfig, error) {
var item model.PaymentMerchantConfig
if err := r.db.Where("provider = ? AND is_default = ? AND status = ?", provider, true, "active").First(&item).Error; err != nil {
if err := r.db.WithContext(ctx).Where("provider = ? AND is_default = ? AND status = ?", provider, true, "active").First(&item).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNoActiveConfigFound
}
@@ -107,9 +108,9 @@ func (r *Repository) FindDefault(provider string) (*model.PaymentMerchantConfig,
}
// FindDefaultAny 查询任意服务商的默认启用配置。
func (r *Repository) FindDefaultAny(includeSecret bool) (*ConfigDTO, error) {
func (r *Repository) FindDefaultAny(ctx context.Context, includeSecret bool) (*ConfigDTO, error) {
var item model.PaymentMerchantConfig
if err := r.db.Where("status = ?", "active").Order("is_default DESC, id DESC").First(&item).Error; err != nil {
if err := r.db.WithContext(ctx).Where("status = ?", "active").Order("is_default DESC, id DESC").First(&item).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrNoActiveConfigFound
}
@@ -123,8 +124,8 @@ func (r *Repository) FindDefaultAny(includeSecret bool) (*ConfigDTO, error) {
}
// FindDefaultByProvider 查询指定服务商的默认启用配置。
func (r *Repository) FindDefaultByProvider(provider string, includeSecret bool) (*ConfigDTO, error) {
item, err := r.FindDefault(provider)
func (r *Repository) FindDefaultByProvider(ctx context.Context, provider string, includeSecret bool) (*ConfigDTO, error) {
item, err := r.FindDefault(ctx, provider)
if err != nil {
return nil, err
}
@@ -136,9 +137,9 @@ func (r *Repository) FindDefaultByProvider(provider string, includeSecret bool)
}
// FindByProviderMerchant 根据服务商和商户号查配置,用于历史支付单继续使用原商户密钥。
func (r *Repository) FindByProviderMerchant(provider string, merchantID string, includeSecret bool) (*ConfigDTO, error) {
func (r *Repository) FindByProviderMerchant(ctx context.Context, provider string, merchantID string, includeSecret bool) (*ConfigDTO, error) {
var item model.PaymentMerchantConfig
if err := r.db.Where("provider = ? AND merchant_id = ?", provider, merchantID).
if err := r.db.WithContext(ctx).Where("provider = ? AND merchant_id = ?", provider, merchantID).
Order("status = 'active' DESC, is_default DESC, id DESC").
First(&item).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -154,9 +155,9 @@ func (r *Repository) FindByProviderMerchant(provider string, merchantID string,
}
// ExportBackup 导出所有支付配置备份,包含解密后的密钥。
func (r *Repository) ExportBackup(actorID uint64, meta AuditMeta) (*ExportBackup, error) {
func (r *Repository) ExportBackup(ctx context.Context, actorID uint64, meta AuditMeta) (*ExportBackup, error) {
var backup *ExportBackup
err := r.db.Transaction(func(tx *gorm.DB) error {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var items []model.PaymentMerchantConfig
if err := tx.Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
return err
@@ -193,7 +194,7 @@ func (r *Repository) ExportBackup(actorID uint64, meta AuditMeta) (*ExportBackup
}
// ImportBackup 导入支付配置备份,按 provider + merchant_id 更新或新增。
func (r *Repository) ImportBackup(backup ExportBackup, actorID uint64, meta AuditMeta) (*ImportBackupResult, error) {
func (r *Repository) ImportBackup(ctx context.Context, backup ExportBackup, actorID uint64, meta AuditMeta) (*ImportBackupResult, error) {
if backup.Type != "payment_config_backup" || backup.Version <= 0 {
return nil, ErrInvalidBackup
}
@@ -204,7 +205,7 @@ func (r *Repository) ImportBackup(backup ExportBackup, actorID uint64, meta Audi
activeKey := backupActiveKey(backup.Configs)
result := &ImportBackupResult{Total: len(backup.Configs)}
err := r.db.Transaction(func(tx *gorm.DB) error {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if activeKey != "" {
if err := deactivateOtherConfigs(tx, 0, actorID); err != nil {
return err
@@ -299,23 +300,23 @@ func (r *Repository) ImportBackup(backup ExportBackup, actorID uint64, meta Audi
}
// FindActiveByProvider 查询提供商的所有激活配置
func (r *Repository) FindActiveByProvider(provider string) ([]model.PaymentMerchantConfig, error) {
func (r *Repository) FindActiveByProvider(ctx context.Context, provider string) ([]model.PaymentMerchantConfig, error) {
var items []model.PaymentMerchantConfig
if err := r.db.Where("provider = ? AND status = ?", provider, "active").Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
if err := r.db.WithContext(ctx).Where("provider = ? AND status = ?", provider, "active").Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
return nil, err
}
return items, nil
}
// Create 创建配置
func (r *Repository) Create(req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
func (r *Repository) Create(ctx context.Context, req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
// 验证必填字段
if err := r.validateCreateRequest(req); err != nil {
return nil, err
}
var dto ConfigDTO
err := r.db.Transaction(func(tx *gorm.DB) error {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 加密密钥
encryptedSignKey, err := r.encryptor.Encrypt(req.SignKey)
if err != nil {
@@ -388,7 +389,7 @@ func (r *Repository) Create(req CreateRequest, actorID uint64, meta AuditMeta) (
}
// Update 更新配置
func (r *Repository) Update(id uint64, req UpdateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
func (r *Repository) Update(ctx context.Context, id uint64, req UpdateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
if req.SignType != nil && *req.SignType != "" && !isValidSignType(*req.SignType) {
return nil, ErrInvalidSignType
}
@@ -400,7 +401,7 @@ func (r *Repository) Update(id uint64, req UpdateRequest, actorID uint64, meta A
}
var dto ConfigDTO
err := r.db.Transaction(func(tx *gorm.DB) error {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var item model.PaymentMerchantConfig
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&item).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -507,8 +508,8 @@ func (r *Repository) Update(id uint64, req UpdateRequest, actorID uint64, meta A
}
// Delete 删除配置
func (r *Repository) Delete(id uint64, actorID uint64, meta AuditMeta) error {
return r.db.Transaction(func(tx *gorm.DB) error {
func (r *Repository) Delete(ctx context.Context, id uint64, actorID uint64, meta AuditMeta) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var item model.PaymentMerchantConfig
if err := tx.Where("id = ?", id).First(&item).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -540,9 +541,9 @@ func (r *Repository) Delete(id uint64, actorID uint64, meta AuditMeta) error {
}
// IncrementUsage 增加使用统计
func (r *Repository) IncrementUsage(id uint64, amountCent int64) error {
func (r *Repository) IncrementUsage(ctx context.Context, id uint64, amountCent int64) error {
now := time.Now()
return r.db.Model(&model.PaymentMerchantConfig{}).Where("id = ?", id).Updates(map[string]any{
return r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}).Where("id = ?", id).Updates(map[string]any{
"total_transactions": gorm.Expr("total_transactions + ?", 1),
"total_amount_cent": gorm.Expr("total_amount_cent + ?", amountCent),
"last_used_at": now,
@@ -550,11 +551,11 @@ func (r *Repository) IncrementUsage(id uint64, amountCent int64) error {
}
// RecordUsage 记录支付配置命中情况,同一个支付单只记录一次。
func (r *Repository) RecordUsage(configID uint64, paymentOrderID uint64, provider string, merchantID string, amountCent int64, bizType string) error {
func (r *Repository) RecordUsage(ctx context.Context, configID uint64, paymentOrderID uint64, provider string, merchantID string, amountCent int64, bizType string) error {
if configID == 0 || paymentOrderID == 0 {
return nil
}
return r.db.Transaction(func(tx *gorm.DB) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var existing model.PaymentConfigUsageLog
err := tx.Where("payment_order_id = ?", paymentOrderID).First(&existing).Error
if err == nil {
@@ -1,5 +1,7 @@
package paymentconfig
import "context"
type Service struct {
repo *Repository
}
@@ -9,8 +11,8 @@ func NewService(repo *Repository) *Service {
}
// List 获取配置列表
func (s *Service) List(query ListQuery) (*ListResponse, error) {
items, total, err := s.repo.List(query)
func (s *Service) List(ctx context.Context, query ListQuery) (*ListResponse, error) {
items, total, err := s.repo.List(ctx, query)
if err != nil {
return nil, err
}
@@ -33,38 +35,38 @@ func (s *Service) List(query ListQuery) (*ListResponse, error) {
}
// Get 获取单个配置
func (s *Service) Get(id uint64, includeSecret bool) (*ConfigDTO, error) {
return s.repo.FindByID(id, includeSecret)
func (s *Service) Get(ctx context.Context, id uint64, includeSecret bool) (*ConfigDTO, error) {
return s.repo.FindByID(ctx, id, includeSecret)
}
// ExportBackup 导出支付配置备份。
func (s *Service) ExportBackup(actorID uint64, meta AuditMeta) (*ExportBackup, error) {
return s.repo.ExportBackup(actorID, meta)
func (s *Service) ExportBackup(ctx context.Context, actorID uint64, meta AuditMeta) (*ExportBackup, error) {
return s.repo.ExportBackup(ctx, actorID, meta)
}
// ImportBackup 导入支付配置备份。
func (s *Service) ImportBackup(backup ExportBackup, actorID uint64, meta AuditMeta) (*ImportBackupResult, error) {
return s.repo.ImportBackup(backup, actorID, meta)
func (s *Service) ImportBackup(ctx context.Context, backup ExportBackup, actorID uint64, meta AuditMeta) (*ImportBackupResult, error) {
return s.repo.ImportBackup(ctx, backup, actorID, meta)
}
// Create 创建配置
func (s *Service) Create(req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
return s.repo.Create(req, actorID, meta)
func (s *Service) Create(ctx context.Context, req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
return s.repo.Create(ctx, req, actorID, meta)
}
// Update 更新配置
func (s *Service) Update(id uint64, req UpdateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
return s.repo.Update(id, req, actorID, meta)
func (s *Service) Update(ctx context.Context, id uint64, req UpdateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
return s.repo.Update(ctx, id, req, actorID, meta)
}
// Delete 删除配置
func (s *Service) Delete(id uint64, actorID uint64, meta AuditMeta) error {
return s.repo.Delete(id, actorID, meta)
func (s *Service) Delete(ctx context.Context, id uint64, actorID uint64, meta AuditMeta) error {
return s.repo.Delete(ctx, id, actorID, meta)
}
// GetDefaultConfig 获取默认配置(用于支付模块调用)
func (s *Service) GetDefaultConfig(provider string) (*ConfigDTO, error) {
config, err := s.repo.FindDefault(provider)
func (s *Service) GetDefaultConfig(ctx context.Context, provider string) (*ConfigDTO, error) {
config, err := s.repo.FindDefault(ctx, provider)
if err != nil {
return nil, err
}