Documentation
¶
Overview ¶
Package shared provides common HTTP handler utilities used across admin and proxy handler packages.
Index ¶
- Constants
- func EndpointLabelFromPath(path string) string
- func HistogramCountForTest(endpoint, status string) uint64
- func ObserveProxyOutcome(obs ProxyObservation)
- func OutcomeSnapshotForTest() map[string]int64
- func RecordProxyRequest()
- func RecordRealtimeOutcome(success bool)
- func RecordRouteRebuildCompleted()
- func RecordStreamMissingUsage()
- func ResetMetricsForTest()
- func ResetRealtimeForTest()
- func SetDBConnections(n int64)
- func SetDBConnectionsInUse(n int64)
- func SnapshotForTest() (requests, errors, streams, rebuilds int64)
- func StatusFromHTTP(code int) string
- func WriteAPIError(w http.ResponseWriter, err *APIError)
- func WriteError(w http.ResponseWriter, code int, message string)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- func WritePrometheusMetrics(w http.ResponseWriter) error
- type APIError
- type MetricsCollector
- type ProxyObservation
- type RealtimePoint
Constants ¶
const ( OutcomeSuccess = "success" OutcomeError = "error" OutcomeTimeout = "timeout" OutcomeUpstreamError = "upstream_error" OutcomeClientError = "client_error" )
Bounded outcome status labels (never raw HTTP codes or error strings).
const ( EndpointChat = "chat" EndpointMessages = "messages" EndpointResponses = "responses" EndpointEmbeddings = "embeddings" EndpointCompletions = "completions" EndpointImages = "images" EndpointRerank = "rerank" EndpointSearch = "search" EndpointGemini = "gemini" EndpointModels = "models" EndpointOther = "other" )
Bounded endpoint labels derived from path suffixes (never full URLs/models).
Variables ¶
This section is empty.
Functions ¶
func EndpointLabelFromPath ¶
EndpointLabelFromPath maps a request path to a low-cardinality endpoint label. Never returns raw paths; unknown paths become "other".
func HistogramCountForTest ¶
HistogramCountForTest returns sample count for one labeled histogram series.
func ObserveProxyOutcome ¶
func ObserveProxyOutcome(obs ProxyObservation)
ObserveProxyOutcome records a terminal proxy outcome: labeled counter, latency histogram, and legacy error counter (when not success). Labels are sanitized to a fixed allowlist; unknown values collapse to safe defaults.
func OutcomeSnapshotForTest ¶
OutcomeSnapshotForTest returns labeled outcome counts for assertions.
func RecordProxyRequest ¶
func RecordProxyRequest()
RecordProxyRequest increments the proxy request counter.
func RecordRealtimeOutcome ¶
func RecordRealtimeOutcome(success bool)
RecordRealtimeOutcome records one terminal proxy outcome into the live ring buffer. Called from ObserveProxyOutcome (the unified terminal observation point) — never from per-attempt intermediate steps.
func RecordRouteRebuildCompleted ¶
func RecordRouteRebuildCompleted()
RecordRouteRebuildCompleted increments successful route rebuild/cache-invalidate counter.
func RecordStreamMissingUsage ¶
func RecordStreamMissingUsage()
RecordStreamMissingUsage increments when a stream expected include_usage tokens but ended without usable counts (observability only; never invents tokens).
func ResetMetricsForTest ¶
func ResetMetricsForTest()
ResetMetricsForTest clears counters/gauges for deterministic tests.
func ResetRealtimeForTest ¶
func ResetRealtimeForTest()
ResetRealtimeForTest clears the ring buffer (test-only).
func SetDBConnections ¶
func SetDBConnections(n int64)
SetDBConnections sets the DB open-connection gauge.
func SetDBConnectionsInUse ¶
func SetDBConnectionsInUse(n int64)
SetDBConnectionsInUse sets the DB in-use connection gauge.
func SnapshotForTest ¶
func SnapshotForTest() (requests, errors, streams, rebuilds int64)
SnapshotForTest returns current counter values for assertions.
func StatusFromHTTP ¶
StatusFromHTTP maps an HTTP status to a bounded outcome label.
func WriteAPIError ¶
func WriteAPIError(w http.ResponseWriter, err *APIError)
WriteAPIError writes the public fields of APIError with the given status. Status defaults to Code when Code > 0; otherwise 500. When RequestID is set, also mirrors it on the X-Request-Id response header if that header is still empty (ingress middleware usually sets it first).
func WriteError ¶
func WriteError(w http.ResponseWriter, code int, message string)
WriteError writes a structured JSON error response to the client. It sets Content-Type: application/json and the given HTTP status code. Callers must use a non-2xx status for failures — never HTTP 200 with an error body.
func WriteJSON ¶ added in v0.12.0
func WriteJSON(w http.ResponseWriter, status int, v any)
WriteJSON writes v as a JSON response with Content-Type: application/json.
func WritePrometheusMetrics ¶
func WritePrometheusMetrics(w http.ResponseWriter) error
WritePrometheusMetrics writes Prometheus text-format metrics to w.
Types ¶
type APIError ¶
type APIError struct {
Code int `json:"-"`
Message string `json:"error"`
Detail string `json:"detail,omitempty"`
RequestID string `json:"request_id,omitempty"`
Internal error `json:"-"`
}
APIError represents a structured JSON error response. Message is safe for public consumption; Internal is logged but never sent. JSON field names are camelCase-compatible public keys used by the admin UI: - error (string message) - detail (optional classifier / subtype) - request_id (optional ingress correlation id, snake_case for log/ops tools)
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector is a zero-dependency Prometheus metrics collector. It tracks proxy request counts and operational gauges using atomic counters. Kept in handler/shared so proxy and admin handlers can record without importing app (app already depends on handler packages).
type ProxyObservation ¶
type ProxyObservation struct {
Endpoint string // bounded label from EndpointLabelFromPath
Status string // Outcome* constants
Stream bool // stream vs non-stream
Latency time.Duration // total observed latency for the attempt/request
}
ProxyObservation is a privacy-safe, low-cardinality proxy terminal event. It must never carry prompts, keys, cookies, model names, or upstream bodies.
type RealtimePoint ¶
type RealtimePoint struct {
Ts int64 `json:"ts"` // unix seconds
Total int64 `json:"total"`
Success int64 `json:"success"`
}
RealtimePoint is one second of live traffic.
func RealtimeSnapshot ¶
func RealtimeSnapshot() (points []RealtimePoint, lifetime int64)
RealtimeSnapshot returns the live traffic series, oldest first, plus the lifetime request count. Missing seconds are zero-filled so the frontend can render a contiguous line without guessing.