common

package
v1.8.7 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: Apache-2.0 Imports: 36 Imported by: ? modules, 0 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

This section is empty.

Variables

This section is empty.

Functions

func FindFreePort

func FindFreePort() (int, error)

FindFreePort returns a free TCP port on localhost.

func FormatAccessLogError

func FormatAccessLogError(reqLog *bfe_access_pb.RequestLog) string

FormatAccessLogError returns a string with all request log fields for debugging test failures.

func GetBFETotalBytesBodyBuffer

func GetBFETotalBytesBodyBuffer(monitorPort int) (int64, error)

GetBFETotalBytesBodyBuffer queries the BFE monitor endpoint for the current total bytes_body buffer size.

func ParseAccessLog

func ParseAccessLog(logDir string, timeout time.Duration) ([]*bfe_access_pb.RequestLog, error)

ParseAccessLog reads the b2log file written by mod_access_pb3 and returns all decoded RequestLog records. It polls briefly if the file is not yet populated.

func ParseAccessLogAfterStop

func ParseAccessLogAfterStop(logDir string) ([]*bfe_access_pb.RequestLog, error)

ParseAccessLogAfterStop reads the b2log file after BFE has been stopped, ensuring all buffered logs are flushed.

func RewriteBFEPorts

func RewriteBFEPorts(path string, httpPort, httpsPort, monitorPort int) error

RewriteBFEPorts rewrites the httpPort, httpsPort and monitorPort lines in bfe.conf and ensures HTTP/HTTPS/monitor listeners are bound to the loopback interface only.

func RewriteBFETotalBodyBufferSize

func RewriteBFETotalBodyBufferSize(path string, size int64) error

RewriteBFETotalBodyBufferSize rewrites the totalBodyBufferSize line in bfe.conf.

func SimBinary added in v1.8.7

func SimBinary(t *testing.T) string

SimBinary locates the llm-d-inference-sim binary: $INFERENCE_SIM_BIN, then the sibling checkout at <bfe-root>/../llm-d-inference-sim/bin, then tests/integration/.sim-bin/. Returns "" when unavailable (tests should t.Skip).

func StartInferenceSim added in v1.8.7

func StartInferenceSim(t *testing.T, logDir, name, model string) (addr string, stop func())

StartInferenceSim starts one llm-d-inference-sim instance on a free loopback port in echo mode with near-zero simulated latency, and waits for its HTTP port. It returns the server address (host:port) and a stop function.

If the inference-sim binary is not found the test is skipped (the sim is an external optional dependency).

func StartInferenceSimWithArgs added in v1.8.7

func StartInferenceSimWithArgs(t *testing.T, logDir, name, model string, extraArgs ...string) (addr string, stop func())

StartInferenceSimWithArgs is StartInferenceSim with extra simulator arguments appended after the standard ones.

func WaitForTCP

func WaitForTCP(addr string, timeout time.Duration) error

WaitForTCP waits until the given TCP address is reachable.

Types

type ActionFile

type ActionFile struct {
	Cmd string
}

ActionFile is the JSON representation of an action.

type BFEConfigBuilder

type BFEConfigBuilder struct {
	// TemplateDir contains static BFE data files (bfe.conf, cluster_conf, mod_ai_route, etc.).
	TemplateDir string
	// TargetConfDir is the directory where the final BFE config will be written.
	TargetConfDir string
	// Backends maps cluster names to mock backends.
	Backends map[string]*MockBackend
	// StaticBackends maps cluster names to host:port addresses of real
	// backend processes (e.g. llm-d-inference-sim) that are not MockBackends.
	StaticBackends map[string]string
	// EPPClusters optionally enables EPP scheduling (BalanceMode=EPP) for the
	// given clusters in the generated cluster_conf.data.
	EPPClusters map[string]*EPPClusterConf
	// AIConfs optionally injects AIConf into cluster_conf.data for specific clusters.
	AIConfs map[string]*cluster_conf.AIConf
	// TotalBodyBufferSize overrides the totalBodyBufferSize value in bfe.conf.
	// A value of 0 keeps the template value.
	TotalBodyBufferSize int64
	// RedisAddr is the address of the redis server used by mod_ai_token_auth.
	// If empty, mod_ai_token_auth.conf is not rewritten.
	RedisAddr string
	// TokenRuleData optionally generates mod_ai_token_auth/token_rule.data.
	TokenRuleData *TokenRuleData
	// RateLimitPolicyData optionally generates mod_ai_rate_limit/ai_rate_limit.data.
	RateLimitPolicyData *RateLimitPolicyData
}

BFEConfigBuilder builds a temporary BFE configuration directory from a template.

