bfe_basic

package
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: Apache-2.0 Imports: 15 Imported by: 2

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 (
	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"

	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"
)
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 (
	COMPLETION_TOKENS_UNKNOWN = -1
)
View Source
const (
	GlobalProduct = "global"
)
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
)
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 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 GetApiKey added in v1.8.3

func GetApiKey(req *Request) string

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
}

type AiBasicInfo added in v1.8.3

type AiBasicInfo struct {
	ClientApiKey string
	ClientModel  string
	TargetModel  string

	ApikeyTags    []ApikeyTag
	TokenTimeInfo TokenTimeInfo
	AiAuthInfo    AiAuthInfo
	// contains filtered or unexported fields
}

func (*AiBasicInfo) GetTokenUsage added in v1.8.3

func (aiinfo *AiBasicInfo) GetTokenUsage() *TokenUsage

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"`
	QuotaPlanId       string `json:"quota_plan_id"`
	LimitType         string `json:"limit_type"`
	Model             string `json:"model"`
	RetryAfterSeconds int    `json:"retry_after_seconds"`
}

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

type ApikeyTag struct {
	TagName  string //eg entity.type
	TagValue string //eg entity.name
}

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

func (r *Request) GetAiRateLimitHitInfo() *AiRateLimitHitInfo

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) 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
	CompletionTokens int64 // number of tokens in the completion
	UsedQuota        int64 // used quota for this request
}

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