shared

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 13 Imported by: 1 module, 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

Overview

Package shared provides common HTTP handler utilities used across admin and proxy handler packages.

Index

Constants

View Source
const (
	OutcomeSuccess       = "success"
	OutcomeError         = "error"
	OutcomeTimeout       = "timeout"
	OutcomeUnavailable   = "unavailable"
	OutcomeUpstreamError = "upstream_error"
	OutcomeClientError   = "client_error"
)

Bounded outcome status labels (never raw HTTP codes or error strings).

View Source
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

func EndpointLabelFromPath(path string) string

EndpointLabelFromPath maps a request path to a low-cardinality endpoint label. Never returns raw paths; unknown paths become "other".

func HistogramCountForTest

func HistogramCountForTest(endpoint, status string) uint64

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, legacy error counter (when not success), and optional Observer hook. Labels are sanitized to a fixed allowlist; unknown values collapse to safe defaults.

func OutcomeSnapshotForTest

func OutcomeSnapshotForTest() map[string]int64

OutcomeSnapshotForTest returns labeled outcome counts for assertions.

func RecordDBConnError

func RecordDBConnError()

RecordDBConnError increments the DB connection-budget / open error counter (e.g. SQLSTATE 53300 too many connections for role). Delegates to the app/observability leaf so lower layers (scheduler) can record without importing handler/shared (resolves package-boundaries §5.11).

func RecordProxyError

func RecordProxyError()

RecordProxyError increments the proxy error counter.

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 RecordStreamEnd

func RecordStreamEnd()

RecordStreamEnd decrements active SSE stream count.

func RecordStreamMissingUsage

func RecordStreamMissingUsage()

RecordStreamMissingUsage increments when a stream expected include_usage tokens but ended without usable counts (observability only; never invents tokens).

func RecordStreamStart

func RecordStreamStart()

RecordStreamStart increments active SSE stream count.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the chi RequestID middleware value when present.

func RequestIDFromRequest

func RequestIDFromRequest(r *http.Request) string

RequestIDFromRequest returns the ingress request/trace id for r.

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 active channel gauge.

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 SetObserver

func SetObserver(o Observer)

SetObserver registers an optional export sink. Pass nil to reset to no-op. Safe for concurrent use; hot path reads under RLock.

func SnapshotForTest

func SnapshotForTest() (requests, errors, streams, rebuilds int64)

SnapshotForTest returns current counter values for assertions.

func StatusFromHTTP

func StatusFromHTTP(code int) string

StatusFromHTTP maps an HTTP status to a bounded outcome label.

func StreamMissingUsageTotal

func StreamMissingUsageTotal() int64

StreamMissingUsageTotal returns the missing-usage counter (tests/ops).

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 WriteErrorDetail

func WriteErrorDetail(w http.ResponseWriter, code int, message, detail string)

WriteErrorDetail writes a structured JSON error response with additional detail field (e.g., "invalid_request" error type).

func WriteErrorDetailWithRequestID

func WriteErrorDetailWithRequestID(w http.ResponseWriter, code int, message, detail, requestID string)

WriteErrorDetailWithRequestID is WriteErrorDetail plus an optional request/trace id.

func WriteErrorWithRequestID

func WriteErrorWithRequestID(w http.ResponseWriter, code int, message, requestID string)

WriteErrorWithRequestID is WriteError plus an optional request/trace id field.

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)

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

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 Observer

type Observer interface {
	ObserveProxy(obs ProxyObservation)
}

Observer is an optional export hook for OTEL/Langfuse-style sinks. Implementations must not block; drop or buffer on backpressure. The default is a no-op.

func GetObserver

func GetObserver() Observer

GetObserver returns the currently registered Observer (never nil).

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.

Jump to

Keyboard shortcuts

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