common

package
v1.8.9 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 39 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 CamelToSnake added in v1.8.9

func CamelToSnake(s string) string

CamelToSnake converts a counter name to the SNAKE_CASE key used by the web-monitor prometheus export. Both Go-style field names and keys that are already upper snake case pass through unchanged in shape: "UsageUnrecognized" -> "USAGE_UNRECOGNIZED", "SETTLE_NO_USAGE" -> "SETTLE_NO_USAGE" (mod_ai_batch declares its counters in upper snake case).

func ClusterSubName added in v1.8.9

func ClusterSubName(clusterName string) string

ClusterSubName returns the sub-cluster name used in cluster_table.data and gslb.data for the given cluster. It is exported for scenarios that regenerate gslb.data at runtime.

func FindFreePort

func FindFreePort() (int, error)

FindFreePort returns a free TCP port on localhost.

func FindFreePorts added in v1.8.9

func FindFreePorts(n int) ([]int, error)

FindFreePorts reserves n distinct free TCP ports on localhost by holding all probe listeners open at once, then closing them. Reserving simultaneously guarantees distinctness: back-to-back FindFreePort calls can receive the same port again from the OS right after the previous probe socket is closed (observed on loaded CI: bfe http and https were assigned the same port and startup died with EADDRINUSE).

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. The monitor server may still be starting up right after the BFE process launches (under -race on a loaded machine the first query can hit connection refused), so it retries briefly.

func ModuleCounterJSON added in v1.8.9

func ModuleCounterJSON(port int, module, key string) (float64, error)

ModuleCounterJSON returns one counter from the module state JSON document (/monitor/<module>).

Modules built on module_state2.State expose their counters through StateData.FormatOutput, which has no prometheus renderer (the endpoint answers {"error":"format not support: prometheus"}); mod_ai_batch is one of them, so its counters are read from the JSON document instead. A missing counter reads as 0; a response without the counters document is an error so a wrong module/endpoint can never look like "counter is zero".

func ModuleMetric added in v1.8.9

func ModuleMetric(port int, module, field string) (float64, error)

ModuleMetric returns the value of one module counter (0 when absent).

The web-monitor prometheus export renders the counter field names in SNAKE_CASE, so callers pass the Go field name of the counter (e.g. "BillingZeroCost", which is exported as "mod_ai_token_auth_BILLING_ZERO_COST").

func ModuleMetricsRaw added in v1.8.9

func ModuleMetricsRaw(port int, module string) (string, error)

ModuleMetricsRaw fetches the prometheus export of a module's counters from the BFE web monitor, e.g. ModuleMetricsRaw(port, "mod_ai_token_auth").

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. The log-level fields are dropped; use ParseBfeLogs when they are needed (e.g. logid).

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 ParseBfeLogs added in v1.8.9

func ParseBfeLogs(logDir string, timeout time.Duration) ([]*bfe_access_pb.BfeLog, error)

ParseBfeLogs reads the b2log file written by mod_access_pb3 and returns the decoded BfeLog records, keeping the log-level fields (e.g. logid) that the per-request view drops. It polls briefly if the file is not yet populated.

func ParseBfeLogsAfterStop added in v1.8.9

func ParseBfeLogsAfterStop(logDir string) ([]*bfe_access_pb.BfeLog, error)

ParseBfeLogsAfterStop is ParseAccessLogAfterStop for the log-level records.

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 RewriteConfLine added in v1.8.9

func RewriteConfLine(path, key, value string) error

RewriteConfLine replaces the value of key in an ini-style config file, preserving every other line. It matches `key = value` case-insensitively on the key and returns an error when the key is absent, so templates stay honest about the knobs scenarios depend on.

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 WaitForModuleCounterJSON added in v1.8.9

func WaitForModuleCounterJSON(port int, module, key string, timeout time.Duration,
	cond func(float64) bool) (float64, error)

WaitForModuleCounterJSON polls ModuleCounterJSON until cond is satisfied or the timeout elapses, returning the last observed value.

func WaitForModuleMetric added in v1.8.9

func WaitForModuleMetric(port int, module, field string, timeout time.Duration,
	cond func(float64) bool) (float64, error)

WaitForModuleMetric polls a module counter until cond is satisfied or the timeout elapses, and returns the last observed value. The monitor handler reads the counters on demand, so the poll only guards the race between a request finishing and the assertion.

