bfe_basic

package
v1.8.9-preview.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 16 Imported by: 4 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	HeaderBfeIP         = "X-Bfe-Ip"
	HeaderBfeLogId      = "X-Bfe-Log-Id"
	HeaderForwardedHost = "X-Forwarded-Host"
	HeaderForwardedFor  = "X-Forwarded-For"
	HeaderForwardedPort = "X-Forwarded-Port"
	HeaderRealIP        = "X-Real-Ip"
	HeaderRealPort      = "X-Real-Port"
)
View Source
const (
	REQ_AI_BASIC_CONTEXT  = "__REQ_AI_BASIC_CONTEXT"
	REQ_AI_RATE_LIMIT_HIT = "__REQ_AI_RATE_LIMIT_HIT"
)
View Source
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.

View Source
const (
	BatchOpUpload   = "upload"
	BatchOpCreate   = "create"
	BatchOpGet      = "get"
	BatchOpList     = "list"
	BatchOpCancel   = "cancel"
	BatchOpDownload = "download"
)

Batch operation types (mod_ai_batch), classified from (method, path).

View Source
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.

View Source
const (
	AuthStyleOpenAI    = "openai"
	AuthStyleAnthropic = "anthropic"
	AuthStyleGemini    = "gemini"
	AuthStyleUnknown   = "unknown"
)

AI protocol/auth styles.

View Source
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).

View Source
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: billing is skipped per the
	// issue #1352 yardstick, and the reported token fields are either
	// auth-time seeding residue or the initial usage of the stream
	// (issue #1414).
	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"
)

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.

View Source
const (
	// ZeroCostReasonUnrecognized: upstream usage was neither recognized nor
	// estimatable.
	ZeroCostReasonUnrecognized = "unrecognized"
	// ZeroCostReasonAborted: the client disconnected before the final usage.
	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).

View Source
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"

	// 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"
	CodeBackendUnavailable = "BACKEND_UNAVAILABLE"
	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"
)
View Source
const (
	TypeAuthenticationError = "authentication_error"
	TypeInvalidRequestError = "invalid_request_error"
	TypeRateLimitError      = "rate_limit_error"
	TypeQuotaError          = "quota_error"
	TypeInternalError       = "internal_error"
)
View Source
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"
)
View Source
const (
	IntentQTypeChoice = "choice"
	IntentQTypeScore  = "score"
)

intent question types

View Source
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

View Source
const (
	SessionNotTrustSource int32 = 0
	SessionTrustSource    int32 = 1
)
View Source
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
)
View Source
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
)
View Source
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.

View Source
const (
	COMPLETION_TOKENS_UNKNOWN = -1
)
View Source
const CtxAiIntent = "__REQ_AI_INTENT"
View Source
const CtxAiRouteResult = "__REQ_AI_ROUTE_RESULT"
View Source
const (
	GlobalProduct = "global"
)
View Source
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).

View Source
const (
	REQ_CTX_WAF_INFO = "waf_client.waf_info"
)
View Source
const (
	SessionStickyBackendKey = "SessionStickyBackendKey"
)

Variables

View Source
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
	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

	// 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
)
View Source
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,
	CodeInvalidRequestBody: TypeInvalidRequestError,
	CodeModelParamMissing:  TypeInvalidRequestError,

	CodeUserQuotaExhausted:     TypeQuotaError,
	CodeSessionQuotaExhausted:  TypeQuotaError,
	CodeFunctionQuotaExhausted: TypeQuotaError,
	CodeCostBudgetExhausted:    TypeQuotaError,
	CodeGeoRestricted:          TypeAuthenticationError,
	CodeTimeWindowRestricted:   TypeAuthenticationError,

	CodeProviderProtocolMismatch: TypeInvalidRequestError,

	CodeUpstreamInvalidRequest: TypeInvalidRequestError,
	CodeUpstreamRateLimited:    TypeRateLimitError,
	CodeUpstreamQuotaExhausted: TypeQuotaError,
	CodeUpstreamAuthError:      TypeInternalError,
	CodeUpstreamModelNotFound:  TypeInvalidRequestError,
	CodeUpstreamOverloaded:     TypeInternalError,
	CodeUpstreamUnknown:        TypeInternalError,
}

