Documentation
¶
Index ¶
- Constants
- Variables
- func AiIntentThreshold(question string) float64
- func BatchAffinityKey(cluster, id string) string
- func BatchPathBatchId(path string) string
- func BatchPathFileId(path string) string
- func ClassifyBatchOp(method string, path string) string
- func CreateForbiddenResp(request *Request) *bfe_http.Response
- func CreateInternalResp(request *Request, code int) *bfe_http.Response
- func CreateInternalSrvErrResp(request *Request) *bfe_http.Response
- func CreateSpecifiedContentResp(request *Request, responseCode int, contentType string, content string) *bfe_http.Response
- func DetectAuthStyle(req *Request) string
- func DetectModeFromPath(path string) string
- func ErrorTypeForCode(code string) string
- func ExtractBatchInputFileId(req *Request) string
- func GenLogId() string
- func GetApiKey(req *Request) string
- func IsMultipartUpload(header bfe_http.Header) (boundary string, ok bool)
- func IsOpenAIEndpoint(path string) bool
- func SetAiIntentResolver(fn func(*Request) *AiIntent)
- func SetAiIntentThreshold(fn func(question string) float64)
- func StripV1Prefix(path string) string
- type AiAuthInfo
- type AiBasicInfo
- func (aiinfo *AiBasicInfo) AppendClusterKeyName(clusterName, keyName string)
- func (aiinfo *AiBasicInfo) GetTokenUsage() *TokenUsage
- func (aiinfo *AiBasicInfo) IncrementRetryCount()
- func (aiinfo *AiBasicInfo) IsAllowEstimateToken() bool
- func (aiinfo *AiBasicInfo) IsEarlyUsageSeen() bool
- func (aiinfo *AiBasicInfo) IsFinalUsageSeen() bool
- func (aiinfo *AiBasicInfo) IsPriceMiss() bool
- func (aiinfo *AiBasicInfo) IsResponseCompleted() bool
- func (aiinfo *AiBasicInfo) IsUpstreamDropped() bool
- func (aiinfo *AiBasicInfo) MarkEarlyUsageSeen()
- func (aiinfo *AiBasicInfo) MarkFinalUsageSeen()
- func (aiinfo *AiBasicInfo) MarkPriceMiss()
- func (aiinfo *AiBasicInfo) MarkPriceWarn(shape string)
- func (aiinfo *AiBasicInfo) MarkResponseCompleted()
- func (aiinfo *AiBasicInfo) MarkUpstreamDropped()
- func (aiinfo *AiBasicInfo) PriceWarn() string
- func (aiinfo *AiBasicInfo) SetAllowEstimateToken(allow bool)
- func (aiinfo *AiBasicInfo) SetUsageDisposition(disposition string)
- func (aiinfo *AiBasicInfo) SetUsageSource(source string)
- func (aiinfo *AiBasicInfo) SetZeroCostReason(reason string)
- func (aiinfo *AiBasicInfo) UsageDisposition() string
- func (aiinfo *AiBasicInfo) UsageSource() string
- func (aiinfo *AiBasicInfo) ZeroCostReason() string
- type AiBatchRouteHint
- type AiError
- type AiErrorBody
- type AiErrorDetail
- type AiIntent
- type AiRateLimitHitInfo
- type AiRouteFallback
- type AiRouteResult
- type AiRouteTarget
- type ApikeyTag
- type BackendInfo
- type ClusterKeyName
- type HitPolicyInfo
- type IntentAnswer
- type OperationStage
- type RedirectInfo
- type Request
- func (req *Request) AddTags(name string, ntags []string)
- func (req *Request) CachedCookie() bfe_http.CookieMap
- func (req *Request) CachedQuery() url.Values
- func (req *Request) Cookie(name string) (*bfe_http.Cookie, bool)
- func (r *Request) GetAiBasicInfo() *AiBasicInfo
- func (req *Request) GetAiBatchRouteHint() *AiBatchRouteHint
- func (r *Request) GetAiRateLimitHitInfo() *AiRateLimitHitInfo
- func (r *Request) GetAiRouteResult() *AiRouteResult
- func (r *Request) GetApikeyTags() []ApikeyTag
- func (req *Request) GetContext(key interface{}) interface{}
- func (req *Request) GetTags(name string) []string
- func (r *Request) GetUsrVariable(varName string) string
- func (r *Request) InitAiBasicInfo() *AiBasicInfo
- func (r *Request) InitAiRateLimitHitInfo() *AiRateLimitHitInfo
- func (req *Request) Protocol() string
- func (req *Request) SetAiBatchRouteHint(hint *AiBatchRouteHint)
- func (r *Request) SetAiIntent(v *AiIntent)
- func (r *Request) SetAiRouteResult(result *AiRouteResult)
- func (req *Request) SetContext(key, val interface{})
- func (req *Request) SetRequestTransport(backend *backend.BfeBackend, transport bfe_http.RoundTripper)
- func (r *Request) SetUsrVariable(varName string, val string)
- type RequestRoute
- type RequestStat
- type RequestTags
- type RequestTransport
- type ServerDataConfInterface
- type Session
- func (s *Session) ClearContext()
- func (s *Session) Finish()
- func (s *Session) GetContext(key interface{}) interface{}
- func (s *Session) GetError() (string, error)
- func (s *Session) GetVip() net.IP
- func (s *Session) IncReqNum(count int) int64
- func (s *Session) IncReqNumActive(count int) int64
- func (s *Session) ReadTotal() int
- func (s *Session) ReqNum() int64
- func (s *Session) ReqNumActive() int64
- func (s *Session) SetContext(key, val interface{})
- func (s *Session) SetError(errCode error, errMsg string)
- func (s *Session) SetReqNum(count int)
- func (s *Session) SetReqNumActive(count int)
- func (s *Session) SetTrustSource(isTrustSource bool)
- func (s *Session) String() string
- func (s *Session) TrustSource() bool
- func (s *Session) UpdateReadTotal(total int) int
- func (s *Session) UpdateWriteTotal(total int) int
- func (s *Session) WriteTotal() int
- type SessionStickyBackend
- type TokenTimeInfo
- type TokenUsage
- type WafInfo
Constants ¶
const ( HeaderBfeIP = "X-Bfe-Ip" HeaderBfeLogId = "X-Bfe-Log-Id" HeaderXRequestId = "X-Request-ID" HeaderForwardedHost = "X-Forwarded-Host" HeaderForwardedFor = "X-Forwarded-For" HeaderForwardedPort = "X-Forwarded-Port" HeaderRealIP = "X-Real-Ip" HeaderRealPort = "X-Real-Port" )
const ( VarNameScopeUser = "usr_variable" VarNameScopeBfeReqHeader = "bfe_req_header" VarNameScopeBfeResHeader = "bfe_rsp_header" VarNameScopeBfeReqCookie = "bfe_req_cookie" VarNameScopeBfeResCookie = "bfe_rsp_cookie" VarNameScopeBfeReqQuery = "bfe_req_query" )
const ( REQ_AI_BASIC_CONTEXT = "__REQ_AI_BASIC_CONTEXT" REQ_AI_RATE_LIMIT_HIT = "__REQ_AI_RATE_LIMIT_HIT" )
const ( ModeChat = "chat" ModeCompletion = "completion" ModeImageGeneration = "image_generation" ModeImageEdit = "image_edit" ModeEmbedding = "embedding" ModeAudioSpeech = "audio_speech" ModeAudioTranscription = "audio_transcription" ModeRerank = "rerank" ModeVideoGeneration = "video_generation" ModeOcr = "ocr" ModeSearch = "search" ModeRealtime = "realtime" ModeResponses = "responses" ModeFile = "file" ModeBatch = "batch" )
AI request modes, inferred from request path.
const ( BatchOpUpload = "upload" BatchOpCreate = "create" BatchOpGet = "get" BatchOpList = "list" BatchOpCancel = "cancel" BatchOpDownload = "download" )
Batch operation types (mod_ai_batch), classified from (method, path).
const ( BatchSettleNone = "none" BatchSettleSettle = "settle" // settled by result-file usage at download BatchSettleRelease = "release" // reserve released without settlement )
Batch quota settlement markers written by mod_ai_batch into AiBasicInfo; consumed by mod_ai_token_auth at HandleRequestFinish.
const ( AuthStyleOpenAI = "openai" AuthStyleAnthropic = "anthropic" AuthStyleGemini = "gemini" AuthStyleUnknown = "unknown" )
AI protocol/auth styles.
const ( // PriceWarnNoEntry: the (model, mode) entry is absent and the cluster // action bills 0 ("bill_zero"). PriceWarnNoEntry = "no_entry" // PriceWarnNoBaseline: the entry is absent and there is no chat-mode // baseline to fall back to (bill 0 under the default action). PriceWarnNoBaseline = "no_baseline" // PriceWarnFallback: a non-chat mode was billed at the model's // chat-mode price ("fallback_chat"). PriceWarnFallback = "fallback" // PriceWarnSubitemMissing: the billed entry lacks sub-item price keys // (e.g. cache read/write) that this request actually used, so those // dimensions were billed 0 ("accepted residual"). PriceWarnSubitemMissing = "subitem_missing" // PriceWarnNoModelTable: the cluster model table is missing. PriceWarnNoModelTable = "no_model_table" // PriceWarnReject: the requested interface has no price configured and // the request was rejected before forwarding ("reject" action). PriceWarnReject = "reject" )
Missing-price shapes (issue #1479). They are shared by the ai_price_warn access-log field and the structured PRICE_MISS log line (the log uses them as its "type" token), so reconciliation queries and log greps use one vocabulary.
const ( // UsageDispositionUnset is the zero value: no disposition was judged // (the request did not go through token authentication, or the module // was not loaded). The access-log fields keep their legacy behaviour. UsageDispositionUnset = "" // UsageDispositionNone means the request never successfully called the // upstream (non-2xx response), so no model usage can exist: the access // log must not report ai_input_tokens / ai_output_tokens / // ai_total_tokens, and any auth-time or response-time estimate is // residue, not usage. UsageDispositionNone = "none" // UsageDispositionObserved means the upstream was successfully called // and the shared TokenUsage holds the real parsed usage or the // EstimateToken estimate of this request (issue #1398 keeps that view // observable); the access log reports it as-is. UsageDispositionObserved = "observed" )
Token-usage dispositions for the access log (issue #1409).
const ( // UsageSourceParsed means a final usage was parsed from the upstream // response, decided by the presence of the usage object rather than by // its values (issue #1414): an upstream that explicitly reports all-zero // usage also lands here and is billed at 0, instead of being estimated. UsageSourceParsed = "parsed" // UsageSourceEstimated means the upstream returned no usage at all but the // request is billable by EstimateToken (estimate allowed and response // completed); the approved estimate is mirrored into the shared usage // (issue #1398). UsageSourceEstimated = "estimated" // UsageSourceAborted means the client disconnected (RST/close/write // failure) before the final usage was seen. Since issue #1478 the // marker describes the cause, not the billing outcome: with // EstimateToken enabled the request is billed by the forwarded-content // estimate, with it disabled billing is skipped per the issue #1352 // yardstick and the reported token fields stay auth-time seeding // residue. UsageSourceAborted = "aborted" // UsageSourceUnrecognized means no final usage was parsed and the // request is not estimatable: billing was skipped and the reported // token fields are auth-time seeding residue. UsageSourceUnrecognized = "unrecognized" // UsageSourceUpstreamDropped means the upstream connection broke // mid-response before the final usage was seen (issue #1474). Unlike a // client abort, content already forwarded to the client is real // consumption: the request is billed by the forwarded-content estimate // when EstimateToken allows, or reported unrecognized otherwise. UsageSourceUpstreamDropped = "upstream_dropped" // UsageSourceEarlySuppressed means a usage object arrived on a non-final // event but no final usage ever followed (issue #1497): an early usage // in a non-terminal delta, or Anthropic message_start without a later // message_delta. The early usage fed the protocol context only and was // kept out of the billing basis; with EstimateToken enabled the request // is billed by the forwarded-content estimate per the issue #1415 // yardstick, otherwise it is reported unrecognized. This keeps the // shape separable from both a clean-EOF estimate and a parsed final // usage in ai_usage_source. UsageSourceEarlySuppressed = "early_suppressed" // UsageSourceFailed means the upstream call never succeeded (non-2xx, // including BFE-generated rejections) and the EstimateToken residue would // have been reported for it (issue #1480). Issue #1493 restored the // normative clause that such residue must not be reported at all, so this // value has no producer since then and the token fields of a non-2xx row // without real usage stay absent. A non-2xx response that does carry a // real usage object is reported as parsed. The constant is kept for // log-decoding compatibility with rows written while #1480 was live. UsageSourceFailed = "failed" )
Usage sources for the access log (issue #1410): where the reported token usage came from. Orthogonal to UsageDisposition, which decides whether usage is reported at all; the source is set at the same decision point as the billing-yardstick guard so the signal can never diverge from the billing call.
const ( // ZeroCostReasonUnrecognized: upstream usage was neither recognized nor // estimatable. ZeroCostReasonUnrecognized = "unrecognized" // ZeroCostReasonUpstreamDropped: the upstream connection broke // mid-response and EstimateToken is off, so the forwarded content could // not be billed (issue #1474). ZeroCostReasonUpstreamDropped = "upstream_dropped" // ZeroCostReasonAborted: the client disconnected before the final usage // and the forwarded-content estimate is disabled, so nothing was // billed (issue #1478; a billable abort is charged and carries no // zero-cost reason). ZeroCostReasonAborted = "aborted" // ZeroCostReasonCacheHit: AI cache hit, the upstream was never called. ZeroCostReasonCacheHit = "cache_hit" // ZeroCostReasonBatchRelease: batch contract released without billing. ZeroCostReasonBatchRelease = "batch_release" // ZeroCostReasonPriceMiss: no price entry and no fallback price. ZeroCostReasonPriceMiss = "price_miss" // ZeroCostReasonPriceZero: the price entry exists but the billed // dimensions are priced 0. ZeroCostReasonPriceZero = "price_zero" // ZeroCostReasonModelTableMissing: the cluster model table is missing or // unlookupable. ZeroCostReasonModelTableMissing = "model_table_missing" // ZeroCostReasonConfigMissing: pricing configuration (server data conf / // cluster / target model) is unavailable at billing time. ZeroCostReasonConfigMissing = "config_missing" // ZeroCostReasonNoUsageTokens: no billable token count, although no usage // problem was detected (e.g. a genuine zero-usage response, or image / // video modes with a zero generated count). ZeroCostReasonNoUsageTokens = "no_usage_tokens" // ZeroCostReasonCostZero: fallback for a zero cost with no classified // cause. ZeroCostReasonCostZero = "cost_zero" )
Zero-cost reasons for the access log (issue #1414): why a 2xx request that holds an RMB quota plan was charged 0. Reported as ai_zero_cost_reason and counted by the BillingZeroCost module counter (AI cache hits are marked but not counted: they never call the upstream, so their zero cost is by design).
const ( CodeInvalidRequest = "INVALID_REQUEST" CodeNoApiKey = "NO_API_KEY" CodeInvalidApiKey = "INVALID_API_KEY" CodeKeyDisabled = "KEY_DISABLED" CodeKeyExpired = "KEY_EXPIRED" CodeSubnetNotAllowed = "SUBNET_NOT_ALLOWED" CodeModelNotAllowed = "MODEL_NOT_ALLOWED" CodeRpmLimitExceeded = "RPM_LIMIT_EXCEEDED" CodeTpmLimitExceeded = "TPM_LIMIT_EXCEEDED" CodeConcurrencyLimitExceeded = "CONCURRENCY_LIMIT_EXCEEDED" CodeRateLimitRedisError = "RATE_LIMIT_REDIS_ERROR" CodeQuotaExhausted = "QUOTA_EXHAUSTED" CodeQuotaExpired = "QUOTA_EXPIRED" CodeQuotaPackageDisabled = "QUOTA_PACKAGE_DISABLED" CodeQuotaModelMismatch = "QUOTA_MODEL_MISMATCH" CodeQuotaPlanFailed = "QUOTA_PLAN_FAILED" CodeInternalQuotaError = "INTERNAL_QUOTA_ERROR" CodeContextLengthExceeded = "CONTEXT_LENGTH_EXCEEDED" CodeContentFiltered = "CONTENT_FILTERED" CodeModelInternalError = "MODEL_INTERNAL_ERROR" CodeBackendTimeout = "BACKEND_TIMEOUT" // Batch (mod_ai_batch) limits: file size/line hard ceilings, resolved // from min(bound policies' batch_limits, mod_ai_batch.data global caps) CodeBatchFileTooLarge = "BATCH_FILE_TOO_LARGE" // Batch file ownership check failed (file_id bound to another apikey) CodeBatchFileForbidden = "BATCH_FILE_FORBIDDEN" CodeProviderProtocolMismatch = "PROVIDER_PROTOCOL_MISMATCH" // Gateway-side capacity exhaustion (issue #1441): no usable upstream API // key could be selected for the target cluster (all penalized / weight 0 // / dead). Distinct from CodeUpstreamRateLimited (an upstream-returned // rate limit, normalized by AIConf.NormalizeUpstreamError) and from // RPM/TPM (client quota). CodeNoAvailableKey = "NO_AVAILABLE_KEY" // CodePriceNotConfigured (issue #1479): the requested (model, mode) has no // price entry and the cluster's AIConf.PriceMissAction is "reject", so the // request is rejected before forwarding. A gateway configuration gap, not // a caller error: mapped to 503 and to TypeInternalError. CodePriceNotConfigured = "PRICE_NOT_CONFIGURED" // EPP admission refusal (issue #1482): the EPP scheduler's flow control // could not admit the request. EPP answers with an ext_proc // ImmediateResponse, which bfe surfaces as-is instead of retrying or // falling back to local balancing. // // CodeEppOverload: pool saturated / queue TTL expired (backpressure). A // gateway capacity decision the caller may retry later: 429, // TypeRateLimitError. CodeEppOverload = "EPP_OVERLOAD" // CodeEppNoCapacity: the pool has no capacity for this request (scaled to // zero / no endpoint can serve it): 503, TypeInternalError. CodeEppNoCapacity = "EPP_NO_CAPACITY" // Upstream error normalization catalog (AIConf.NormalizeUpstreamError). // Values are single-sourced in bfe_model_protocol/utils and shared with // the protocol adapters' mapping tables. CodeUpstreamInvalidRequest = bfe_model_protocol.CodeUpstreamInvalidRequest CodeUpstreamRateLimited = bfe_model_protocol.CodeUpstreamRateLimited CodeUpstreamQuotaExhausted = bfe_model_protocol.CodeUpstreamQuotaExhausted CodeUpstreamAuthError = bfe_model_protocol.CodeUpstreamAuthError CodeUpstreamModelNotFound = bfe_model_protocol.CodeUpstreamModelNotFound CodeUpstreamOverloaded = bfe_model_protocol.CodeUpstreamOverloaded CodeUpstreamUnknown = bfe_model_protocol.CodeUpstreamUnknown CodeConfigLoadError = "CONFIG_LOAD_ERROR" // Gateway-side capacity exhaustion with a legitimately empty instance // pool (issue #1453): the balance layer already reported BK_NO_BACKEND, // so the response keeps that business code instead of collapsing it into // BACKEND_UNAVAILABLE. Clients can then tell "no capacity" apart from // "backend failure". CodeNoBackend = "BK_NO_BACKEND" CodeInvalidRequestBody = "INVALID_REQUEST_BODY" CodeModelParamMissing = "MODEL_PARAM_MISSING" CodeUserQuotaExhausted = "USER_QUOTA_EXHAUSTED" CodeSessionQuotaExhausted = "SESSION_QUOTA_EXHAUSTED" CodeFunctionQuotaExhausted = "FUNCTION_QUOTA_EXHAUSTED" CodeCostBudgetExhausted = "COST_BUDGET_EXHAUSTED" CodeGeoRestricted = "GEO_RESTRICTED" CodeTimeWindowRestricted = "TIME_WINDOW_RESTRICTED" // Gateway-side content audit rejection (SC35 TC-02): a request-phase // body-process REJECT is a deterministic policy rejection, not a backend // fault, so it keeps the HTTP 500 business contract with its own code // instead of collapsing into BACKEND_UNAVAILABLE (502) — the same // treatment shape as BK_NO_BACKEND (issue #1453). CodeContentRejected = "CONTENT_REJECTED" )
const ( TypeAuthenticationError = "authentication_error" TypeInvalidRequestError = "invalid_request_error" TypeRateLimitError = "rate_limit_error" TypeQuotaError = "quota_error" TypeInternalError = "internal_error" )
const ( LimitTypeApiKeyQuota = "api_key_quota" LimitTypeRpm = "rpm" LimitTypeTpm = "tpm" LimitTypeConcurrency = "concurrency" LimitTypeErrRedis = "redis_access_error" // Batch limits (mod_ai_batch): file bytes/line ceilings LimitTypeBatchFile = "batch_file" )
const ( IntentQTypeChoice = "choice" IntentQTypeScore = "score" )
intent question types
const ( IntentSourceHeader = "header" // explicitly declared by client request header IntentSourceModel = "model" // classified by decision service IntentSourceCache = "cache" // served from in-process cache )
intent answer sources
const ( SessionNotTrustSource int32 = 0 SessionTrustSource int32 = 1 )
const ( REQ_CHECK_ONLY = "CheckOnly" REQ_NO_CHECK = "NoCheck" REQ_FORBIDDEN = "Forbidden" REQ_OK = "WaitResponse.Pass.Ok" REQ_TIMEOUT = "WaitResponse.Pass.Timeout" REQ_OTHER = "WaitResponse.Pass.Other" NET_ERR = "Net.Error" // net error between go-bfe and waf-server )
const ( WAF_NO_CHECK = 0 // no check for request WAF_CHECKONLY = 1 // check only; from mod_waf_client, not used now WAF_FORBIDDEN = 2 // check and forbidden WAF_PASS = 3 // check and pass WAF_DEGRADE = 4 // check, but pass with degraded WAF_TIMEOUT = 5 // check, but pass with timeout WAF_ERROR = 6 // check and pass with error happened )
const AIKeyAffinityBatchPrefix = "bfe:ai:key_affinity:batch"
AIKeyAffinityBatchPrefix is the Redis namespace of batch-level key affinity bindings, written by mod_ai_batch and read by chooseAIKeyWithAffinity (bfe_server). It intentionally does not follow the configurable [AIKeyAffinity] prefix: batch bindings are an independent namespace so the two mechanisms cannot shadow each other.
const (
COMPLETION_TOKENS_UNKNOWN = -1
)
const CtxAiIntent = "__REQ_AI_INTENT"
const CtxAiRouteResult = "__REQ_AI_ROUTE_RESULT"
const (
GlobalProduct = "global"
)
const HeaderBfeGwError = "X-Bfe-Gw-Error"
HeaderBfeGwError marks gateway-generated error responses. Upstream error normalization skips responses carrying this marker (they are already in the unified AiError format).
const (
REQ_CTX_WAF_INFO = "waf_client.waf_info"
)
const (
SessionStickyBackendKey = "SessionStickyBackendKey"
)
const (
TagsIPLocation = "IPLocationTags"
)
const (
UsrVaraibleNamePrifix = "__usr_variable_name_"
)
Variables ¶
var ( // client error ErrClientTlsHandshake = errors.New("CLIENT_TLS_HANDSHAKE") // tls handshake error ErrClientWrite = errors.New("CLIENT_WRITE") // write client error ErrClientClose = errors.New("CLIENT_CLOSE") // close by peer ErrClientLongHeader = errors.New("CLIENT_LONG_HEADER") // req too long header ErrClientLongUrl = errors.New("CLIENT_LONG_URL") // req too long url ErrClientTimeout = errors.New("CLIENT_TIMEOUT") // timeout ErrClientBadRequest = errors.New("CLIENT_BAD_REQUEST") // bad request ErrClientZeroContentlen = errors.New("CLIENT_ZERO_CONTENTLEN") // zero content length ErrClientExpectFail = errors.New("CLIENT_EXPECT_FAIL") // expect fail ErrClientReset = errors.New("CLIENT_RESET") // client reset connection ErrClientFrame = errors.New("CLIENT_LONG_FRAME") // only used for spdy/http2 // backend error ErrBkFindProduct = errors.New("BK_FIND_PRODUCT") // fail to find product ErrBkFindLocation = errors.New("BK_FIND_LOCATION") // fail to find location ErrBkNoCluster = errors.New("BK_NO_CLUSTER") // no cluster found ErrBkNoSubCluster = errors.New("BK_NO_SUB_CLUSTER") // no sub-cluster found ErrBkNoBackend = errors.New("BK_NO_BACKEND") // no backend found ErrBkRequestBackend = errors.New("BK_REQUEST_BACKEND") // forward request to backend error ErrBkConnectBackend = errors.New("BK_CONNECT_BACKEND") // connect backend error ErrBkWriteRequest = errors.New("BK_WRITE_REQUEST") // write request error (caused by bk or client) ErrBkReadRespHeader = errors.New("BK_READ_RESP_HEADER") // read response error ErrBkRespHeaderTimeout = errors.New("BK_RESP_HEADER_TIMEOUT") // read response timeout ErrBkReadRespBody = errors.New("BK_READ_RESP_BODY") // read response body error (upstream dropped mid-stream) ErrBkTransportBroken = errors.New("BK_TRANSPORT_BROKEN") // conn broken ErrBkRetryTooMany = errors.New("BK_RETRY_TOOMANY") // reach retry max ErrBkNoSubClusterCross = errors.New("BK_NO_SUB_CLUSTER_CROSS") // no sub-cluster found ErrBkCrossRetryBalance = errors.New("BK_CROSS_RETRY_BALANCE") // cross retry balance failed ErrBkBodyProcess = errors.New("BK_BODY_PROCESS") // body process error // EPP admission decision (ext_proc ImmediateResponse), not a transport or // infra failure: the request must not be retried on another EPP address, // must not fall back to local balancing, and must not count against the // EPP circuit breaker (issue #1482). The concrete status code (429/503) // travels through the bal_gslb request context. ErrEppRejected = errors.New("EPP_REJECTED") // GSLB error ErrGslbBlackhole = errors.New("GSLB_BLACKHOLE") // deny by blackhole // AI rate limit deny (mod_ai_rate_limit); global sentinel so that the // server core can distinguish a local policy rejection from an upstream // 429 without importing the module package. ErrAiRateLimit = errors.New("AI_RATE_LIMIT") // deny by mod_ai_rate_limit // AI key exhaustion at the gateway (issue #1441): no usable upstream API // key could be selected for the target cluster. Deliberately NOT // ErrAiRateLimit: cluster fallback must still be allowed. ErrAiNoAvailableKey = errors.New("NO_AVAILABLE_KEY") // no usable ai key )
var ErrorCodeToErrorType = map[string]string{ CodeInvalidRequest: TypeInvalidRequestError, CodeNoApiKey: TypeAuthenticationError, CodeInvalidApiKey: TypeAuthenticationError, CodeKeyDisabled: TypeAuthenticationError, CodeKeyExpired: TypeAuthenticationError, CodeSubnetNotAllowed: TypeAuthenticationError, CodeModelNotAllowed: TypeInvalidRequestError, CodeRpmLimitExceeded: TypeRateLimitError, CodeTpmLimitExceeded: TypeRateLimitError, CodeConcurrencyLimitExceeded: TypeRateLimitError, CodeRateLimitRedisError: TypeRateLimitError, CodeQuotaExhausted: TypeQuotaError, CodeQuotaExpired: TypeQuotaError, CodeQuotaPackageDisabled: TypeQuotaError, CodeQuotaModelMismatch: TypeQuotaError, CodeQuotaPlanFailed: TypeQuotaError, CodeInternalQuotaError: TypeInternalError, CodeContextLengthExceeded: TypeInvalidRequestError, CodeContentFiltered: TypeInvalidRequestError, CodeModelInternalError: TypeInternalError, CodeBackendTimeout: TypeInternalError, CodeBatchFileTooLarge: TypeRateLimitError, CodeBatchFileForbidden: TypeAuthenticationError, CodeConfigLoadError: TypeInternalError, CodeBackendUnavailable: TypeInternalError, CodeNoBackend: TypeInternalError, CodeContentRejected: TypeInvalidRequestError, CodeInvalidRequestBody: TypeInvalidRequestError, CodeModelParamMissing: TypeInvalidRequestError, CodeUserQuotaExhausted: TypeQuotaError, CodeSessionQuotaExhausted: TypeQuotaError, CodeFunctionQuotaExhausted: TypeQuotaError, CodeCostBudgetExhausted: TypeQuotaError, CodeGeoRestricted: TypeAuthenticationError, CodeTimeWindowRestricted: TypeAuthenticationError, CodeProviderProtocolMismatch: TypeInvalidRequestError, CodePriceNotConfigured: TypeInternalError, CodeEppOverload: TypeRateLimitError, CodeEppNoCapacity: TypeInternalError, CodeNoAvailableKey: TypeRateLimitError, CodeUpstreamInvalidRequest: TypeInvalidRequestError, CodeUpstreamRateLimited: TypeRateLimitError, CodeUpstreamQuotaExhausted: TypeQuotaError, CodeUpstreamAuthError: TypeInternalError, CodeUpstreamModelNotFound: TypeInvalidRequestError, CodeUpstreamOverloaded: TypeInternalError, CodeUpstreamUnknown: TypeInternalError, }
ErrorCodeToErrorType maps every catalog code to its error.type.
var ErrorCodeToStatusCode = map[string]int{ CodeInvalidRequest: 400, CodeNoApiKey: 401, CodeInvalidApiKey: 401, CodeKeyDisabled: 403, CodeKeyExpired: 403, CodeSubnetNotAllowed: 403, CodeModelNotAllowed: 400, CodeRpmLimitExceeded: 429, CodeTpmLimitExceeded: 429, CodeConcurrencyLimitExceeded: 429, CodeRateLimitRedisError: 500, CodeQuotaExhausted: 429, CodeQuotaExpired: 429, CodeQuotaPackageDisabled: 429, CodeQuotaModelMismatch: 429, CodeQuotaPlanFailed: 429, CodeInternalQuotaError: 500, CodeContextLengthExceeded: 400, CodeContentFiltered: 400, CodeModelInternalError: 500, CodeBackendTimeout: 504, CodeBatchFileTooLarge: 413, CodeBatchFileForbidden: 404, CodeConfigLoadError: 500, CodeBackendUnavailable: 502, CodeNoBackend: 500, CodeContentRejected: 500, CodeInvalidRequestBody: 400, CodeModelParamMissing: 400, CodeUserQuotaExhausted: 429, CodeSessionQuotaExhausted: 429, CodeFunctionQuotaExhausted: 429, CodeCostBudgetExhausted: 429, CodeGeoRestricted: 403, CodeTimeWindowRestricted: 403, CodeProviderProtocolMismatch: 400, CodePriceNotConfigured: 503, CodeEppOverload: 429, CodeEppNoCapacity: 503, CodeUpstreamInvalidRequest: 400, CodeUpstreamRateLimited: 429, CodeUpstreamQuotaExhausted: 429, CodeUpstreamAuthError: 502, CodeUpstreamModelNotFound: 404, CodeUpstreamOverloaded: 503, CodeUpstreamUnknown: 502, CodeNoAvailableKey: 429, }
var HopHeaders = []string{
"Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te",
"Trailers",
"Transfer-Encoding",
"Upgrade",
}
HopHeaders are Hop-by-hop headers. These are removed when sent to the backend. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
Functions ¶
func AiIntentThreshold ¶ added in v1.8.9
AiIntentThreshold returns the current effective confidence gate of a question. Without an injected threshold (module not loaded) it is 0, i.e. only the presence of an answer is required.
func BatchAffinityKey ¶ added in v1.8.9
BatchAffinityKey builds the binding key for a batch or file identifier.
func BatchPathBatchId ¶ added in v1.8.9
BatchPathBatchId extracts the {id} segment of /batches/{id}[/cancel].
func BatchPathFileId ¶ added in v1.8.9
BatchPathFileId extracts the {id} segment of /files/{id}[/content].
func ClassifyBatchOp ¶ added in v1.8.9
ClassifyBatchOp maps (method, request path) to a batch operation type. It mirrors the endpoint coverage of openAIEndpointModes: the /files and /batches entries match their sub-paths by prefix, so /files/{id} and /files/{id}/content arrive here with ModeFile, and /batches/{id} and /batches/{id}/cancel with ModeBatch. Returns "" for operations not intercepted (e.g. DELETE /files/{id}). Shared by mod_ai_batch and mod_ai_rate_limit.
func CreateForbiddenResp ¶
CreateForbiddenResp returns a HTTP 403 response
func CreateInternalSrvErrResp ¶
CreateInternalSrvErrResp returns a HTTP 500 response
func CreateSpecifiedContentResp ¶ added in v1.8.0
func DetectAuthStyle ¶ added in v1.8.6
DetectAuthStyle infers the AI protocol/auth style from request characteristics. It is purely based on request path/headers and does not rely on user routing rules.
func DetectModeFromPath ¶ added in v1.8.6
DetectModeFromPath infers the AI request mode from the request path. It defaults to ModeChat for unknown paths to keep backward compatibility.
OpenAI standard endpoints are recognized with or without the /v1 version prefix: both /v1/embeddings and /embeddings map to ModeEmbedding, so the billing mode never depends on whether the client entry carries /v1 (consistent with the upstream path rewrite, issue #1379 follow-up). Provider-native entries whose prefix ends in a /v1 segment (the OpenAI SDK base_url form, e.g. /compatible-mode/v1/responses) reduce to the same endpoints (issue #1382).
func ErrorTypeForCode ¶ added in v1.8.9
ErrorTypeForCode returns the error.type for a catalog code, defaulting to internal_error for unknown codes.
func ExtractBatchInputFileId ¶ added in v1.8.9
ExtractBatchInputFileId parses input_file_id from a buffered batch create request body. Returns "" when the body is not fully buffered or does not parse. Used by the reverse proxy to derive the batch affinity hint before module callbacks run.
func GenLogId ¶ added in v1.8.9
func GenLogId() string
GenLogId generates the unified log id shared by the session id, the request log id and the X-Bfe-Log-Id header.
Format (bfenetworks/bfe#1417): a decimal string denoting a value in [1, 2^63-1]. The access log carries the same value as a uint64 (`BfeLog.logid`), so the string must be convertible without truncation; the previous 32-char hex format (128 bits) could not fit that field and was silently written as 0, which turned the report table's dedup key into a same-second overwrite (n-1 of n concurrent rows lost).
The value is masked to 63 bits on purpose: logid is stored as a signed BIGINT on MySQL / Doris / StarRocks, and an out-of-range value would be truncated to the boundary value by Doris (non-strict), making every high-bit row collide, or reject the whole batch on MySQL (Error 1264).
Shared since bfenetworks/bfe#1441 (round 2): gateway-generated AI error responses also use it as the last fallback of the X-Bfe-Log-Id correlation header, so the generator lives here (bfe_basic) instead of mod_logid.
func IsMultipartUpload ¶ added in v1.8.9
IsMultipartUpload reports whether the request body is a multipart envelope and returns its boundary. Batch file limits (max_file_bytes/max_file_lines) are defined on the `file` part content, never on the envelope (boundary lines, part headers, other form fields), so callers must not measure Content-Length against the limits when this returns true. Shared by mod_ai_batch and mod_ai_rate_limit.
func IsOpenAIEndpoint ¶ added in v1.8.8
IsOpenAIEndpoint reports whether path (with any /v1 prefix already stripped) is a recognized OpenAI API endpoint, i.e. listed in openAIEndpointModes. Used by the bfe_server upstream path rewrite to decide whether the configured base path applies.
func SetAiIntentResolver ¶ added in v1.8.9
func SetAiIntentThreshold ¶ added in v1.8.9
func StripV1Prefix ¶ added in v1.8.8
StripV1Prefix strips a leading "/v1" version prefix from an OpenAI-style request path: "/v1/chat/completions" -> "/chat/completions"; paths without the prefix (including "/v10/xxx" and provider-native paths such as "/compatible-mode/v1/chat/completions") are returned unchanged. Shared by DetectModeFromPath and the bfe_server path rewrite so both treat the optional /v1 entry prefix identically.
Types ¶
type AiAuthInfo ¶ added in v1.8.3
type AiBasicInfo ¶ added in v1.8.3
type AiBasicInfo struct {
ClientApiKey string
ClientKeyId string
ClientModel string
TargetModel string
Mode string // request mode, e.g. chat, image_generation
Provider string // upstream model provider, e.g. openai, deepseek
AuthStyle string // request protocol/auth style, e.g. openai, anthropic
RetryCount uint32 // model invocation retry count (key-level retry)
CostCurrency string // cost currency, e.g. RMB, USD
ApikeyTags []ApikeyTag
TokenTimeInfo TokenTimeInfo
AiAuthInfo AiAuthInfo
ClusterKeyNames []ClusterKeyName // tried (cluster, key) pairs during request processing
// AI cache (mod_ai_cache) result
AiCacheHit bool // true when the response was served from the AI cache
AiCacheStatus string // cache status: hit / hit_semantic / miss / skip, empty if cache not enabled
AiCacheKey string // cache key, only filled when mod_ai_cache debug is on
AiCacheSemantic bool // true when the hit comes from the semantic (vector) cache
AiCacheSimilarity float64 // normalized similarity [0,1] of a semantic cache hit, 0 if not applicable
// AI context compress (mod_ai_context) result
ContextCompressStatus string // "" = not processed; skip_* / trim / rewrite / repair_rollback (also the fallback idempotency guard)
ContextTokensBefore int64 // estimated tokens before context compression (heuristic estimate)
ContextTokensAfter int64 // estimated tokens after context compression, 0 if not compressed
ContextCompressMode string // effective mode: conservative / balanced / aggressive
// Provider-level compensating normalization (AIConf.EnsureReasoningContent):
// true when this request had an empty reasoning_content injected on at least
// one assistant message inside the upstream validation window.
ReasoningPatched bool
// Traffic mirroring (mod_traffic_mirror) result: only synchronous fields
// are recorded here; async mirror results (status/usage/latency) are
// reported via module Prometheus metrics and are not written back
MirrorHit bool // true when the request was selected for mirroring
MirrorCluster string // mirror target cluster name, empty if not mirrored
// Upstream error normalization (AIConf.NormalizeUpstreamError) result;
// all fields stay at zero values when normalization is disabled or the
// response is not an upstream error
UpstreamStatus int32 // original upstream HTTP status, 0 = not recorded
UpstreamErrCode string // original upstream error code (redacted)
ErrNormalized bool // true when the upstream error was rewritten into the unified error body
ErrNormalizeMiss bool // true when the parser did not recognize the upstream error body
StreamErrorRewritten bool // true when at least one SSE error event of the stream was rewritten
StreamTruncated bool // true when the stream ended without the protocol's terminal event
// ClientClosedAfterComplete is true when the response was fully delivered
// (the protocol terminal event had been parsed) and the client then closed
// the connection without waiting for the HTTP EOF. Such a request is not a
// client abort and not a write failure: no err_code is set and
// ERR_CLIENT_WRITE is not counted (issue #1473).
ClientClosedAfterComplete bool
// UpstreamKey holds the last injected upstream credential; it is the
// pattern source for error-body credential redaction and must never be
// written to logs or responses.
UpstreamKey string
// Batch task (mod_ai_batch) context: filled on files/batches operations.
// BatchSettle carries the quota settlement contract consumed by
// mod_ai_token_auth: "settle" (price the parsed usage at batch price and
// release the reserve), "release" (release the reserve only) or "none".
BatchId string // batch_xxx, empty for non-batch traffic
BatchFileId string // file-xxx, empty when unknown
BatchOp string // BatchOp*: upload/create/get/list/cancel/download
BatchLines int64 // jsonl line count (upload counting / output parsing)
BatchBytes int64 // file bytes (upload counting / provider response)
BatchStatus string // provider status snapshot: validating/.../cancelling
BatchSettle string // BatchSettle*: none/settle/release
BatchSettleId string // idempotency key for settle/release (batch_id)
// Batch effective file limits, computed by mod_ai_rate_limit as
// min(bound policies' batch_limits, mod_ai_batch.data global hard
// ceiling); consumed by mod_ai_batch pre-forward checks. 0 = unlimited.
BatchEffMaxFileBytes int64
BatchEffMaxFileLines int64
// BatchUsageByModel carries per-model usage aggregated from a batch
// result file, keyed by target model; consumed by mod_ai_token_auth to
// price the settlement at mode=batch rates per model group.
BatchUsageByModel map[string]TokenUsage
// BatchSettleApplied reports whether this request actually executed the
// settle/release contract: mod_ai_token_auth sets it once the
// BATCH_SETTLED claim is won and the deduction/release ran. mod_ai_batch
// persists the settlement fields into BATCH_TASK only when it is true, so
// a batch already settled/released by another path (control-plane
// reconcile backstop, concurrent download) is never re-marked.
BatchSettleApplied bool
// BatchSettledUnits carries the RMB amount (1e-8 fixed-point units)
// actually charged by the settlement, published alongside
// BatchSettleApplied so mod_ai_batch can persist BATCH_TASK.settle_units.
// Zero is a legitimate value (price miss, no usage) and is still written.
BatchSettledUnits int64
// contains filtered or unexported fields
}
func (*AiBasicInfo) AppendClusterKeyName ¶ added in v1.8.5
func (aiinfo *AiBasicInfo) AppendClusterKeyName(clusterName, keyName string)
func (*AiBasicInfo) GetTokenUsage ¶ added in v1.8.3
func (aiinfo *AiBasicInfo) GetTokenUsage() *TokenUsage
func (*AiBasicInfo) IncrementRetryCount ¶ added in v1.8.5
func (aiinfo *AiBasicInfo) IncrementRetryCount()
func (*AiBasicInfo) IsAllowEstimateToken ¶ added in v1.8.4
func (aiinfo *AiBasicInfo) IsAllowEstimateToken() bool
func (*AiBasicInfo) IsEarlyUsageSeen ¶ added in v1.9.0
func (aiinfo *AiBasicInfo) IsEarlyUsageSeen() bool
IsEarlyUsageSeen reports whether MarkEarlyUsageSeen was recorded.
func (*AiBasicInfo) IsFinalUsageSeen ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) IsFinalUsageSeen() bool
func (*AiBasicInfo) IsPriceMiss ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) IsPriceMiss() bool
IsPriceMiss reports whether MarkPriceMiss was recorded for this request.
func (*AiBasicInfo) IsResponseCompleted ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) IsResponseCompleted() bool
func (*AiBasicInfo) IsUpstreamDropped ¶ added in v1.9.0
func (aiinfo *AiBasicInfo) IsUpstreamDropped() bool
IsUpstreamDropped reports whether MarkUpstreamDropped was recorded.
func (*AiBasicInfo) MarkEarlyUsageSeen ¶ added in v1.9.0
func (aiinfo *AiBasicInfo) MarkEarlyUsageSeen()
MarkEarlyUsageSeen records that a usage object was parsed from a non-final event (issue #1497): an early usage in a non-terminal delta, or the Anthropic message_start initial usage. The usage is protocol context only and must not be billed as the final usage.
func (*AiBasicInfo) MarkFinalUsageSeen ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) MarkFinalUsageSeen()
func (*AiBasicInfo) MarkPriceMiss ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) MarkPriceMiss()
MarkPriceMiss records that the request's (model, mode) price entry was absent and its cost was computed with a fallback (or billed 0); the access log reports it as ai_price_miss (issue #1408).
func (*AiBasicInfo) MarkPriceWarn ¶ added in v1.9.0
func (aiinfo *AiBasicInfo) MarkPriceWarn(shape string)
MarkPriceWarn records a missing-price shape, keeping the most specific one.
func (*AiBasicInfo) MarkResponseCompleted ¶ added in v1.8.7
func (aiinfo *AiBasicInfo) MarkResponseCompleted()
func (*AiBasicInfo) MarkUpstreamDropped ¶ added in v1.9.0
func (aiinfo *AiBasicInfo) MarkUpstreamDropped()
MarkUpstreamDropped records that the upstream connection broke before the response body was fully delivered (issue #1474).
func (*AiBasicInfo) PriceWarn ¶ added in v1.9.0
func (aiinfo *AiBasicInfo) PriceWarn() string
PriceWarn returns the recorded missing-price shape ("" when none applied).
func (*AiBasicInfo) SetAllowEstimateToken ¶ added in v1.8.4
func (aiinfo *AiBasicInfo) SetAllowEstimateToken(allow bool)
func (*AiBasicInfo) SetUsageDisposition ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) SetUsageDisposition(disposition string)
SetUsageDisposition records whether the token usage of this request may be reported by the access log (issue #1409).
func (*AiBasicInfo) SetUsageSource ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) SetUsageSource(source string)
SetUsageSource records where the reported token usage came from (issue #1410); the access log reports it as ai_usage_source.
func (*AiBasicInfo) SetZeroCostReason ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) SetZeroCostReason(reason string)
SetZeroCostReason records why a zero-cost request was charged 0 (issue #1414); the access log reports it as ai_zero_cost_reason.
func (*AiBasicInfo) UsageDisposition ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) UsageDisposition() string
UsageDisposition returns the token-usage disposition set at request finish (UsageDispositionUnset when it was never judged).
func (*AiBasicInfo) UsageSource ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) UsageSource() string
UsageSource returns the usage source set at request finish (empty when it was never judged, e.g. the upstream call never succeeded).
func (*AiBasicInfo) ZeroCostReason ¶ added in v1.8.9
func (aiinfo *AiBasicInfo) ZeroCostReason() string
ZeroCostReason returns the zero-cost reason (empty when the request was billed, when no RMB plan was bound, or when nothing judged it).
type AiBatchRouteHint ¶ added in v1.8.9
type AiBatchRouteHint struct {
BatchId string // batch_xxx for /v1/batches/{id}[...] operations
FileId string // file-xxx for /v1/files/{id}[...] operations
}
AiBatchRouteHint carries the batch/file identifiers of the current request from mod_ai_batch (which classifies the operation) to the reverse proxy (which performs batch-level key affinity in chooseAIKeyWithAffinity). It lives in bfe_basic so that bfe_server does not import module packages.
type AiError ¶ added in v1.8.3
type AiError struct {
Code string `json:"code"`
Type string `json:"type"`
Param *string `json:"param"`
Message string `json:"message"`
Details *AiErrorDetail `json:"details"`
}
func NewAiError ¶ added in v1.8.3
func NewAiErrorWithDetails ¶ added in v1.8.3
func NewAiErrorWithDetails(code, typeStr, message string, details *AiErrorDetail) *AiError
func (*AiError) CreateErrorResponse ¶ added in v1.8.3
func (*AiError) GenRespBody ¶ added in v1.8.3
func (aiError *AiError) GenRespBody() *AiErrorBody
func (*AiError) GenRespBodyStr ¶ added in v1.8.3
type AiErrorBody ¶ added in v1.8.3
type AiErrorBody struct {
Error AiError `json:"error"`
}
type AiErrorDetail ¶ added in v1.8.3
type AiErrorDetail struct {
ApiKey string `json:"api_key"`
KeyId string `json:"key_id"`
QuotaPlanId string `json:"quota_plan_id"`
LimitType string `json:"limit_type"`
Model string `json:"model"`
RetryAfterSeconds int `json:"retry_after_seconds"`
// UpstreamStatus/UpstreamCode are set by upstream error normalization
// (AIConf.NormalizeUpstreamError): the vendor's original HTTP status
// and error code, for cross-checking vendor documentation.
UpstreamStatus *int `json:"upstream_status,omitempty"`
UpstreamCode string `json:"upstream_code,omitempty"`
}
type AiIntent ¶ added in v1.8.9
type AiIntent struct {
QuestionsVersion string // version of the questions conf in use
Answers map[string]*IntentAnswer // answers by question name
Source string // answer source: header / model / cache
BackendVersion string // decision service backend version
LatencyMs int64 // classification latency in milliseconds
Resolved bool // true once resolve finished (even if all unknown)
ConsumedQuestion string // first question evaluated by route conditions; "" if none
ConsumedUnknown bool // that answer was below threshold (derived at read time)
}
AiIntent holds intent classification results for a request.
func GetAiIntent ¶ added in v1.8.9
GetAiIntent returns the intent classification result of the request, triggering lazy resolve on first call via the injected resolver.
type AiRateLimitHitInfo ¶ added in v1.8.3
type AiRateLimitHitInfo struct {
HitPolicyDict map[string]*HitPolicyInfo `json:"hit_rate_limit_policys"` //limite policy id -> HitPolicyInfo
}
func (*AiRateLimitHitInfo) GetPolicyHitInfo ¶ added in v1.8.3
func (obj *AiRateLimitHitInfo) GetPolicyHitInfo(policyId string) *HitPolicyInfo
type AiRouteFallback ¶ added in v1.8.4
type AiRouteResult ¶ added in v1.8.4
type AiRouteResult struct {
RouteType string // apikey / entity / global
Owner string // route table owner
RuleName string // hit rule name
Targets []AiRouteTarget
Fallbacks []AiRouteFallback
}
type AiRouteTarget ¶ added in v1.8.4
type BackendInfo ¶
type ClusterKeyName ¶ added in v1.8.5
ClusterKeyName represents a tried cluster and API-Key pair during request processing
type HitPolicyInfo ¶ added in v1.8.3
type IntentAnswer ¶ added in v1.8.9
type IntentAnswer struct {
QType string // question type: choice / score
Choice string // selected option; for score, level name derived from Score
Score float64 // expected level index, for score questions
LevelNames []string // ordered level names (low to high), for score questions
Probabilities map[string]float64 // option name / level name -> probability
AnswerConfidence float64 // confidence of the reported answer
Unknown bool // derived at read time, see Match()
}
IntentAnswer is the answer of a single intent question. It stores raw probabilities only: the Unknown flag is never persisted but derived at read time against the current MinConfidence threshold, so threshold hot-update takes effect immediately without re-classification.
type OperationStage ¶
type OperationStage int
const ( StageStartConn OperationStage = iota StageReadReqHeader StageReadReqBody StageConnBackend StageWriteBackend StageReadResponseHeader StageReadResponseBody StageWriteClient StageEndRequest )
type RedirectInfo ¶
type Request ¶
type Request struct {
Connection net.Conn
Session *Session
RemoteAddr *net.TCPAddr // address of remote peer
ClientAddr *net.TCPAddr // address of real client. Maybe nil if request is from
HttpRequest *bfe_http.Request // incoming request
OutRequest *bfe_http.Request // forwarded request
HttpResponse *bfe_http.Response // corresponding response
CookieMap bfe_http.CookieMap // cookie map
Query url.Values // save url query
LogId string // log id for each request
ReqBody []byte // req body, size is limited
ReqBodyPeeked bool // whether req body has been peeked
Route RequestRoute // for get backend cluster based on host/path/query/header/...
Tags RequestTags // request tag info
Trans RequestTransport // request transport
BfeStatusCode int // request directly return by bfe
ErrCode error // error code for handling request
ErrMsg string // additional error msg
Stat *RequestStat // time, data length, etc.
RetryTime int // times of retry
Backend BackendInfo // backend info
Redirect RedirectInfo // redirect info
SvrDataConf ServerDataConfInterface // interface for ServerDataConf
// User context associated with this request
Context map[interface{}]interface{}
IsSse bool
}
Request is a wrapper of HTTP request
func NewRequest ¶
func NewRequest(request *bfe_http.Request, conn net.Conn, stat *RequestStat, session *Session, svrDataConf ServerDataConfInterface) *Request
NewRequest creates and initializes a new request.
func (*Request) CachedCookie ¶
func (*Request) CachedQuery ¶
func (*Request) GetAiBasicInfo ¶ added in v1.8.3
func (r *Request) GetAiBasicInfo() *AiBasicInfo
Get user context by key.
func (*Request) GetAiBatchRouteHint ¶ added in v1.8.9
func (req *Request) GetAiBatchRouteHint() *AiBatchRouteHint
GetAiBatchRouteHint returns the hint set by mod_ai_batch, or nil.
func (*Request) GetAiRateLimitHitInfo ¶ added in v1.8.3
func (r *Request) GetAiRateLimitHitInfo() *AiRateLimitHitInfo
func (*Request) GetAiRouteResult ¶ added in v1.8.4
func (r *Request) GetAiRouteResult() *AiRouteResult
func (*Request) GetApikeyTags ¶ added in v1.8.3
func (*Request) GetContext ¶
func (req *Request) GetContext(key interface{}) interface{}
func (*Request) GetUsrVariable ¶ added in v1.9.0
Get user variable by key.
func (*Request) InitAiBasicInfo ¶ added in v1.8.3
func (r *Request) InitAiBasicInfo() *AiBasicInfo
Set user context by key and val.
func (*Request) InitAiRateLimitHitInfo ¶ added in v1.8.3
func (r *Request) InitAiRateLimitHitInfo() *AiRateLimitHitInfo
func (*Request) SetAiBatchRouteHint ¶ added in v1.8.9
func (req *Request) SetAiBatchRouteHint(hint *AiBatchRouteHint)
SetAiBatchRouteHint attaches the hint to the request context.
func (*Request) SetAiIntent ¶ added in v1.8.9
func (*Request) SetAiRouteResult ¶ added in v1.8.4
func (r *Request) SetAiRouteResult(result *AiRouteResult)
func (*Request) SetContext ¶
func (req *Request) SetContext(key, val interface{})
func (*Request) SetRequestTransport ¶
func (req *Request) SetRequestTransport(backend *backend.BfeBackend, transport bfe_http.RoundTripper)
func (*Request) SetUsrVariable ¶ added in v1.9.0
Set user variable by varName and val.
type RequestRoute ¶
type RequestStat ¶
type RequestStat struct {
// time stat
ReadReqStart time.Time // after read first line of http request
ReadReqEnd time.Time // after read http request
FindProStart time.Time // just before find product
FindProEnd time.Time // after find product
LocateStart time.Time // just before find location
LocateEnd time.Time // after find location
ClusterStart time.Time // just before connect backend cluster
ClusterEnd time.Time // after get response from backend cluster
// info for last successful connected backend
BackendStart time.Time // just before connect backend
BackendEnd time.Time // after get response from backend
ResponseStart time.Time // before write response to client
ResponseEnd time.Time // after write response to client
BackendFirst time.Time // just before connect backend, for first invoke (retry may exist)
// data length
HeaderLenIn int // length of request header
BodyLenIn int // length of request body
HeaderLenOut int // length of response header
BodyLenOut int // length of response body
// some status
IsCrossCluster bool // with cross-cluster retry?
}
func NewRequestStat ¶
func NewRequestStat(start time.Time) *RequestStat
type RequestTags ¶
type RequestTransport ¶
type RequestTransport struct {
Backend *backend.BfeBackend // destination backend for request
Transport bfe_http.RoundTripper // transport to backend
}
type ServerDataConfInterface ¶
type ServerDataConfInterface interface {
ClusterTableLookup(clusterName string) (*bfe_cluster.BfeCluster, error)
HostTableLookup(hostname string) (string, error)
}
ServerDataConfInterface is an interface used for lookup config for each request
type Session ¶
type Session struct {
SessionId string // session id
StartTime time.Time // time of accept the connection
EndTime time.Time // time of close connection
Overhead time.Duration
Connection net.Conn
RemoteAddr *net.TCPAddr // client address
Use100Continue bool // "expect 100-continue" is used?
Proto string // protocol for the connection
IsSecure bool // over tls connection?
TlsState *tls.ConnectionState // tls state when using TLS
// TlsClientAuth/TlsClientCAName are filled by bfe_server from the
// matched tls rule after handshake (std tls.ConnectionState has no
// such fields; they were extensions of the removed bfe_tls fork)
TlsClientAuth bool
TlsClientCAName string
Vip net.IP // the virtual ip visited
Vport int // vip virtual port visited
Product string // product name of vip
Rtt uint32 // smoothed RTT for current connection (us)
// contains filtered or unexported fields
}
func NewSession ¶
NewSession creates and initializes a new session
func (*Session) ClearContext ¶ added in v1.2.0
func (s *Session) ClearContext()
ClearContext clears the old context and makes a new one.
func (*Session) GetContext ¶
func (s *Session) GetContext(key interface{}) interface{}
func (*Session) IncReqNumActive ¶
func (*Session) ReqNumActive ¶
func (*Session) SetContext ¶
func (s *Session) SetContext(key, val interface{})
func (*Session) SetReqNumActive ¶ added in v1.2.0
func (*Session) SetTrustSource ¶ added in v1.2.0
func (*Session) TrustSource ¶ added in v1.2.0
func (*Session) UpdateReadTotal ¶
func (*Session) UpdateWriteTotal ¶
func (*Session) WriteTotal ¶
type SessionStickyBackend ¶ added in v1.8.3
type TokenTimeInfo ¶ added in v1.8.3
type TokenTimeInfo struct {
TReqEnd int64 // Unix microsecond timestamp when the gateway finishes receiving the request body
TFirstToken int64 // Unix microsecond timestamp when the gateway receives the first chunk with valid generated text
TLastToken int64 // Unix microsecond timestamp when the last token is read
TTFT int64 // Time to first token (microseconds), TFirstToken - TReqEnd
TPOT int64 // Average time per output token (microseconds), (TLastToken - TFirstToken) / (CompletionTokens - 1)
}
type TokenUsage ¶ added in v1.8.3
type TokenUsage struct {
PromptTokens int64 // number of tokens in the prompt (includes cache_read_tokens, audio_input_tokens, image_input_tokens)
CompletionTokens int64 // number of tokens in the completion (includes audio_output_tokens)
CacheReadTokens int64 // usage.cache_read_tokens, already included in PromptTokens
CacheWriteTokens int64 // usage.cache_write_tokens, already included in PromptTokens (normalized for Anthropic)
CacheWriteTokens1h int64 // 1h-TTL cache write tokens (usage.cache_creation.ephemeral_1h_input_tokens), already included in CacheWriteTokens
AudioInputTokens int64 // usage.audio_input_tokens, already included in PromptTokens
AudioOutputTokens int64 // usage.audio_output_tokens, already included in CompletionTokens
ImageInputTokens int64 // usage.image_input_tokens / input_token_details.image_tokens, already included in PromptTokens
VideoCount int64 // number of generated videos for video generation models
ImageCount int64 // number of generated images for image generation models
UsedQuota int64 // used quota for this request (unit=total_token)
UsedCost int64 // used RMB cost for this request, 1 unit = 1e-8 yuan (unit=RMB)
}