func WaitForModuleMetricValue added in v1.8.9

func WaitForModuleMetricValue(port int, module, field string, want float64, timeout time.Duration) float64

WaitForModuleMetricValue polls one module metric until it reaches at least want or the timeout elapses, returning the last observed value. It is used by scenarios that assert a counter/gauge moved (e.g. proxy_state SSE counters) without depending on a fixed sleep.

func WaitForTCP

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

WaitForTCP waits until the given TCP address is reachable.

func WriteJSONFile added in v1.8.9

func WriteJSONFile(path string, data interface{}) error

WriteJSONFile writes data as indented JSON to path, creating parent directories. It is exported for scenarios that generate module rule data (e.g. mod_traffic_mirror/mirror_rule.data) at runtime.

func WritePEMFile added in v1.8.9

func WritePEMFile(path string, data []byte) error

WritePEMFile writes PEM bytes to path, creating parent directories.

Types

type ActionFile

type ActionFile struct {
	Cmd string
}

ActionFile is the JSON representation of an action.

type AiCacheRule added in v1.8.9

type AiCacheRule struct {
	Cond             string `json:"cond"`
	CacheKeyStrategy string `json:"cacheKeyStrategy"`
	CacheTTL         int    `json:"cacheTTL,omitempty"`
	MaxBodyBytes     int64  `json:"maxBodyBytes,omitempty"`
	MaxValueBytes    int64  `json:"maxValueBytes,omitempty"`

	// EnableSemanticCache turns on the semantic (vector similarity) cache
	// for this rule; ignored unless the module conf configures both the
	// [embedding] and [vector] sections. Nil omits the field and keeps the
	// module default (false).
	EnableSemanticCache *bool `json:"enableSemanticCache,omitempty"`
}

AiCacheRule is the JSON representation of a product rule in mod_ai_cache_rule.data.

type AiCacheRuleData added in v1.8.9

type AiCacheRuleData struct {
	Version  string                   `json:"Version"`
	Semantic *AiCacheSemanticRule     `json:"Semantic,omitempty"`
	Config   map[string][]AiCacheRule `json:"Config"`
}

AiCacheRuleData holds the content of mod_ai_cache/mod_ai_cache_rule.data.

type AiCacheSemanticRule added in v1.8.9

type AiCacheSemanticRule struct {
	TopK              *int     `json:"topK,omitempty"`
	Threshold         *float64 `json:"threshold,omitempty"`
	ThresholdRelation *string  `json:"thresholdRelation,omitempty"`
}

AiCacheSemanticRule is the JSON representation of the top-level Semantic block of mod_ai_cache_rule.data (module-level global conf of the semantic cache). Nil fields are omitted and take the module defaults.

type AuditCall added in v1.8.9

type AuditCall struct {
	Path string
	Text string
}

AuditCall records one content-audit request.

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
	// BackendGroups maps cluster names to additional mock backends that share
	// the same sub-cluster (same weight as the primary backend). It is used by
	// scenarios that must distinguish which backend served a request, e.g.
	// session sticky. Backends and BackendGroups may be combined.
	BackendGroups 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
	// AiCacheRuleData optionally generates mod_ai_cache/mod_ai_cache_rule.data.
	AiCacheRuleData *AiCacheRuleData
	// DecisionServiceAddr optionally rewrites the DecisionServiceAddr line in
	// mod_ai_intent/mod_ai_intent.conf (e.g. with the address of a mock
	// decision service). If empty, mod_ai_intent.conf is not rewritten.
	DecisionServiceAddr string
	// EmbeddingServiceAddr optionally rewrites the serviceHost/servicePort
	// lines of the [embedding] section in mod_ai_cache/mod_ai_cache.conf
	// (e.g. with the address of a mock embedding service). If empty, the
	// section is left untouched.
	EmbeddingServiceAddr string
	// VectorServiceAddr optionally rewrites the serviceHost/servicePort lines
	// of the [vector] section in mod_ai_cache/mod_ai_cache.conf (e.g. with
	// the address of a mock vector store). If empty, the section is left
	// untouched.
	VectorServiceAddr string
	// ClusterOverrides customizes the generated cluster_conf.data per cluster.
	// Nil sections keep the defaults produced by clusterBasicConf().
	ClusterOverrides map[string]*ClusterOverride
}

BFEConfigBuilder builds a temporary BFE configuration directory from a template.

func (*BFEConfigBuilder) Build