ErrorCodeToErrorType maps every catalog code to its error.type.

View Source
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

func AiIntentThreshold(question string) float64

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

func BatchAffinityKey(cluster, id string) string

BatchAffinityKey builds the binding key for a batch or file identifier.

func BatchPathBatchId added in v1.8.9

func BatchPathBatchId(path string) string

BatchPathBatchId extracts the {id} segment of /batches/{id}[/cancel].

func BatchPathFileId added in v1.8.9

func BatchPathFileId(path string) string

BatchPathFileId extracts the {id} segment of /files/{id}[/content].

func ClassifyBatchOp added in v1.8.9

func ClassifyBatchOp(method string, path string) string

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

func CreateForbiddenResp(request *Request) *bfe_http.Response

CreateForbiddenResp returns a HTTP 403 response

func CreateInternalResp

func CreateInternalResp(request *Request, code int) *bfe_http.Response

func CreateInternalSrvErrResp

func CreateInternalSrvErrResp(request *Request) *bfe_http.Response

CreateInternalSrvErrResp returns a HTTP 500 response

func CreateSpecifiedContentResp added in v1.8.0

func CreateSpecifiedContentResp(request *Request, responseCode int, contentType string, content string) *bfe_http.Response

func DetectAuthStyle added in v1.8.6

func DetectAuthStyle(req *Request) string

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

func DetectModeFromPath(path string) string

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

func ErrorTypeForCode(code string) string

ErrorTypeForCode returns the error.type for a catalog code, defaulting to internal_error for unknown codes.

func ExtractBatchInputFileId added in v1.8.9

func ExtractBatchInputFileId(req *Request) string

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 GetApiKey added in v1.8.3

func GetApiKey(req *Request) string

func IsOpenAIEndpoint added in v1.8.8

func IsOpenAIEndpoint(path string) bool

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 SetAiIntentResolver(fn func(*Request) *AiIntent)

func SetAiIntentThreshold added in v1.8.9

func SetAiIntentThreshold(fn func(question string) float64)

func StripV1Prefix added in v1.8.8

func StripV1Prefix(path string) string

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 AiAuthInfo struct {
	RejectReason     string   // reason for rejection
	RejectQuotaPlans []string // quota plan IDs rejected due to insufficient quota
	HitQuotaPlans    []string // quota plan IDs hit (passed balance check) for successful requests
}

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

	// 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
	// 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) 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) 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) MarkResponseCompleted added in v1.8.7

func (aiinfo *AiBasicInfo) MarkResponseCompleted()

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 NewAiError(code, typeStr, message string) *AiError

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 *AiError) CreateErrorResponse(request *Request) *bfe_http.Response

func (*AiError) Error added in v1.8.3

func (aiError *AiError) Error() string

func (*AiError) GenRespBody added in v1.8.3

func (aiError *AiError) GenRespBody() *AiErrorBody

func (*AiError) GenRespBodyStr added in v1.8.3

func (aiError *AiError) GenRespBodyStr() string

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

func GetAiIntent(req *Request) *AiIntent

GetAiIntent returns the intent classification result of the request, triggering lazy resolve on first call via the injected resolver.

func (*AiIntent) Match added in v1.8.9

func (ai *AiIntent) Match(question string, options ...string) bool

Match reports whether the answer of the given question is available (not unknown under the current threshold) and its choice is one of options.

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 AiRouteFallback struct {
	ClusterName string
	Model       string
}

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 AiRouteTarget struct {
	ClusterName string
	Model       string
	Weight      int
}

type ApikeyTag added in v1.8.3

type ApikeyTag struct {
	TagName  string //eg entity.type
	TagValue string //eg entity.name
	TagLevel int    // entity type level, value range 1~5
}

type BackendInfo

type BackendInfo struct {
	ClusterName    string // name of cluster
	SubclusterName string // name of sub-cluster
	BackendAddr    string // backend ip address
	BackendPort    uint32 // backend's port
	BackendName    string // backend name
}

