diff --git a/backend/internal/service/balance_notify_dedup_test.go b/backend/internal/service/balance_notify_dedup_test.go new file mode 100644 index 0000000000..156c599330 --- /dev/null +++ b/backend/internal/service/balance_notify_dedup_test.go @@ -0,0 +1,46 @@ +//go:build unit + +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBalanceNotifyDeductionKey(t *testing.T) { + require.Equal(t, "42:req-1", balanceNotifyDeductionKey(42, "req-1")) + require.Equal(t, "42:req-1", balanceNotifyDeductionKey(42, " req-1 ")) + require.Empty(t, balanceNotifyDeductionKey(42, " ")) +} + +func TestBalanceLowReminderKeyIsStablePerDeduction(t *testing.T) { + first := balanceLowReminderKey("42:req-1") + require.NotEmpty(t, first) + require.True(t, strings.HasPrefix(first, "deduction:")) + require.Equal(t, first, balanceLowReminderKey("42:req-1")) + require.NotEqual(t, first, balanceLowReminderKey("42:req-2"), "another deduction must alert again") + require.NotEqual(t, first, balanceLowReminderKey("43:req-1"), "the same request id under another key must not dedup") +} + +func TestBalanceLowReminderKeyFallsBackToUTCDate(t *testing.T) { + require.Regexp(t, `^\d{4}-\d{2}-\d{2}$`, balanceLowReminderKey("")) +} + +func TestBalanceLowDeliveryKeyScopesDedupToTheDeduction(t *testing.T) { + deliveryKey := func(deduction string) string { + return notificationEmailDeliveryKey( + NotificationEmailEventBalanceLow, + "balance_low", + "7", + "user@example.com", + balanceLowReminderKey(deduction), + ) + } + + first := deliveryKey("42:req-1") + require.NotEmpty(t, first) + require.Equal(t, first, deliveryKey("42:req-1"), "replaying the same deduction must hit the same delivery record") + require.NotEqual(t, first, deliveryKey("42:req-2"), "a new crossing on the same day must send again") +} diff --git a/backend/internal/service/balance_notify_service.go b/backend/internal/service/balance_notify_service.go index b7c43f84b9..a11b13a858 100644 --- a/backend/internal/service/balance_notify_service.go +++ b/backend/internal/service/balance_notify_service.go @@ -2,6 +2,8 @@ package service import ( "context" + "crypto/sha256" + "encoding/hex" "fmt" "html" "log/slog" @@ -72,6 +74,14 @@ func resolveBalanceThreshold(threshold float64, thresholdType string, totalRecha // CheckBalanceAfterDeduction checks if balance crossed below threshold after deduction. // Notification is sent only on first crossing: oldBalance >= threshold && newBalance < threshold. func (s *BalanceNotifyService) CheckBalanceAfterDeduction(ctx context.Context, user *User, oldBalance, cost float64) { + s.CheckBalanceAfterDeductionWithKey(ctx, user, oldBalance, cost, "") +} + +// CheckBalanceAfterDeductionWithKey is CheckBalanceAfterDeduction with the +// committed deduction identity. The identity scopes the delivery dedup key, so +// a later deduction that crosses the threshold again alerts even on the same +// UTC day, while a replay of the same deduction stays deduplicated. +func (s *BalanceNotifyService) CheckBalanceAfterDeductionWithKey(ctx context.Context, user *User, oldBalance, cost float64, deductionKey string) { if !s.canNotifyBalance(user) { return } @@ -83,7 +93,29 @@ func (s *BalanceNotifyService) CheckBalanceAfterDeduction(ctx context.Context, u if !crossedDownward(oldBalance, newBalance, effectiveThreshold) { return } - s.dispatchBalanceLowEmail(ctx, user, newBalance, effectiveThreshold, rechargeURL) + s.dispatchBalanceLowEmail(ctx, user, newBalance, effectiveThreshold, rechargeURL, deductionKey) +} + +// balanceNotifyDeductionKey identifies one committed deduction. The billing +// request ID alone can repeat across API keys, so the key ID keeps them apart. +func balanceNotifyDeductionKey(apiKeyID int64, requestID string) string { + requestID = strings.TrimSpace(requestID) + if requestID == "" { + return "" + } + return strconv.FormatInt(apiKeyID, 10) + ":" + requestID +} + +// balanceLowReminderKey scopes the balance-low delivery dedup. A deduction key +// gives every newly committed crossing its own stable reminder key; callers +// without one keep the historical per-UTC-day behavior. +func balanceLowReminderKey(deductionKey string) string { + deductionKey = strings.TrimSpace(deductionKey) + if deductionKey == "" { + return time.Now().UTC().Format("2006-01-02") + } + sum := sha256.Sum256([]byte(deductionKey)) + return "deduction:" + hex.EncodeToString(sum[:]) } // canNotifyBalance checks nil guards and user-level toggle. @@ -121,12 +153,12 @@ func crossedDownward(oldV, newV, threshold float64) bool { } // dispatchBalanceLowEmail sends within the bounded notification task. -func (s *BalanceNotifyService) dispatchBalanceLowEmail(ctx context.Context, user *User, newBalance, threshold float64, rechargeURL string) { +func (s *BalanceNotifyService) dispatchBalanceLowEmail(ctx context.Context, user *User, newBalance, threshold float64, rechargeURL, deductionKey string) { siteName := s.getSiteName(ctx) recipients := s.collectBalanceNotifyRecipients(user) slog.Info("CheckBalanceAfterDeduction: sending notification", "user_id", user.ID, "recipients", recipients, "new_balance", newBalance, "threshold", threshold) - s.sendBalanceLowEmails(ctx, recipients, user.ID, user.Username, user.Email, newBalance, threshold, siteName, rechargeURL) + s.sendBalanceLowEmails(ctx, recipients, user.ID, user.Username, user.Email, newBalance, threshold, siteName, rechargeURL, deductionKey) } // quotaDim describes one quota dimension for notification checking. @@ -333,7 +365,7 @@ func (s *BalanceNotifyService) sendEmails(parent context.Context, recipients []s } // sendBalanceLowEmails sends balance low notification to all recipients. -func (s *BalanceNotifyService) sendBalanceLowEmails(parent context.Context, recipients []string, userID int64, userName, userEmail string, balance, threshold float64, siteName, rechargeURL string) { +func (s *BalanceNotifyService) sendBalanceLowEmails(parent context.Context, recipients []string, userID int64, userName, userEmail string, balance, threshold float64, siteName, rechargeURL, deductionKey string) { displayName := userName if displayName == "" { displayName = userEmail @@ -352,7 +384,7 @@ func (s *BalanceNotifyService) sendBalanceLowEmails(parent context.Context, reci UserID: userID, SourceType: "balance_low", SourceID: firstNonEmpty(strconv.FormatInt(userID, 10), userEmail), - ReminderKey: time.Now().UTC().Format("2006-01-02"), + ReminderKey: balanceLowReminderKey(deductionKey), Variables: map[string]string{ "current_balance": fmt.Sprintf("%.2f", balance), "threshold": fmt.Sprintf("%.2f", threshold), diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 6bf853f48c..95d80bcf37 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -88,6 +88,11 @@ type postUsageBillingParams struct { // path that records only API-key 5h/1d/7d window usage. It must not trigger // balance, subscription, account, platform, or lifetime-key-quota effects. SimpleModeKeyRateLimitOnly bool + // DeductionKey identifies the committed billing request for balance-low + // notification dedup. It is set from the billing command so replays of the + // same deduction keep one notification key, while a later deduction that + // crosses the threshold again gets its own key. + DeductionKey string } var ErrSimpleModeKeyRateLimitBillingUnavailable = errors.New("simple mode api key rate-limit billing unavailable") @@ -360,6 +365,9 @@ func applyUsageBilling(ctx context.Context, requestID string, usageLog *UsageLog } cmd := buildUsageBillingCommand(requestID, usageLog, p) + if cmd != nil { + p.DeductionKey = balanceNotifyDeductionKey(cmd.APIKeyID, cmd.RequestID) + } if cmd == nil || cmd.RequestID == "" || repo == nil { if p.SimpleModeKeyRateLimitOnly { return false, ErrSimpleModeKeyRateLimitBillingUnavailable @@ -525,7 +533,7 @@ func notifyBalanceLow(ctx context.Context, p *postUsageBillingParams, deps *bill "threshold", p.User.BalanceNotifyThreshold, "result_has_new_balance", result != nil && result.NewBalance != nil, ) - deps.balanceNotifyService.CheckBalanceAfterDeduction(ctx, p.User, oldBalance, p.Cost.ActualCost) + deps.balanceNotifyService.CheckBalanceAfterDeductionWithKey(ctx, p.User, oldBalance, p.Cost.ActualCost, p.DeductionKey) } // resolveOldBalance returns the pre-deduction balance. diff --git a/backend/internal/service/gateway_usage_billing_simple_mode_test.go b/backend/internal/service/gateway_usage_billing_simple_mode_test.go index cd65253398..0ff0a6c03e 100644 --- a/backend/internal/service/gateway_usage_billing_simple_mode_test.go +++ b/backend/internal/service/gateway_usage_billing_simple_mode_test.go @@ -84,6 +84,22 @@ func TestApplyUsageBillingSimpleModeDeduplicatesWithoutBalanceEffects(t *testing } } +func TestApplyUsageBillingSetsBalanceNotifyDeductionKey(t *testing.T) { + repo := &simpleModeUsageBillingRepoStub{} + p := &postUsageBillingParams{ + Cost: &CostBreakdown{ActualCost: 3.25, TotalCost: 3.25}, + User: &User{ID: 7}, + APIKey: &APIKey{ID: 13, Quota: 100, RateLimit5h: 10}, + Account: &Account{ID: 9, Type: AccountTypeAPIKey}, + APIKeyService: &apiKeyQuotaUpdaterStub{}, + SimpleModeKeyRateLimitOnly: true, + } + + _, err := applyUsageBilling(context.Background(), "req-42", nil, p, &billingDeps{deferredService: &DeferredService{}}, repo) + require.NoError(t, err) + require.Equal(t, "13:req-42", p.DeductionKey) +} + func TestApplyUsageBillingSimpleModeRejectsLegacyFallback(t *testing.T) { for _, missing := range []string{"repository", "request_id", "api_key"} { t.Run(missing, func(t *testing.T) {