func (b *BFEConfigBuilder) Build() error

Build prepares the BFE configuration directory.

func (*BFEConfigBuilder) WriteClusterConfData added in v1.8.9

func (b *BFEConfigBuilder) WriteClusterConfData() error

WriteClusterConfData regenerates cluster_conf.data in the target conf dir from the current builder settings. Tests mutate EPPClusters (or Backends) and call it to produce a new cluster_conf.data before triggering /reload/server_data_conf, so cluster GslbBasic (e.g. EPP parameters) is hot-updated without restarting BFE.

type ChromaRecord added in v1.8.9

type ChromaRecord struct {
	ID        string    // unique record id (upsert replaces on conflict)
	Tenant    string    // tenant_id metadata (mandatory filter)
	Question  string    // document payload
	Answer    string    // answer inlined in the metadata
	Embedding []float64 // vector
	CreatedAt time.Time // created_at metadata (unix seconds, TTL filter)
}

ChromaRecord describes a single vector record of a collection. It is used by UpsertRecord to inject records directly into the in-memory store (e.g. a record with an expired created_at for TTL tests), bypassing HTTP.

type ClusterOverride added in v1.8.9

type ClusterOverride struct {
	BackendConf        map[string]interface{}
	CheckConf          map[string]interface{}
	ClusterBasic       map[string]interface{}
	GslbBasic          map[string]interface{}
	HTTPSConf          map[string]interface{}
	RemoveBackendConf  []string
	RemoveCheckConf    []string
	RemoveClusterBasic []string
	RemoveGslbBasic    []string
}

ClusterOverride overrides individual sections of the generated cluster_conf.data entry for one cluster. Keys are merged into the corresponding section, so a test only has to name the knobs it changes. Remove lists keys to delete from a section, letting BFE apply its own defaults for knobs the shared harness pre-populates.

type DecisionAnswer added in v1.8.9

type DecisionAnswer struct {
	Type             string             // "choice" or "score"
	Choice           string             // chosen option / level name
	Score            float64            // expected level index (score questions)
	Probabilities    map[string]float64 // option name / level index -> probability
	AnswerConfidence float64            // reported answer_confidence (informative)
	Legend           []string           // level names for score answers (optional)
}

DecisionAnswer describes the scripted System One answer of a single intent question. For choice questions set Choice and Probabilities (the probability of Choice is taken as the answer confidence by BFE). For score questions set Score (level index) and Probabilities keyed by level index ("0", "1", ...), optionally with Legend (level names).

type DecisionResponse added in v1.8.9

type DecisionResponse struct {
	Status  int                       // HTTP status code, 0 means 200
	Answers map[string]DecisionAnswer // question name -> answer
}

DecisionResponse describes the scripted System One response for a prompt keyword. Status is the HTTP status code (0 means 200).

type DecisionScript added in v1.8.9

type DecisionScript map[string]DecisionResponse

DecisionScript maps prompt keywords to scripted responses. The matching rule is "longest keyword first": the longest keyword contained in the prompt wins, so a prompt containing "写设计文档" matches that entry before the shorter "写文档".

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 EmbeddingScript added in v1.8.9

type EmbeddingScript map[string][]float64

EmbeddingScript maps question keywords to scripted embedding vectors. The matching rule is "longest keyword first" (mirroring DecisionScript): the longest keyword contained in the input text wins, so an input containing "introduce bfe" matches that entry before the shorter "bfe". Inputs matching no keyword get a deterministic default vector far from any scripted one.

type MockAudit added in v1.8.9

type MockAudit struct {

	// FilterFunc handles /text-filter (request body audit). The default
	// returns {"RiskLevel":"PASS"}.
	FilterFunc func(text string) TextFilterResponse
	// ReplaceFunc handles /text-replace (response body rewrite). The default
	// echoes the input text back via ResultText.
	ReplaceFunc func(text string) TextFilterResponse
	// contains filtered or unexported fields
}

MockAudit is a ToolGood-style text filter/replace service used by mod_body_process content audit tests.

func NewMockAudit added in v1.8.9

func NewMockAudit(t *testing.T) *MockAudit

NewMockAudit starts the audit service.

func (*MockAudit) CallCount added in v1.8.9

func (m *MockAudit) CallCount() int

CallCount returns the number of recorded audit calls.

func (*MockAudit) Calls added in v1.8.9

func (m *MockAudit) Calls() []AuditCall

Calls returns a snapshot of the recorded audit calls.

func (*MockAudit) Close added in v1.8.9

func (m *MockAudit) Close()

Close stops the audit service.

func (*MockAudit) FilterCalls added in v1.8.9

func (m *MockAudit) FilterCalls() []AuditCall

FilterCalls returns the recorded /text-filter calls.

func (*MockAudit) ReplaceCalls added in v1.8.9

func (m *MockAudit) ReplaceCalls() []AuditCall

ReplaceCalls returns the recorded /text-replace calls.

func (*MockAudit) URL added in v1.8.9

func (m *MockAudit) URL() string

URL returns the base URL to put into body_process rule params.

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
	// SSERaw, if non-nil, switches the handler to raw server-sent event
	// mode: each entry is written verbatim (e.g.
	// "event: error\ndata: {\"type\":\"error\"}\n\n") followed by a flush.
	// It takes precedence over SSEEvents and exists for protocols whose
	// frames carry non-data lines (e.g. Anthropic "event: error").
	SSERaw []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
	// SSEContentType overrides the Content-Type used in SSE/SSERaw modes
	// (default "text/event-stream"). It exists to exercise the response-side
	// SSE detection for vendor media types.
	SSEContentType string
	// SNIRecorder, if non-nil, is called with the TLS ClientHello server name
	// on every TLS handshake (TLS mock backend only).
	SNIRecorder func(serverName string)
	// HoldAfterHeader, if non-nil, blocks the handler after the response
	// status/headers have been flushed and before the body is written. It
	// keeps BFE blocked on the response body while the headers are already on
	// the wire, so a client-side write timeout can be observed.
	HoldAfterHeader <-chan struct{}
	// 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 NewMockBackendTLS added in v1.8.9

func NewMockBackendTLS(t *testing.T, clusterName string, response int, body string, opts TLSOptions) *MockBackend

NewMockBackendTLS starts an HTTPS mock backend with a caller-provided certificate, reusing the recording handler of MockBackend.

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) ContentLengths added in v1.8.9

func (b *MockBackend) ContentLengths() []int64

ContentLengths returns the ContentLength value of each backend request (-1 for chunked requests, 0 for requests without a body).

func (*MockBackend) HeaderCopies added in v1.8.9

func (b *MockBackend) HeaderCopies() []http.Header

HeaderCopies returns deep copies of all observed request headers.

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) Hosts added in v1.8.9

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

Hosts returns the Host header values observed on the backend requests.

func (*MockBackend) Models

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

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

func (*MockBackend) RawQueries added in v1.8.9

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

RawQueries returns a deep copy of all observed request URL raw queries.

func (*MockBackend) RequestBodies

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

RequestBodies returns a deep copy of all observed request bodies.

func (*MockBackend) SetReadBeforeClose added in v1.8.9

func (b *MockBackend) SetReadBeforeClose(n int)

SetReadBeforeClose sets ReadBeforeClose. It is called from tests while the server may still be handling a previous request, so the write must be synchronized with the handler reads.

func (*MockBackend) TransferEncodings added in v1.8.9

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

TransferEncodings returns the TransferEncoding values of each backend request (e.g. ["chunked"]).

func (*MockBackend) URLPaths added in v1.8.8

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

URLPaths returns a deep copy of all observed request URL paths.

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 MockChromaService added in v1.8.9

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

MockChromaService is an in-process httptest server implementing the Chroma HTTP API subset consumed by the mod_ai_cache vector provider: heartbeat, collection get_or_create, record upsert and vector query. The query endpoint evaluates the where conjunction for real (tenant_id $eq, created_at $gt and friends) and ranks candidates by the true cosine distance of the stored vectors, so tenant isolation and TTL semantics can be asserted against it. Counters, a global failure switch (HTTP 500), an empty-result switch and direct record injection support the test cases.

func NewMockChromaService added in v1.8.9

func NewMockChromaService(t *testing.T) *MockChromaService

NewMockChromaService starts a local Chroma mock with an empty store.

func (*MockChromaService) Addr added in v1.8.9

func (m *MockChromaService) Addr() string

Addr returns the host:port of the mock chroma service.

func (*MockChromaService) Close added in v1.8.9

func (m *MockChromaService) Close()

Close shuts down the mock chroma service.

func (*MockChromaService) CollectionsHits added in v1.8.9

func (m *MockChromaService) CollectionsHits() int

CollectionsHits returns the number of collection get_or_create calls received.

func (*MockChromaService) HeartbeatHits added in v1.8.9

func (m *MockChromaService) HeartbeatHits() int

HeartbeatHits returns the number of heartbeat calls received.

func (*MockChromaService) QueryFilters added in v1.8.9

func (m *MockChromaService) QueryFilters() []map[string]interface{}

QueryFilters returns deep copies of all where expressions received by the query endpoint, in arrival order.

func (*MockChromaService) QueryHits added in v1.8.9

func (m *MockChromaService) QueryHits() int

QueryHits returns the number of query calls received.

func (*MockChromaService) RecordCount added in v1.8.9

func (m *MockChromaService) RecordCount(collection string) int

RecordCount returns the number of records stored in the collection.

func (*MockChromaService) SetEmptyResults added in v1.8.9

func (m *MockChromaService) SetEmptyResults(empty bool)

SetEmptyResults forces the query endpoint to return empty result sets while still accepting and recording requests.

func (*MockChromaService) SetFailAll added in v1.8.9

func (m *MockChromaService) SetFailAll(fail bool)

SetFailAll switches the mock between global failure (every response is HTTP 500) and normal behavior.

func (*MockChromaService) SetStatus added in v1.8.9

func (m *MockChromaService) SetStatus(status int)

SetStatus forces the given HTTP status code for all subsequent responses (0 disables the override).

func (*MockChromaService) URL added in v1.8.9

func (m *MockChromaService) URL() string

URL returns the http address of the mock chroma service.

func (*MockChromaService) UpsertHits added in v1.8.9

func (m *MockChromaService) UpsertHits() int

UpsertHits returns the number of upsert calls received.

func (*MockChromaService) UpsertRecord added in v1.8.9

func (m *MockChromaService) UpsertRecord(collection string, rec ChromaRecord)

UpsertRecord injects one record directly into the in-memory store of the given collection, materializing the same metadata (tenant_id, answer, created_at) the real upload path sends. It bypasses HTTP and the failure switches, which makes it suitable for seeding expired records.

type MockDecisionService added in v1.8.9

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

MockDecisionService is an in-process httptest server implementing the System One decision protocol (POST /v1/systemone). It classifies the request state (the last user message) against a keyword script and returns the scripted answers, plus a concurrent-safe call counter.

func NewMockDecisionService added in v1.8.9

func NewMockDecisionService(t *testing.T, script DecisionScript) *MockDecisionService

NewMockDecisionService starts a local decision service mock serving the given script.

func (*MockDecisionService) Calls added in v1.8.9

func (m *MockDecisionService) Calls() int

Calls returns the number of decision service calls received. It is an alias of Hits.

func (*MockDecisionService) Close added in v1.8.9

func (m *MockDecisionService) Close()

Close shuts down the mock decision service.

func (*MockDecisionService) Hits added in v1.8.9

func (m *MockDecisionService) Hits() int

Hits returns the number of decision service calls received.

func (*MockDecisionService) RequestBodies added in v1.8.9

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

RequestBodies returns a deep copy of all received request bodies.

func (*MockDecisionService) SetFailAll added in v1.8.9

func (m *MockDecisionService) SetFailAll(fail bool)

SetFailAll switches the mock between global failure (every response is HTTP 500) and scripted behavior.

func (*MockDecisionService) SetScript added in v1.8.9

func (m *MockDecisionService) SetScript(script DecisionScript)

SetScript replaces the response script.

func (*MockDecisionService) SetStatus added in v1.8.9

func (m *MockDecisionService) SetStatus(status int)

SetStatus forces the given HTTP status code for all subsequent responses (0 disables the override).

func (*MockDecisionService) URL added in v1.8.9

func (m *MockDecisionService) URL() string

URL returns the http address of the mock decision service.

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 verifies nothing when EPPTLS is {Insecure: true}; an absent EPPTLS defaults to plaintext dialing), and records the pool metadata, request headers/body and response headers/body of every processed stream for test assertions.

In dual mode the same port additionally serves cleartext gRPC, so a test can flip EPPTLS.Plaintext on reload and prove which transport BFE's data connection and health probe use (TLSConnCount / PlaintextConnCount, and RestrictProtocols to break the abandoned transport).

func NewMockEPP added in v1.8.7

