tiered_settle.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. package service
  2. import (
  3. "github.com/QuantumNous/new-api/pkg/billingexpr"
  4. relaycommon "github.com/QuantumNous/new-api/relay/common"
  5. )
  6. // TieredResultWrapper wraps billingexpr.TieredResult for use at the service layer.
  7. type TieredResultWrapper = billingexpr.TieredResult
  8. // TryTieredSettle checks if the request uses tiered_expr billing and, if so,
  9. // computes the actual quota using the frozen BillingSnapshot. Returns:
  10. // - ok=true, quota, result when tiered billing applies
  11. // - ok=false, 0, nil when it doesn't (caller should fall through to existing logic)
  12. func TryTieredSettle(relayInfo *relaycommon.RelayInfo, params billingexpr.TokenParams) (ok bool, quota int, result *billingexpr.TieredResult) {
  13. snap := relayInfo.TieredBillingSnapshot
  14. if snap == nil || snap.BillingMode != "tiered_expr" {
  15. return false, 0, nil
  16. }
  17. requestInput := billingexpr.RequestInput{}
  18. if relayInfo.BillingRequestInput != nil {
  19. requestInput = *relayInfo.BillingRequestInput
  20. }
  21. tr, err := billingexpr.ComputeTieredQuotaWithRequest(snap, params, requestInput)
  22. if err != nil {
  23. quota = relayInfo.FinalPreConsumedQuota
  24. if quota <= 0 {
  25. quota = snap.EstimatedQuotaAfterGroup
  26. }
  27. return true, quota, nil
  28. }
  29. return true, tr.ActualQuotaAfterGroup, &tr
  30. }