func (*BFEConfigBuilder) Build

func (b *BFEConfigBuilder) Build() error

Build prepares the BFE configuration directory.

type EPPClusterConf added in v1.8.7

type EPPClusterConf struct {
	// Addrs is the ordered EPP address list ([0]=primary, [1]=backup).
	Addrs []string
	// EPPCheck optionally overrides health check / failover hysteresis
	// parameters (map merged into GslbBasic, e.g. {"CheckInterval": "200ms"}).
	EPPCheck map[string]interface{}
	// EPPTimeout optionally overrides EPP call timeouts.
	EPPTimeout map[string]interface{}
	// EPPTLS optionally configures TLS verification for EPP connections.
	EPPTLS map[string]interface{}
	// EPPBreaker optionally overrides circuit breaker parameters.
	EPPBreaker map[string]interface{}
}

EPPClusterConf describes the EPP scheduling configuration written into the GslbBasic section of cluster_conf.data for a cluster.

type MockBackend

type MockBackend struct {
	ClusterName string
	Response    int
	Body        string
	// ReadBeforeClose, if greater than 0, causes the handler to read this
	// many bytes from the request body and then close the connection without
	// sending an HTTP response. This is useful for simulating a backend that
	// fails mid-stream.
	ReadBeforeClose int
	// DelayResponse sleeps for the given duration after reading the body and
	// before writing the response. It can be used to keep the request (and
	// any allocated body buffer) alive for a period of time.
	DelayResponse time.Duration
	// ReadNotify, if non-nil, is closed the first time the handler starts
	// reading the request body. This can be used to synchronize with the
	// allocation of body buffers inside BFE.
	ReadNotify chan struct{}
	// HoldResponse, if non-nil, blocks the handler after the request body has
	// been fully read and before the response is written. The response is only
	// sent after the channel is closed. This is useful for keeping a request
	// alive while another request is being processed.
	HoldResponse <-chan struct{}
	// HoldBeforeRead, if non-nil, blocks the handler after the request headers
	// have been received and before the body is read. This can be used to keep
	// BFE from closing the request body while another request is processed.
	HoldBeforeRead <-chan struct{}
	// ResponseFunc, if non-nil, overrides Response/Body and is called for each
	// request to determine the response status and body.
	ResponseFunc func(r *http.Request, count int) (int, string)
	// ResponseHeaders, if non-nil, is written to the response before the status code.
	ResponseHeaders map[string]string
	// NoContentLength, if true, flushes the response headers before writing
	// the body so the response uses chunked transfer encoding without a
	// Content-Length header. The default (false) lets net/http infer a
	// Content-Length for short bodies.
	NoContentLength bool
	// SSEEvents, if non-nil, switches the handler to server-sent event mode:
	// each entry is written as one "data: <event>\n\n" frame followed by a
	// flush. ResponseFunc/Response/Body are ignored in this mode.
	SSEEvents []string
	// SSEHold, if non-nil, blocks the handler after SSEEvents have been
	// flushed and before SSETrailing is written. Closing it releases the stream.
	SSEHold <-chan struct{}
	// SSETrailing, if non-nil, is written (and flushed) after SSEHold is
	// released, simulating backend data arriving after a client abort.
	SSETrailing []string
	// contains filtered or unexported fields
}

MockBackend wraps an httptest.Server and records request metadata.

func NewMockBackend

func NewMockBackend(clusterName string, response int, body string) *MockBackend

NewMockBackend starts a local HTTP server that returns the given status code.

func (*MockBackend) Addr

func (b *MockBackend) Addr() string

Addr returns the host:port of the mock backend.

func (*MockBackend) AnthropicVersions added in v1.8.6

func (b *MockBackend) AnthropicVersions() []string

AnthropicVersions returns a deep copy of all observed anthropic-version headers.

func (*MockBackend) AuthHeaders

func (b *MockBackend) AuthHeaders() []string

AuthHeaders returns a deep copy of all observed Authorization headers.

func (*MockBackend) Close

func (b *MockBackend) Close()

Close shuts down the mock backend.

func (*MockBackend) Hits

func (b *MockBackend) Hits() int

Hits returns the number of requests received.

func (*MockBackend) HostPort

func (b *MockBackend) HostPort() (string, int)

HostPort returns the host and port of the mock backend.

func (*MockBackend) Models

func (b *MockBackend) Models() []string

Models returns the list of model values observed in request bodies.

func (*MockBackend) RequestBodies

func (b *MockBackend) RequestBodies() [][]byte

RequestBodies returns a deep copy of all observed request bodies.

