fix: P1 activation path hardening - Bug 4-9
Bug 4: resolveRenewalActivationSubscription - add fallback by user_id+subscribe_id with SELECT FOR UPDATE when token lookup fails Bug 5: appleIAPNotifyLogic - return error on product ID mapping failure instead of silently dropping the notification Bug 6: NewPurchase fallback query - wrap in transaction with SELECT FOR UPDATE to prevent concurrent duplicate subscription creation Bug 7: appleIAPNotifyLogic - fix UserId=0 by reverse-lookup from original purchase order; create renewal audit order record for DID_RENEW/SUBSCRIBED notifications Bug 8: UpdateOrderStatus - pre-delete cache before DB write (double-delete) to close TOCTOU window between DB update and cache invalidation Bug 9: validateNewUserOnlyEligibilityAtActivation - add Redis distributed lock on user_id to serialise concurrent new-user-only order activations Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -636,7 +636,7 @@ func (l *ActivateOrderLogic) NewPurchase(ctx context.Context, orderInfo *order.O
|
||||
return err
|
||||
}
|
||||
|
||||
if err = validateNewUserOnlyEligibilityAtActivation(ctx, l.svc.DB, orderInfo, sub); err != nil {
|
||||
if err = validateNewUserOnlyEligibilityAtActivation(ctx, l.svc.DB, l.svc.Redis, orderInfo, sub); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -714,18 +714,23 @@ func (l *ActivateOrderLogic) NewPurchase(ctx context.Context, orderInfo *order.O
|
||||
// 兜底:创建新订阅前,查找用户是否已有同套餐的订阅记录(含过期/赠送),
|
||||
// 有则复用旧记录续期,避免出现重复订阅。
|
||||
// 需要同时检查 UserId 和 SubscriptionUserId,因为家庭组绑定前后 owner 可能不同。
|
||||
// 使用 SELECT ... FOR UPDATE 防止并发下多个 worker 同时选中同一订阅并创建重复记录。
|
||||
if userSub == nil {
|
||||
candidateUserIds := []int64{orderInfo.UserId}
|
||||
if orderInfo.SubscriptionUserId > 0 && orderInfo.SubscriptionUserId != orderInfo.UserId {
|
||||
candidateUserIds = append(candidateUserIds, orderInfo.SubscriptionUserId)
|
||||
}
|
||||
var existingSub user.Subscribe
|
||||
if findErr := l.svc.DB.Model(&user.Subscribe{}).
|
||||
Where("user_id IN ? AND token != ''", candidateUserIds).
|
||||
Order("expire_time DESC").
|
||||
Order("updated_at DESC").
|
||||
Order("id DESC").
|
||||
First(&existingSub).Error; findErr == nil {
|
||||
findErr := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
return tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id IN ? AND token != ''", candidateUserIds).
|
||||
Order("expire_time DESC").
|
||||
Order("updated_at DESC").
|
||||
Order("id DESC").
|
||||
First(&existingSub).Error
|
||||
})
|
||||
if findErr == nil {
|
||||
// 家庭组场景:订阅 owner 可能变更(如成员注册的试用 → 被家主收归),
|
||||
// 续期前把 user_id 校正为当前订单的 SubscriptionUserId
|
||||
effectiveOwner := orderInfo.UserId
|
||||
@@ -1512,7 +1517,40 @@ func (l *ActivateOrderLogic) resolveRenewalActivationSubscription(ctx context.Co
|
||||
}
|
||||
userSub, err := l.getUserSubscription(ctx, orderInfo.SubscribeToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// Fallback: token may have been lost (subscription deleted or owner changed).
|
||||
// Locate the most recent subscription by user_id + subscribe_id with FOR UPDATE
|
||||
// to prevent a concurrent worker from renewing the same record twice.
|
||||
targetUserID := orderInfo.UserId
|
||||
if orderInfo.SubscriptionUserId > 0 {
|
||||
targetUserID = orderInfo.SubscriptionUserId
|
||||
}
|
||||
var fallbackSub user.Subscribe
|
||||
txErr := l.svc.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
return tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Model(&user.Subscribe{}).
|
||||
Where("user_id = ? AND subscribe_id = ?", targetUserID, orderInfo.SubscribeId).
|
||||
Where("status IN ?", []int64{0, 1, 2, 3}).
|
||||
Order("expire_time DESC").
|
||||
Order("updated_at DESC").
|
||||
Order("id DESC").
|
||||
First(&fallbackSub).Error
|
||||
})
|
||||
if txErr != nil {
|
||||
logger.WithContext(ctx).Error("CRITICAL: Renewal activation token and fallback lookup both failed",
|
||||
logger.Field("token_error", err.Error()),
|
||||
logger.Field("fallback_error", txErr.Error()),
|
||||
logger.Field("order_no", orderInfo.OrderNo),
|
||||
logger.Field("target_user_id", targetUserID),
|
||||
logger.Field("subscribe_id", orderInfo.SubscribeId),
|
||||
)
|
||||
return nil, fmt.Errorf("renewal activation subscription not found by token or user_id+subscribe_id for order %s: %w", orderInfo.OrderNo, err)
|
||||
}
|
||||
logger.WithContext(ctx).Info("Renewal token lookup failed; found subscription via fallback user_id+subscribe_id",
|
||||
logger.Field("order_no", orderInfo.OrderNo),
|
||||
logger.Field("fallback_subscribe_id", fallbackSub.Id),
|
||||
logger.Field("target_user_id", targetUserID),
|
||||
)
|
||||
userSub = &fallbackSub
|
||||
}
|
||||
if orderInfo.UserId <= 0 {
|
||||
return userSub, nil
|
||||
|
||||
@@ -10,12 +10,14 @@ import (
|
||||
"github.com/perfect-panel/server/internal/model/order"
|
||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||
internaltypes "github.com/perfect-panel/server/internal/types"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func validateNewUserOnlyEligibilityAtActivation(
|
||||
ctx context.Context,
|
||||
db *gorm.DB,
|
||||
rdb *redis.Client,
|
||||
orderInfo *order.Order,
|
||||
sub *subscribe.Subscribe,
|
||||
) error {
|
||||
@@ -31,6 +33,20 @@ func validateNewUserOnlyEligibilityAtActivation(
|
||||
return nil
|
||||
}
|
||||
|
||||
// Acquire a per-user distributed lock so concurrent new-user-only activations
|
||||
// for the same account are serialised. Without this, two workers can both read
|
||||
// historyCount=0 and both pass the check before either has written the order.
|
||||
lockKey := fmt.Sprintf("new_user_only_activate:%d", orderInfo.UserId)
|
||||
const lockTTL = 30 * time.Second
|
||||
acquired, lockErr := rdb.SetNX(ctx, lockKey, orderInfo.OrderNo, lockTTL).Result()
|
||||
if lockErr != nil {
|
||||
return fmt.Errorf("new user only: acquire lock error: %w", lockErr)
|
||||
}
|
||||
if !acquired {
|
||||
return fmt.Errorf("new user only: another activation is in progress for user %d", orderInfo.UserId)
|
||||
}
|
||||
defer rdb.Del(ctx, lockKey)
|
||||
|
||||
eligibility, err := commonLogic.ResolveNewUserEligibility(ctx, db, orderInfo.UserId)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
Reference in New Issue
Block a user