settle.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package billingexpr
  2. // quotaConversion converts raw expression output to quota based on the
  3. // expression version. This is the central dispatch point for future versions
  4. // that may use a different conversion formula.
  5. func quotaConversion(exprOutput float64, snap *BillingSnapshot) float64 {
  6. switch snap.ExprVersion {
  7. default: // v1: coefficients are $/1M tokens prices
  8. return exprOutput / 1_000_000 * snap.QuotaPerUnit
  9. }
  10. }
  11. // ComputeTieredQuota runs the Expr from a frozen BillingSnapshot against
  12. // actual token counts and returns the settlement result.
  13. func ComputeTieredQuota(snap *BillingSnapshot, params TokenParams) (TieredResult, error) {
  14. return ComputeTieredQuotaWithRequest(snap, params, RequestInput{})
  15. }
  16. func ComputeTieredQuotaWithRequest(snap *BillingSnapshot, params TokenParams, request RequestInput) (TieredResult, error) {
  17. cost, trace, err := RunExprByHashWithRequest(snap.ExprString, snap.ExprHash, params, request)
  18. if err != nil {
  19. return TieredResult{}, err
  20. }
  21. quotaBeforeGroup := quotaConversion(cost, snap)
  22. afterGroup := QuotaRound(quotaBeforeGroup * snap.GroupRatio)
  23. crossed := trace.MatchedTier != snap.EstimatedTier
  24. return TieredResult{
  25. ActualQuotaBeforeGroup: quotaBeforeGroup,
  26. ActualQuotaAfterGroup: afterGroup,
  27. MatchedTier: trace.MatchedTier,
  28. CrossedTier: crossed,
  29. }, nil
  30. }