func (*MockBackend) XApiKeyHeaders added in v1.8.6

func (b *MockBackend) XApiKeyHeaders() []string

XApiKeyHeaders returns a deep copy of all observed x-api-key headers.

func (*MockBackend) XGoogApiKeyHeaders added in v1.8.7

func (b *MockBackend) XGoogApiKeyHeaders() []string

XGoogApiKeyHeaders returns a deep copy of all observed x-goog-api-key headers.

type MockEPP added in v1.8.7

type MockEPP struct {
	// contains filtered or unexported fields
}

MockEPP is an in-process mock EPP (ext-proc) server. It implements the envoy ext_proc v3 ExternalProcessor service plus the gRPC health service (used by BFE's EPP health checker), speaks TLS with a self-signed certificate (BFE dials EPP with InsecureSkipVerify when EPPTLS is unset), and records the pool metadata, request headers/body and response headers/body of every processed stream for test assertions.

func NewMockEPP added in v1.8.7

func NewMockEPP(t *testing.T) *MockEPP

NewMockEPP starts a mock EPP server on a free loopback port.

func (*MockEPP) Addr added in v1.8.7

func (m *MockEPP) Addr() string

Addr returns the mock EPP listen address (host:port).

func (*MockEPP) Close added in v1.8.7

func (m *MockEPP) Close()

Close stops the mock EPP server.

func (*MockEPP) Pools added in v1.8.7

func (m *MockEPP) Pools() []string

Pools returns the inference-pool values observed in stream metadata.

func (*MockEPP) Process added in v1.8.7

Process implements the ext-proc bidirectional stream. The conversation mirrors what BFE's bal_gslb.callEPP / EppClient produce:

request  dir: RequestHeaders [+ RequestBody]
response dir: decision (dynamic metadata) [+ empty body reply]
request  dir: ResponseHeaders, ResponseBody*
response dir: empty replies

func (*MockEPP) RequestBodies added in v1.8.7

func (m *MockEPP) RequestBodies() [][]byte

RequestBodies returns the request bodies of each processed stream.

func (*MockEPP) RequestHeadersList added in v1.8.7

func (m *MockEPP) RequestHeadersList() []http.Header

RequestHeadersList returns the request headers of each processed stream.

func (*MockEPP) ResponseBodies added in v1.8.7

func (m *MockEPP) ResponseBodies() [][]byte

ResponseBodies returns the assembled response bodies of each completed stream (what the mock received via ResponseBody messages, excluding the trailing EndOfStream message).

func (*MockEPP) ResponseHeadersList added in v1.8.7

func (m *MockEPP) ResponseHeadersList() []http.Header

ResponseHeadersList returns the response headers of each processed stream.

func (*MockEPP) SetDecisionEndpoint added in v1.8.7

func (m *MockEPP) SetDecisionEndpoint(addr string)

SetDecisionEndpoint sets the endpoint address returned in dynamic metadata (envoy.lb -> x-gateway-destination-endpoint).

func (*MockEPP) SetRequestError added in v1.8.7

func (m *MockEPP) SetRequestError(err error)

SetRequestError makes the server fail every stream on its first message with the given error (typically a gRPC status error created with status.Error). Pass nil to restore normal behavior.

func (*MockEPP) SetServing added in v1.8.7

func (m *MockEPP) SetServing(serving bool)

SetServing controls the gRPC health status reported to BFE's EPP health checker.

func (*MockEPP) ShutdownHealth added in v1.8.7

func (m *MockEPP) ShutdownHealth()

ShutdownHealth simulates an EPP process crash: the gRPC health service is deregistered entirely, so health checks fail with UNIMPLEMENTED.

func (*MockEPP) StreamCount added in v1.8.7

func (m *MockEPP) StreamCount() int

StreamCount returns the number of streams that sent RequestHeaders.

type ProcessEnv

type ProcessEnv struct {
	// contains filtered or unexported fields
}

ProcessEnv manages building and running a real BFE process for integration tests.

func NewProcessEnv

func NewProcessEnv(t *testing.T) *ProcessEnv

NewProcessEnv creates a ProcessEnv for the current test.

func (*ProcessEnv) Build

func (p *ProcessEnv) Build()

Build compiles the BFE binary if not already cached. The binary path includes the current git commit hash so that switching commits forces a rebuild. Within the same commit, source mtime is checked to catch uncommitted local edits.

func (*ProcessEnv) SourceRoot

func (p *ProcessEnv) SourceRoot() string

SourceRoot returns the absolute path to the bfe source root.

func (*ProcessEnv) StartBFE

func (p *ProcessEnv) StartBFE(confDir, logDir string) (int, int, func())

StartBFE starts a real BFE process with the given conf root and log dir. It returns the HTTP port, the monitor port and a teardown function.

func (*ProcessEnv) WorkDir

func (p *ProcessEnv) WorkDir() string

WorkDir returns the per-test temporary directory.

type QuotaPlan

type QuotaPlan struct {
	Id          string
	Unlimited   bool
	PassNoQuota bool
	RedisKey    string
	ExpiredTime int64
	Quota       int64
	Unit        string
}

QuotaPlan is the JSON representation of a quota plan.

type RateLimitPolicy added in v1.8.6

type RateLimitPolicy struct {
	Name    string `json:"name"`
	Enabled bool   `json:"enabled"`
	Rules   struct {
		TPM            []RateLimitRule `json:"tpm,omitempty"`
		RPM            []RateLimitRule `json:"rpm,omitempty"`
		MaxConcurrency *int64          `json:"max_concurrency,omitempty"`
	} `json:"rules"`
}

RateLimitPolicy is the JSON representation of a rate limit policy in ai_rate_limit.data.

type RateLimitPolicyData added in v1.8.6

type RateLimitPolicyData struct {
	Version                       string                            `json:"Version"`
	Config                        map[string][]RateLimitProductRule `json:"Config"`
	RateLimitPolicies             map[string]RateLimitPolicy        `json:"RateLimitPolicies"`
	ApikeyRateLimitPolicyBindings map[string][]string               `json:"ApikeyRateLimitPolicyBindings"`
}

RateLimitPolicyData holds the content of mod_ai_rate_limit/ai_rate_limit.data.

type RateLimitProductRule added in v1.8.6

type RateLimitProductRule struct {
	Cond      string `json:"cond"`
	HitAction struct {
		Cmd    string   `json:"cmd"`
		Params []string `json:"params,omitempty"`
	} `json:"hit_action"`
}

RateLimitProductRule is the JSON representation of a product rule in ai_rate_limit.data.

type RateLimitRule added in v1.8.6

type RateLimitRule struct {
	Name          string   `json:"name"`
	WindowMinutes int      `json:"window_minutes"`
	MaxTokens     int64    `json:"max_tokens,omitempty"`
	MaxRequests   int64    `json:"max_requests,omitempty"`
	StepMinutes   int      `json:"step_minutes,omitempty"`
	Burst         int64    `json:"burst,omitempty"`
	Models        []string `json:"models,omitempty"`
	RedisKey      string   `json:"redis_key,omitempty"`
}

RateLimitRule is the JSON representation of a TPM/RPM rule in ai_rate_limit.data.

type RedisServer

type RedisServer struct {
	// contains filtered or unexported fields
}

RedisServer wraps miniredis for integration tests.

func NewRedisServer

func NewRedisServer(t *testing.T) *RedisServer

NewRedisServer starts a new embedded redis server.

func (*RedisServer) Addr

func (s *RedisServer) Addr() string

Addr returns the redis server address in "host:port" format.

func (*RedisServer) Close

func (s *RedisServer) Close()

Close stops the redis server.

func (*RedisServer) Exists added in v1.8.6

func (s *RedisServer) Exists(key string) bool

Exists reports whether the given key is present in redis.

func (*RedisServer) GetQuota

func (s *RedisServer) GetQuota(key string) int64

GetQuota returns the current integer quota value for the given key.

func (*RedisServer) SetQuota

func (s *RedisServer) SetQuota(key string, value int64)

SetQuota sets an integer quota value for the given key.

type TokenFile

type TokenFile struct {
	Key            string                `json:"key"`
	KeyId          string                `json:"key_id"`
	Enabled        bool                  `json:"enabled"`
	ExpiredTime    int64                 `json:"expired_time"`
	UnlimitedQuota bool                  `json:"unlimited_quota"`
	Models         *string               `json:"allow_models"`
	BlockModels    *string               `json:"block_models"`
	Subnet         *string               `json:"subnet"`
	Tags           []bfe_basic.ApikeyTag `json:"tags"`
	QuotaPlans     []string              `json:"quota_plans"`
}

TokenFile is the JSON representation of a token file.

type TokenRule

type TokenRule struct {
	Cond   string
	Action ActionFile
}

TokenRule is the JSON representation of a token rule.

type TokenRuleData

type TokenRuleData struct {
	Version    string
	QuotaPlans map[string][]QuotaPlan
	Tokens     map[string]map[string]TokenFile
	Config     map[string][]TokenRule
}

TokenRuleData holds the content of mod_ai_token_auth/token_rule.data.

Jump to

Keyboard shortcuts

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