Documentation
¶
Index ¶
- Constants
- func ActionFileCheck(conf *ActionFile) error
- func BatchPreCheck(req *bfe_basic.Request, rmbUnits, tokenUnits int64) bool
- func BatchRelease(batchId string) bool
- func BatchReserve(req *bfe_basic.Request, batchId string, rmbUnits, tokenUnits int64) bool
- func CalcReqUsedQuota(req *bfe_basic.Request, promptTokens, completionTokens int64) int64
- func GetApiKey(req *bfe_basic.Request) string
- func GetImageCountFromReq(req *bfe_basic.Request) int64
- func GetPromptToken(req *bfe_basic.Request) int64
- func GetUUID() string
- func GetVideoCountFromReq(req *bfe_basic.Request) int64
- func ProductRuleConfLoad(filename string, kr *crypto.Keyring) (productRuleConf, error)
- func SetAiAuthInfo(req *bfe_basic.Request, rejectReason string, rejectQuotaPlans []string)
- func SetApiKey(req *bfe_http.Request, apiKey string, authStyle string)
- func SetTokenAuthContext(req *bfe_basic.Request, tok *Token, promptToken int64, ...)
- func UpdateCtxByUsage(ctx *TokenAuthContext, data []byte) bool
- type Action
- type ActionFile
- type ConfModAITokenAuth
- type ModuleAITokenAuth
- func (m *ModuleAITokenAuth) Init(cbs *bfe_module.BfeCallbacks, whs *web_monitor.WebHandlers, cr string) error
- func (m *ModuleAITokenAuth) Name() string
- func (m *ModuleAITokenAuth) ValidateTargetModel(req *bfe_basic.Request, targetModel string) *bfe_basic.AiError
- func (m *ModuleAITokenAuth) ValidateUserTokenByReq(req *bfe_basic.Request) (token *Token, err *bfe_basic.AiError)
- type ModuleAITokenAuthState
- type ProductQuotaPlanFiles
- type ProductQuotaPlans
- type ProductRules
- type ProductRulesFile
- type ProductTokenFiles
- type ProductTokens
- type QuotaPlan
- type QuotaPlanMap
- type Token
- type TokenAuthContext
- type TokenFile
- type TokenRuleTable
Constants ¶
const (
ActionCheckToken = "CHECK_TOKEN"
)
const (
ModAITokenAuth = "mod_ai_token_auth"
)
const REQ_TOKEN_AUTH_CONTEXT = "tokenauth_ctx"
Variables ¶
This section is empty.
Functions ¶
func ActionFileCheck ¶
func ActionFileCheck(conf *ActionFile) error
func BatchPreCheck ¶ added in v1.8.9
BatchPreCheck reports whether every bound quota plan (except PassNoQuota and unlimited ones) can cover the reserve on top of already reserved amounts: available = balance - reserveMirror.
func BatchRelease ¶ added in v1.8.9
BatchRelease releases the reserve mirrors of a batch (terminal status or accepted cancel). Safe to call multiple times: the second call finds no reserve record. Reports whether a reserve record existed.
func BatchReserve ¶ added in v1.8.9
BatchReserve writes the per-plan reserve mirrors and the per-batch reserve record after the upstream accepted the batch creation. Returns false when nothing could be reserved (recorded anyway by the caller; settle bills the actual usage).
func CalcReqUsedQuota ¶
func GetImageCountFromReq ¶ added in v1.8.6
GetImageCountFromReq reads the request body "n" field for image generation requests. It returns at least 1 to avoid under-billing when the field is missing or invalid.
func GetPromptToken ¶
func GetVideoCountFromReq ¶ added in v1.8.7
GetVideoCountFromReq reads the request body "n" field for video generation requests. It returns at least 1 to avoid under-billing when the field is missing or invalid.
func ProductRuleConfLoad ¶
func SetAiAuthInfo ¶ added in v1.8.3
func SetTokenAuthContext ¶
func SetTokenAuthContext(req *bfe_basic.Request, tok *Token, promptToken int64, tags []bfe_basic.ApikeyTag)
SetTokenAuthContext sets the token authentication context in the request
func UpdateCtxByUsage ¶ added in v1.8.3
func UpdateCtxByUsage(ctx *TokenAuthContext, data []byte) bool
UpdateCtxByUsage writes the usage observed in a complete non-streaming body into the shared TokenUsage. It reports whether the upstream carried a usage object at all (issue #1414): presence, not "some value is > 0", is what distinguishes a genuine all-zero usage report from a missing one, and the caller marks the final usage / gates the estimate on it.
Types ¶
type Action ¶
type Action ActionFile
type ActionFile ¶
type ActionFile struct {
Cmd string
}
type ConfModAITokenAuth ¶
type ConfModAITokenAuth struct {
Basic struct {
ProductRulePath string
}
// redis conf
Redis struct {
Bns string // bns name for redis proxy
ConnectTimeout int // connect timeout (ms)
ReadTimeout int // read timeout (ms)
WriteTimeout int // write timeout(ms)
// max idle connections in pool
MaxIdle int
// redis password,ignore if not set
Password string
// max active connections in pool,
// when set 0, there is no connection num limit
MaxActive int
}
Log struct {
OpenDebug bool
}
}
func (*ConfModAITokenAuth) Check ¶
func (cfg *ConfModAITokenAuth) Check(confRoot string) error
type ModuleAITokenAuth ¶
type ModuleAITokenAuth struct {
// contains filtered or unexported fields
}
func NewModuleAITokenAuth ¶
func NewModuleAITokenAuth() *ModuleAITokenAuth
func (*ModuleAITokenAuth) Init ¶
func (m *ModuleAITokenAuth) Init(cbs *bfe_module.BfeCallbacks, whs *web_monitor.WebHandlers, cr string) error
func (*ModuleAITokenAuth) Name ¶
func (m *ModuleAITokenAuth) Name() string
func (*ModuleAITokenAuth) ValidateTargetModel ¶ added in v1.8.8
func (m *ModuleAITokenAuth) ValidateTargetModel(req *bfe_basic.Request, targetModel string) *bfe_basic.AiError
ValidateTargetModel validates the resolved target model against the token's effective allow/block model lists (issue #1387). It must be called only after the target model has been fully resolved (route target override, cluster prefix stripping and cluster model mapping all applied), i.e. on the final model name forwarded to the backend, not the raw client model.
Requests without a TokenAuthContext (no token rule matched, hence no authenticated key) and tokens without allow/block lists pass unchanged, preserving the behavior where the model check is tied to token authentication.
On rejection it records the reject reason via SetAiAuthInfo, counts ReqAuthFail and returns the AiError; the caller converts it into a response before invoking the backend.
func (*ModuleAITokenAuth) ValidateUserTokenByReq ¶
type ModuleAITokenAuthState ¶
type ModuleAITokenAuthState struct {
ReqTotal *metrics.Counter
ReqAuth *metrics.Counter
ReqAuthFail *metrics.Counter
// PriceMissZeroBilled counts billing attempts that ended up billing 0
// because the (model, mode) price entry was absent and no fallback was
// taken (bill_zero action, or fallback_chat with no chat-mode baseline;
// also incremented by the batch settle path for an unpriced batch mode).
// Renamed from PriceLookupMiss by issue #1479 (the old name suggested a
// lookup failure rather than a zero-billed outcome; the metric is not
// consumed by any production dashboard yet, so the rename is one-shot).
PriceMissZeroBilled *metrics.Counter
// PriceRejected counts requests rejected before forwarding because the
// cluster's PriceMissAction is "reject" and the requested (model, mode)
// has no price entry (issue #1479). Such requests never call the upstream
// and are never billed.
PriceRejected *metrics.Counter
// PriceFallbackSubItemMiss counts fallback-billed requests whose chat
// entry lacks sub-item price keys (cache read/write) that the request
// actually used, so those dimensions were billed 0 (issue #1479). The
// accepted residual, made observable; see missingSubitemKeys.
PriceFallbackSubItemMiss *metrics.Counter
// PriceFallbackUsed counts billing attempts whose (model, mode) price
// entry was missing but the cost was recovered by falling back to the
// model's chat-mode price (issue #1408 product decision: an unpriced mode
// is billed the same as chat). Together with the per-request ai_price_miss
// access-log marker it keeps the price-table gap visible.
PriceFallbackUsed *metrics.Counter
// Non2xxEstimateDropped counts requests whose upstream call never
// succeeded (non-2xx) and whose EstimateToken residue (auth-time prompt
// seeding / response-time completion guessing) was dropped from the
// shared TokenUsage so it cannot be reported as model usage
// (issue #1409; restored by #1493 after #1480's reversal was rejected
// against the normative field-definition clause).
Non2xxEstimateDropped *metrics.Counter
// Non2xxRealUsageKept counts non-2xx requests that still carried a real
// parsed usage. Such observations are reported with ai_usage_source=parsed
// (issue #1480; before that they were kept in the shared TokenUsage but
// never reported, issue #1409); a non-zero value means an upstream
// returned usage on an error response.
Non2xxRealUsageKept *metrics.Counter
// UsageUnrecognized counts 2xx requests whose upstream usage was never
// recognized (no final usage parsed) and which are not billable by
// EstimateToken (estimate disabled, or response not completed). Their
// billing fields are zeroed and no RMB deduction happens. Together with
// the per-request ai_usage_source access-log marker this is the
// product-side signal for the billing bypass (issue #1410); a genuine
// zero-usage request parses successfully and never lands here.
UsageUnrecognized *metrics.Counter
// AbortBillingSkipped counts client aborts (RST/close/write failure)
// detected before the final usage was seen AND charged 0 because the
// forwarded-content estimate is disabled (EstimateToken=false). Since
// issue #1478 an abort is billable by the estimate when EstimateToken
// allows (the issue #1352 intent is preserved: only content delivered
// to the client is billed); those requests are counted by
// AbortBillingEstimated instead. It was counted by UsageUnrecognized
// until issue #1414 split the two causes, so that an upstream/parsing
// problem and a client-side disconnect stay separable.
AbortBillingSkipped *metrics.Counter
// AbortBillingEstimated counts client aborts billed by the
// forwarded-content estimate (issue #1478): prompt tokens seeded at
// auth time plus the per-chunk accumulation of content actually
// forwarded to the client before the disconnect. Together with
// AbortBillingSkipped it keeps the billable and the zero-billed abort
// shapes separable.
AbortBillingEstimated *metrics.Counter
// UpstreamDropBilled counts 2xx requests whose upstream connection
// broke mid-response (issue #1474) and which were billed by the
// forwarded-content estimate. Like a billable client abort (#1478),
// content already delivered to the client is real consumption and
// must be charged; this counter keeps the upstream-drop shape
// separable from the client-abort counters and from the issue #1415
// clean-EOF estimate billing.
UpstreamDropBilled *metrics.Counter
// EarlyUsageSuppressed counts 2xx requests where a usage object appeared
// on a non-final event (early usage, issue #1497) but no final usage ever
// followed, and which were billed by the forwarded-content estimate. The
// early usage values fed the protocol context only and were kept out of
// the billing basis, so the billed amount is the #1415 forwarded-content
// estimate rather than the early numbers. Together with the per-request
// ai_usage_source=early_suppressed marker this keeps the shape separable
// from a clean-EOF estimate (no usage object at all) and from an
// unrecognized billing bypass (#1410).
EarlyUsageSuppressed *metrics.Counter
// BillingZeroCost counts 2xx requests that hold an RMB quota plan and were
// charged 0, excluding AI cache hits (which never call the upstream, so
// their zero cost is by design). It is the structural counterpart of
// UsageUnrecognized: instead of covering one billing bypass, it covers
// every zero-cost 2xx request — unrecognized usage, client aborts, batch
// releases, price-table gaps, deduction-time configuration loss — so a new
// bypass shape cannot stay silent. The per-request cause is reported as
// ai_zero_cost_reason (issue #1414).
BillingZeroCost *metrics.Counter
// DeductFailed counts quota deductions that the Redis write rejected.
// Such requests were billed in the log but not charged; the failure used
// to produce only a log line (issue #1414).
DeductFailed *metrics.Counter
// QuotaOverage counts quota deductions that drove the balance negative
// (issue #1476): the plan is in arrears and the overrun is fully
// recorded in the balance. Since the fix, balances are never truncated
// at zero, so a negative balance means cumulative consumption has
// exceeded the plan quota — normal right after a large request exhausts
// a small plan, but a sustained growth under PassNoQuota signals the
// pass-through mode is accumulating unpaid usage.
QuotaOverage *metrics.Counter
}
type ProductQuotaPlanFiles ¶ added in v1.8.3
type ProductQuotaPlanFiles map[string]*quotaPlanFileList
type ProductQuotaPlans ¶ added in v1.8.3
type ProductQuotaPlans map[string]*QuotaPlanMap
type ProductRules ¶
type ProductRules map[string]*tokenRuleList
type ProductRulesFile ¶
type ProductRulesFile map[string]*tokenRuleFileList
type ProductTokenFiles ¶
type ProductTokenFiles map[string]*tokenFileMap
type ProductTokens ¶
type ProductTokens map[string]*tokenMap
type QuotaPlan ¶ added in v1.8.3
type QuotaPlan struct {
Id string
Unlimited bool
PassNoQuota bool
RedisKey string
ExpiredTime int64 // -1 means never expired
Quota int64 // 配额总量,固定点整数:total_token 时为 Token 数;RMB 时为 1e-8 元
Unit string // "total_token" or "RMB"
}
func (*QuotaPlan) HasBalance ¶ added in v1.8.3
type QuotaPlanMap ¶ added in v1.8.3
type TokenAuthContext ¶
type TokenAuthContext struct {
Token *Token
// contains filtered or unexported fields
}
func GetTokenAuthContext ¶
func GetTokenAuthContext(req *bfe_basic.Request) *TokenAuthContext
type TokenFile ¶
type TokenFile struct {
Key string `json:"key"`
KeyId string `json:"key_id"`
Enabled bool `json:"enabled"`
ExpiredTime int64 `json:"expired_time"` // -1 means never expired
UnlimitedQuota bool `json:"unlimited_quota"`
Models *string `json:"allow_models"` // allowed models
BlockModels *string `json:"block_models"` // blocked models
Subnet *string `json:"subnet"` // allowed subnet
Tags []bfe_basic.ApikeyTag
QuotaPlans []string `json:"quota_plans"` // quotaPlan IDs
// contains filtered or unexported fields
}
type TokenRuleTable ¶
type TokenRuleTable struct {
// contains filtered or unexported fields
}
func NewTokenRuleTable ¶
func NewTokenRuleTable() *TokenRuleTable
func (*TokenRuleTable) GetToken ¶
func (t *TokenRuleTable) GetToken(product, key string) (*Token, bool)
func (*TokenRuleTable) Search ¶
func (t *TokenRuleTable) Search(product string) (*tokenRuleList, bool)
func (*TokenRuleTable) Update ¶
func (t *TokenRuleTable) Update(conf productRuleConf)
func (*TokenRuleTable) ValidateUserToken ¶
func (t *TokenRuleTable) ValidateUserToken(product, key string) (token *Token, err error)