type ClusterKeyName added in v1.8.5

type ClusterKeyName struct {
	ClusterName string
	KeyName     string
}

ClusterKeyName represents a tried cluster and API-Key pair during request processing

type HitPolicyInfo added in v1.8.3

type HitPolicyInfo struct {
	TpmRules      []string `json:"tpm_rules"` //name of limiter
	RpmRules      []string `json:"rpm_rules"` //name of limiter
	IsConcurrency bool     `json:"is_concurrency"`
	IsRedisError  string   `json:"is_redis_error"`
}

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 RedirectInfo struct {
	Url    string          // URL
	Code   int             // HTTP status code
	Header bfe_http.Header // Extra header
}

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) AddTags

func (req *Request) AddTags(name string, ntags []string)

func (*Request) CachedCookie

func (req *Request) CachedCookie() bfe_http.CookieMap

func (*Request) CachedQuery

func (req *Request) CachedQuery() url.Values

func (*Request) Cookie

func (req *Request) Cookie(name string) (*bfe_http.Cookie, bool)

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 (r *Request) GetApikeyTags() []ApikeyTag

func (*Request) GetContext

func (req *Request) GetContext(key interface{}) interface{}

func (*Request) GetTags

func (req *Request) GetTags(name string) []string

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) Protocol

func (req *Request) Protocol() string

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 (r *Request) SetAiIntent(v *AiIntent)

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)

type RequestRoute

type RequestRoute struct {
	Error       error  // error in request-route
	HostTag     string // tags
	Product     string // name of product
	ClusterName string // clustername req should route to
}

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 RequestTags struct {
	Error    error               // error in request-tag
	TagTable map[string][]string // type-tags pairs
}

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 *bfe_tls.ConnectionState // tls state when using TLS

	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

func NewSession(conn net.Conn) *Session

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) Finish

func (s *Session) Finish()

func (*Session) GetContext

func (s *Session) GetContext(key interface{}) interface{}

func (*Session) GetError

func (s *Session) GetError() (string, error)

func (*Session) GetVip

func (s *Session) GetVip() net.IP

func (*Session) IncReqNum

func (s *Session) IncReqNum(count int) int64

func (*Session) IncReqNumActive

func (s *Session) IncReqNumActive(count int) int64

func (*Session) ReadTotal

func (s *Session) ReadTotal() int

func (*Session) ReqNum

func (s *Session) ReqNum() int64

func (*Session) ReqNumActive

func (s *Session) ReqNumActive() int64

func (*Session) SetContext

func (s *Session) SetContext(key, val interface{})

func (*Session) SetError

func (s *Session) SetError(errCode error, errMsg string)

func (*Session) SetReqNum added in v1.2.0

func (s *Session) SetReqNum(count int)

func (*Session) SetReqNumActive added in v1.2.0

func (s *Session) SetReqNumActive(count int)

func (*Session) SetTrustSource added in v1.2.0

func (s *Session) SetTrustSource(isTrustSource bool)

func (*Session) String

func (s *Session) String() string

func (*Session) TrustSource added in v1.2.0

func (s *Session) TrustSource() bool

func (*Session) UpdateReadTotal

func (s *Session) UpdateReadTotal(total int) int

func (*Session) UpdateWriteTotal

func (s *Session) UpdateWriteTotal(total int) int

func (*Session) WriteTotal

func (s *Session) WriteTotal() int

type SessionStickyBackend added in v1.8.3

type SessionStickyBackend struct {
	Addr       *string `json:"ip"`
	Port       *int    `json:"port"`
	SubCluster *string `json:"subcluster"`
	RenewTime  *int64  `json:"renewtime"`
}

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)
}

type WafInfo added in v1.8.0

type WafInfo struct {
	WafSpentTime int64  // in ms.
	WafStatus    int    // waf status, see bfe proto file for detail
	WafRuleName  string // not used
}

support old waf info struct

func GetWafInfo added in v1.8.0

func GetWafInfo(req *Request) *WafInfo

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL