Documentation
¶
Overview ¶
Package shared provides common HTTP handler utilities used across admin and proxy handler packages.
Index ¶
- Constants
- func ActiveChannelsForTest() int64
- func ActiveStreamsForTest() int64
- func DecActiveStreams()
- func EndpointLabelFromPath(path string) string
- func HistogramCountForTest(endpoint, status string) uint64
- func IncActiveStreams()
- func ObserveProxyOutcome(obs ProxyObservation)
- func OutcomeSnapshotForTest() map[string]int64
- func RecordProxyRequest()
- func RecordRealtimeOutcome(success bool)
- func RecordRouteRebuildCompleted()
- func RecordStreamMissingUsage()
- func ResetMetricsForTest()
- func ResetRealtimeForTest()
- func SetActiveChannels(n int64)
- func SetActiveStreams(n int64)
- 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 WriteErrorCode(w http.ResponseWriter, code int, errorCode, 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 ActiveChannelsForTest ¶ added in v0.13.0
func ActiveChannelsForTest() int64
ActiveChannelsForTest returns the current metapi_active_channels gauge value.
func ActiveStreamsForTest ¶ added in v0.13.0
func ActiveStreamsForTest() int64
ActiveStreamsForTest returns the current metapi_proxy_streams_active gauge value.
func DecActiveStreams ¶ added in v0.13.0
func DecActiveStreams()
DecActiveStreams decrements the metapi_proxy_streams_active gauge. Call when a proxied SSE/stream response ends (success, error, or client disconnect). Uses Add(-1) so a misplaced Dec can drive the gauge negative, which is the honest signal that Inc/Dec are unbalanced.
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 IncActiveStreams ¶ added in v0.13.0
func IncActiveStreams()
IncActiveStreams increments the metapi_proxy_streams_active gauge. Call at the start of every proxied SSE/stream response. Pair with DecActiveStreams.
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 SetActiveChannels ¶
func SetActiveChannels(n int64)
SetActiveChannels sets the metapi_active_channels gauge. Call from the channel list handler (or a periodic refresh) so /metrics reflects the real count of proxy channels instead of a constant 0.
func SetActiveStreams ¶ added in v0.13.0
func SetActiveStreams(n int64)
SetActiveStreams sets the metapi_proxy_streams_active gauge to an absolute value (useful for reconciliation/edge resets from a coordinator snapshot).
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 WriteErrorCode ¶ added in v0.16.20
func WriteErrorCode(w http.ResponseWriter, code int, errorCode, message string)
WriteErrorCode writes a structured JSON error response carrying a machine-readable errorCode in addition to the human-readable message. errorCode must be a stable camelCase identifier from the registry documented in docs/api.md; message stays the user-facing text.
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"`
ErrorCode string `json:"errorCode,omitempty"`
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; human-readable, never matched by clients)
- errorCode (optional machine-readable identifier; stable camelCase value from the registry in docs/api.md — additive, omitted when unset)
- detail (optional free-form classifier / subtype; NOT a stable contract)
- 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, uptimeSeconds int64)
RealtimeSnapshot returns the live traffic series, oldest first, plus the lifetime request count and the process uptime in whole seconds. The two counters are distinct signals: lifetime is a monotonic request counter, uptimeSeconds is wall-clock runtime — the frontend renders the latter as "uptime". Missing seconds are zero-filled so the frontend can render a contiguous line without guessing.