func NewMockEPP(t *testing.T, opts ...MockEPPOption) *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) PlaintextConnCount added in v1.8.9

func (m *MockEPP) PlaintextConnCount() int

PlaintextConnCount returns the number of accepted cleartext connections (data and probe) in dual mode.

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) RestrictProtocols added in v1.8.9

func (m *MockEPP) RestrictProtocols(tls, plaintext bool)

RestrictProtocols makes the mock accept only the given transport for new connections and closes every existing connection of the other transport. It lets a test prove that BFE actually abandoned the previous transport after a hot reload: the old connection is broken, so only a client that re-established the connection with the new transport keeps working.

func (*MockEPP) SetDecisionDelay added in v1.8.9

func (m *MockEPP) SetDecisionDelay(d time.Duration)

SetDecisionDelay makes the server wait d before replying with the scheduling decision. It is used to exercise EPPTimeout.Call.

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.

func (*MockEPP) TLSConnCount added in v1.8.9

func (m *MockEPP) TLSConnCount() int

TLSConnCount returns the number of accepted TLS connections (data and probe) in dual mode.

type MockEPPOption added in v1.8.9

type MockEPPOption func(*mockEPPConfig)

MockEPPOption customizes NewMockEPP.

func WithDualMode added in v1.8.9

func WithDualMode() MockEPPOption

WithDualMode makes the mock EPP accept both TLS and plaintext gRPC on its single listen port. Without it the mock only speaks TLS, matching the historical BFE default.

type MockEmbeddingService added in v1.8.9

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

MockEmbeddingService is an in-process httptest server implementing the OpenAI compatible embedding API (POST /v1/embeddings) consumed by mod_ai_cache. It returns scripted vectors per request text, plus a concurrent-safe call counter, a global failure switch (HTTP 500) and a request body recorder for assertions.

func NewMockEmbeddingService added in v1.8.9

func NewMockEmbeddingService(t *testing.T, script EmbeddingScript) *MockEmbeddingService

NewMockEmbeddingService starts a local embedding service mock serving the given script.

func (*MockEmbeddingService) Addr added in v1.8.9

func (m *MockEmbeddingService) Addr() string

Addr returns the host:port of the mock embedding service.

func (*MockEmbeddingService) Calls added in v1.8.9

func (m *MockEmbeddingService) Calls() int

Calls returns the number of embedding calls received. It is an alias of Hits.

func (*MockEmbeddingService) Close added in v1.8.9

func (m *MockEmbeddingService) Close()

Close shuts down the mock embedding service.

func (*MockEmbeddingService) Hits added in v1.8.9

func (m *MockEmbeddingService) Hits() int

Hits returns the number of embedding calls received.

func (*MockEmbeddingService) RequestBodies added in v1.8.9

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

RequestBodies returns a deep copy of all received request bodies.

func (*MockEmbeddingService) SetFailAll added in v1.8.9

func (m *MockEmbeddingService) SetFailAll(fail bool)

SetFailAll switches the mock between global failure (every response is HTTP 500) and scripted behavior.

func (*MockEmbeddingService) SetScript added in v1.8.9

func (m *MockEmbeddingService) SetScript(script EmbeddingScript)

SetScript replaces the keyword script.

func (*MockEmbeddingService) SetStatus added in v1.8.9

func (m *MockEmbeddingService) SetStatus(status int)

SetStatus forces the given HTTP status code for all subsequent responses (0 disables the override).

func (*MockEmbeddingService) URL added in v1.8.9

func (m *MockEmbeddingService) URL() string

URL returns the http address of the mock embedding service.

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) BinaryPath added in v1.8.9

func (p *ProcessEnv) BinaryPath() string

BinaryPath returns the absolute path of the compiled BFE binary. Build must be called first.

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) StartBFERaw added in v1.8.9

func (p *ProcessEnv) StartBFERaw(confDir, logDir string) (int, int, func(), error)

StartBFERaw behaves like StartBFE but returns an error instead of failing the test when BFE never opens its HTTP port (e.g. fail-fast startup rejection scenarios that assert the process refuses to start). On error the returned teardown function is nil and the process is already reaped.

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 RateLimitBatchLimits added in v1.8.9

type RateLimitBatchLimits struct {
	MaxCreateRPM     int64  `json:"max_create_rpm,omitempty"`
	MaxActiveBatches int64  `json:"max_active_batches,omitempty"`
	MaxFileBytes     int64  `json:"max_file_bytes,omitempty"`
	MaxFileLines     int64  `json:"max_file_lines,omitempty"`
	RedisKey         string `json:"redis_key,omitempty"`
}

RateLimitBatchLimits is the JSON representation of the batch limit section (mod_ai_batch); nil omits the section (policy does not restrict batch traffic).

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"`
		Batch          *RateLimitBatchLimits `json:"batch,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) AdvanceTime added in v1.8.9

func (s *RedisServer) AdvanceTime(d time.Duration)

AdvanceTime advances both the key-expiry clock and the virtual server clock (the one returned by the Redis TIME command). Time-based limiters that build sliding windows from TIME need the latter; FastForward alone only shifts key TTLs. The jump is measured from the later of the tracked virtual time and the current wall clock, so a jump is never diluted by elapsed test time.

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) FastForward added in v1.8.9

func (s *RedisServer) FastForward(d time.Duration)

FastForward advances the redis server clock, affecting key expiry.

func (*RedisServer) Fault added in v1.8.9

func (s *RedisServer) Fault()

Fault stops the server so that subsequent client calls are rejected (connection refused), simulating a redis outage.

func (*RedisServer) Get added in v1.8.9

func (s *RedisServer) Get(key string) string

Get returns the string value of a key ("" when missing).

func (*RedisServer) GetQuota

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

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

func (*RedisServer) HGetAll added in v1.8.9

func (s *RedisServer) HGetAll(key string) map[string]string

HGetAll returns the field/value map of a hash key (nil when the key is missing or not a hash). Used by scenarios that assert on BATCH_* records.

func (*RedisServer) Keys added in v1.8.8

func (s *RedisServer) Keys() []string

Keys returns all keys currently present in redis.

func (*RedisServer) Recover added in v1.8.9

func (s *RedisServer) Recover()

Recover starts a fresh empty server on the original address, restoring connectivity. It is used to assert fail-open behavior after an outage.

func (*RedisServer) Set added in v1.8.9

func (s *RedisServer) Set(key string, value string)

Set stores a raw string 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.

func (*RedisServer) ZMembers added in v1.8.9

func (s *RedisServer) ZMembers(key string) []string

ZMembers returns the members of a sorted set (nil when missing).

type TLSOptions added in v1.8.9

type TLSOptions struct {
	// CertPEM/KeyPEM is the server certificate presented to BFE.
	CertPEM []byte
	KeyPEM  []byte
	// ClientCAs, when non-nil, makes the backend require and verify a client
	// certificate against the pool (mutual TLS).
	ClientCAs *x509.CertPool
	// SNIRecorder, if non-nil, receives the SNI server name of each handshake.
	SNIRecorder func(serverName string)
	// ClientCertRecorder, if non-nil, receives the client certificate common
	// name of each request (empty when no client cert was presented).
	ClientCertRecorder func(commonName string)
}

TLSOptions configures a TLS mock backend.

type TestCA added in v1.8.9

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

TestCA is a throwaway certificate authority for TLS integration tests.

func NewTestCA added in v1.8.9

func NewTestCA(t *testing.T, commonName string) *TestCA

NewTestCA creates a self-signed CA valid for one hour.

func (*TestCA) IssueClientCert added in v1.8.9

func (ca *TestCA) IssueClientCert(t *testing.T, commonName string) ([]byte, []byte)

IssueClientCert issues a client certificate and returns PEM-encoded cert/key.

func (*TestCA) IssueServerCert added in v1.8.9

func (ca *TestCA) IssueServerCert(t *testing.T, dnsNames []string, ips []string) ([]byte, []byte)

IssueServerCert issues a server certificate for the given DNS names and IP addresses and returns PEM-encoded cert/key.

func (*TestCA) Pool added in v1.8.9

func (ca *TestCA) Pool() *x509.CertPool

Pool returns a cert pool containing the CA certificate.

func (*TestCA) WriteCAPEM added in v1.8.9

func (ca *TestCA) WriteCAPEM(path string) error

WriteCAPEM writes the CA certificate to path (creating parent directories).

type TextFilterResponse added in v1.8.9

type TextFilterResponse struct {
	RiskLevel      string
	SentimentScore float32
	ResultText     string
}

TextFilterResponse is the JSON body understood by mod_body_process. The gateway struct has no json tags, so the field names are matched case-insensitively (CamelCase is the canonical form).

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