Documentation
¶
Index ¶
- func NormalizePath(path string) string
- func Reset() bool
- func SetProvider(p Provider)
- type AIProxyRecorder
- type Config
- type NoOpProvider
- func (n *NoOpProvider) DecRequestsInFlight()
- func (n *NoOpProvider) Handler() http.Handler
- func (n *NoOpProvider) IncRequestsInFlight()
- func (n *NoOpProvider) RecordCacheHit(provider string)
- func (n *NoOpProvider) RecordCacheMiss(provider string)
- func (n *NoOpProvider) RecordDBQuery(operation, schema, entity, table string, duration time.Duration, err error)
- func (n *NoOpProvider) RecordEventProcessed(source, eventType, status string, duration time.Duration)
- func (n *NoOpProvider) RecordEventPublished(source, eventType string)
- func (n *NoOpProvider) RecordHTTPRequest(method, path, status string, duration time.Duration)
- func (n *NoOpProvider) RecordPanic(methodName string)
- func (n *NoOpProvider) UpdateCacheSize(provider string, size int64)
- func (n *NoOpProvider) UpdateEventQueueSize(size int64)
- type PrometheusProvider
- func (p *PrometheusProvider) DecRequestsInFlight()
- func (p *PrometheusProvider) Handler() http.Handler
- func (p *PrometheusProvider) IncRequestsInFlight()
- func (p *PrometheusProvider) JSONHandler() http.Handler
- func (p *PrometheusProvider) Middleware(next http.Handler) http.Handler
- func (p *PrometheusProvider) Push() error
- func (p *PrometheusProvider) PushAndReset() error
- func (p *PrometheusProvider) PushToEndpoint(ctx context.Context) error
- func (p *PrometheusProvider) RecordAIProxy(upstream, kind, model, statusClass, outcome string, duration time.Duration, ...)
- func (p *PrometheusProvider) RecordCacheHit(provider string)
- func (p *PrometheusProvider) RecordCacheMiss(provider string)
- func (p *PrometheusProvider) RecordDBQuery(operation, schema, entity, table string, duration time.Duration, err error)
- func (p *PrometheusProvider) RecordEventProcessed(source, eventType, status string, duration time.Duration)
- func (p *PrometheusProvider) RecordEventPublished(source, eventType string)
- func (p *PrometheusProvider) RecordHTTPRequest(method, path, status string, duration time.Duration)
- func (p *PrometheusProvider) RecordPanic(methodName string)
- func (p *PrometheusProvider) Reset()
- func (p *PrometheusProvider) ResetHandler() http.Handler
- func (p *PrometheusProvider) StopAutoPush()
- func (p *PrometheusProvider) UpdateCacheSize(provider string, size int64)
- func (p *PrometheusProvider) UpdateEventQueueSize(size int64)
- type Provider
- type Resetter
- type ResponseWriter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NormalizePath ¶ added in v1.3.5
NormalizePath replaces dynamic-looking path segments (numeric IDs, UUIDs, long hex strings and other long opaque tokens) with ":id" so that /users/123 and /users/456 share one label value.
Types ¶
type AIProxyRecorder ¶ added in v1.3.9
type AIProxyRecorder interface {
// RecordAIProxy records one proxied (or refused) request. statusClass is "2xx".."5xx",
// outcome is ok, upstream_error, denied or rate_limited, model may be empty.
RecordAIProxy(upstream, kind, model, statusClass, outcome string, duration time.Duration, promptTokens, completionTokens int64)
}
AIProxyRecorder is optionally implemented by providers that record aiproxy traffic. pkg/aiproxy uses it when the global provider implements it.
type Config ¶ added in v1.0.5
type Config struct {
// Enabled determines whether metrics collection is enabled
Enabled bool `mapstructure:"enabled"`
// Provider specifies which metrics provider to use (prometheus, noop)
Provider string `mapstructure:"provider"`
// Namespace is an optional prefix for all metric names
Namespace string `mapstructure:"namespace"`
// HTTPRequestBuckets defines histogram buckets for HTTP request duration (in seconds)
// Default: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
HTTPRequestBuckets []float64 `mapstructure:"http_request_buckets"`
// DBQueryBuckets defines histogram buckets for database query duration (in seconds)
// Default: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5]
DBQueryBuckets []float64 `mapstructure:"db_query_buckets"`
// HTTPMaxPaths caps the number of distinct values of the "path" label on HTTP
// metrics. Paths beyond the cap are reported as "other". Paths are already
// normalized (route pattern, or dynamic segments replaced with ":id").
// Default: 1024. Set to a negative value to disable the cap.
HTTPMaxPaths int `mapstructure:"http_max_paths"`
// HTTPPathNormalizer optionally maps a request to its "path" label (e.g. the
// matched route template of your router). Return "" to fall back to the
// default behaviour (ServeMux pattern, then generic ID normalization).
HTTPPathNormalizer func(*http.Request) string `mapstructure:"-"`
// PushgatewayURL is the URL of the Prometheus Pushgateway (optional)
// If set, metrics will be pushed to this gateway instead of only being scraped
// Example: "http://pushgateway:9091"
PushgatewayURL string `mapstructure:"pushgateway_url"`
// PushgatewayJobName is the job name to use when pushing metrics to Pushgateway
// Default: "resolvespec"
PushgatewayJobName string `mapstructure:"pushgateway_job_name"`
// PushgatewayInterval is the interval at which to push metrics to Pushgateway
// Only used if PushgatewayURL is set. If 0, automatic pushing is disabled.
// Default: 0 (no automatic pushing)
PushgatewayInterval int `mapstructure:"pushgateway_interval"`
// PushEndpointURL is a custom HTTP endpoint that metrics are POSTed to
// (independent of Pushgateway). Example: "https://collector.example.com/metrics"
PushEndpointURL string `mapstructure:"push_endpoint_url"`
// PushEndpointFormat is the request body format: "text" (Prometheus text
// exposition, Content-Type text/plain; version=0.0.4) or "json".
// Default: "text"
PushEndpointFormat string `mapstructure:"push_endpoint_format"`
// PushEndpointHeaders are extra headers sent with each POST (e.g. Authorization).
PushEndpointHeaders map[string]string `mapstructure:"push_endpoint_headers"`
// PushEndpointInterval is the interval in seconds for automatic POSTs.
// If 0, automatic posting is disabled (PushToEndpoint can still be called manually).
PushEndpointInterval int `mapstructure:"push_endpoint_interval"`
// PushEndpointTimeout is the per-request timeout in seconds. Default: 10
PushEndpointTimeout int `mapstructure:"push_endpoint_timeout"`
// PushEndpointResetOnSuccess clears local counters and histograms after the
// endpoint answers with a 2xx status. Default: false.
PushEndpointResetOnSuccess bool `mapstructure:"push_endpoint_reset_on_success"`
// PushgatewayResetOnPush clears the local counters and histograms after each
// successful push (automatic or via PushAndReset), so each push carries only
// the activity since the previous one. Default: false.
PushgatewayResetOnPush bool `mapstructure:"pushgateway_reset_on_push"`
}
Config holds configuration for the metrics provider
func DefaultConfig ¶ added in v1.0.5
func DefaultConfig() *Config
DefaultConfig returns a Config with sensible defaults
Example ¶
ExampleDefaultConfig demonstrates getting default configuration
package main
import (
"fmt"
"github.com/bitechdev/ResolveSpec/pkg/metrics"
)
func main() {
config := metrics.DefaultConfig()
fmt.Printf("Default provider: %s\n", config.Provider)
fmt.Printf("Default enabled: %v\n", config.Enabled)
}
Output: Default provider: prometheus Default enabled: true
func (*Config) ApplyDefaults ¶ added in v1.0.5
func (c *Config) ApplyDefaults()
ApplyDefaults fills in any missing values with defaults
Example ¶
ExampleConfig_ApplyDefaults demonstrates applying defaults to partial config
package main
import (
"fmt"
"github.com/bitechdev/ResolveSpec/pkg/metrics"
)
func main() {
// Create partial configuration
config := &metrics.Config{
Namespace: "myapp",
// Other fields will be filled with defaults
}
// Apply defaults
config.ApplyDefaults()
fmt.Printf("Provider: %s\n", config.Provider)
fmt.Printf("Namespace: %s\n", config.Namespace)
}
Output: Provider: prometheus Namespace: myapp
type NoOpProvider ¶
type NoOpProvider struct{}
NoOpProvider is a no-op implementation of Provider
func (*NoOpProvider) DecRequestsInFlight ¶
func (n *NoOpProvider) DecRequestsInFlight()
func (*NoOpProvider) Handler ¶
func (n *NoOpProvider) Handler() http.Handler
func (*NoOpProvider) IncRequestsInFlight ¶
func (n *NoOpProvider) IncRequestsInFlight()
func (*NoOpProvider) RecordCacheHit ¶
func (n *NoOpProvider) RecordCacheHit(provider string)
func (*NoOpProvider) RecordCacheMiss ¶
func (n *NoOpProvider) RecordCacheMiss(provider string)
func (*NoOpProvider) RecordDBQuery ¶
func (n *NoOpProvider) RecordDBQuery(operation, schema, entity, table string, duration time.Duration, err error)
func (*NoOpProvider) RecordEventProcessed ¶ added in v0.0.107
func (n *NoOpProvider) RecordEventProcessed(source, eventType, status string, duration time.Duration)
func (*NoOpProvider) RecordEventPublished ¶ added in v0.0.107
func (n *NoOpProvider) RecordEventPublished(source, eventType string)
func (*NoOpProvider) RecordHTTPRequest ¶
func (n *NoOpProvider) RecordHTTPRequest(method, path, status string, duration time.Duration)
func (*NoOpProvider) RecordPanic ¶ added in v0.0.122
func (n *NoOpProvider) RecordPanic(methodName string)
func (*NoOpProvider) UpdateCacheSize ¶
func (n *NoOpProvider) UpdateCacheSize(provider string, size int64)
func (*NoOpProvider) UpdateEventQueueSize ¶ added in v0.0.107
func (n *NoOpProvider) UpdateEventQueueSize(size int64)
type PrometheusProvider ¶
type PrometheusProvider struct {
// contains filtered or unexported fields
}
PrometheusProvider implements the Provider interface using Prometheus
func NewPrometheusProvider ¶
func NewPrometheusProvider(cfg *Config) *PrometheusProvider
NewPrometheusProvider creates a new Prometheus metrics provider If cfg is nil, default configuration will be used
Example (Custom) ¶
ExampleNewPrometheusProvider_custom demonstrates using custom configuration
package main
import (
"fmt"
"github.com/bitechdev/ResolveSpec/pkg/metrics"
)
func main() {
// Create custom configuration
config := &metrics.Config{
Enabled: true,
Provider: "prometheus",
Namespace: "myapp",
HTTPRequestBuckets: []float64{0.01, 0.05, 0.1, 0.5, 1, 2, 5},
DBQueryBuckets: []float64{0.001, 0.01, 0.05, 0.1, 0.5, 1},
}
// Initialize with custom configuration
provider := metrics.NewPrometheusProvider(config)
metrics.SetProvider(provider)
fmt.Println("Provider initialized with custom config")
}
Output: Provider initialized with custom config
Example (Default) ¶
ExampleNewPrometheusProvider_default demonstrates using default configuration
package main
import (
"fmt"
"github.com/bitechdev/ResolveSpec/pkg/metrics"
)
func main() {
// Initialize with default configuration
provider := metrics.NewPrometheusProvider(nil)
metrics.SetProvider(provider)
fmt.Println("Provider initialized with defaults")
}
Output: Provider initialized with defaults
func (*PrometheusProvider) DecRequestsInFlight ¶
func (p *PrometheusProvider) DecRequestsInFlight()
DecRequestsInFlight implements Provider interface
func (*PrometheusProvider) Handler ¶
func (p *PrometheusProvider) Handler() http.Handler
Handler implements Provider interface It responds 404 when metrics are disabled.
func (*PrometheusProvider) IncRequestsInFlight ¶
func (p *PrometheusProvider) IncRequestsInFlight()
IncRequestsInFlight implements Provider interface
func (*PrometheusProvider) JSONHandler ¶ added in v1.3.5
func (p *PrometheusProvider) JSONHandler() http.Handler
JSONHandler returns an HTTP handler serving the current metrics as JSON (same shape as the "json" push endpoint format). Only GET and HEAD are accepted, and it responds 404 when metrics are disabled. It performs no authentication; mount it on an internal/protected route.
func (*PrometheusProvider) Middleware ¶
func (p *PrometheusProvider) Middleware(next http.Handler) http.Handler
Middleware returns an HTTP middleware that collects metrics When metrics are disabled it returns next unchanged.
func (*PrometheusProvider) Push ¶ added in v1.0.6
func (p *PrometheusProvider) Push() error
Push manually pushes metrics to the configured Pushgateway Returns an error if pushing fails or if Pushgateway is not configured
func (*PrometheusProvider) PushAndReset ¶ added in v1.3.5
func (p *PrometheusProvider) PushAndReset() error
PushAndReset pushes metrics to the Pushgateway and, only if the push succeeded, clears the local stats. Returns an error if Pushgateway is not configured, so stats are never discarded without being delivered. Observations recorded between the push and the reset are lost.
func (*PrometheusProvider) PushToEndpoint ¶ added in v1.3.5
func (p *PrometheusProvider) PushToEndpoint(ctx context.Context) error
PushToEndpoint POSTs the current metrics to the configured PushEndpointURL. If PushEndpointResetOnSuccess is set, local stats are cleared after a 2xx reply. Returns an error if no endpoint is configured.
func (*PrometheusProvider) RecordAIProxy ¶ added in v1.3.9
func (p *PrometheusProvider) RecordAIProxy(upstream, kind, model, statusClass, outcome string, duration time.Duration, promptTokens, completionTokens int64)
RecordAIProxy implements AIProxyRecorder
func (*PrometheusProvider) RecordCacheHit ¶
func (p *PrometheusProvider) RecordCacheHit(provider string)
RecordCacheHit implements Provider interface
func (*PrometheusProvider) RecordCacheMiss ¶
func (p *PrometheusProvider) RecordCacheMiss(provider string)
RecordCacheMiss implements Provider interface
func (*PrometheusProvider) RecordDBQuery ¶
func (p *PrometheusProvider) RecordDBQuery(operation, schema, entity, table string, duration time.Duration, err error)
RecordDBQuery implements Provider interface
func (*PrometheusProvider) RecordEventProcessed ¶ added in v1.0.5
func (p *PrometheusProvider) RecordEventProcessed(source, eventType, status string, duration time.Duration)
RecordEventProcessed implements Provider interface
func (*PrometheusProvider) RecordEventPublished ¶ added in v1.0.5
func (p *PrometheusProvider) RecordEventPublished(source, eventType string)
RecordEventPublished implements Provider interface
func (*PrometheusProvider) RecordHTTPRequest ¶
func (p *PrometheusProvider) RecordHTTPRequest(method, path, status string, duration time.Duration)
RecordHTTPRequest implements Provider interface The path is normalized and capped to keep label cardinality bounded.
func (*PrometheusProvider) RecordPanic ¶ added in v0.0.122
func (p *PrometheusProvider) RecordPanic(methodName string)
RecordPanic implements the Provider interface
func (*PrometheusProvider) Reset ¶ added in v1.3.5
func (p *PrometheusProvider) Reset()
Reset clears all recorded counters, histograms and labelled gauges (cache size) and forgets the tracked HTTP path labels. Live gauges (requests in flight, event queue size) are left untouched since they reflect current state. Prometheus treats the drop in counters as a counter reset, so rate() and increase() keep working on the scraper side.
func (*PrometheusProvider) ResetHandler ¶ added in v1.3.5
func (p *PrometheusProvider) ResetHandler() http.Handler
ResetHandler returns an HTTP handler that clears local stats on POST. With ?push=true it first pushes to the Pushgateway and only resets on success. The handler performs no authentication; mount it on an internal/protected route.
func (*PrometheusProvider) StopAutoPush ¶ added in v1.0.6
func (p *PrometheusProvider) StopAutoPush()
StopAutoPush stops the automatic push goroutine This should be called when shutting down the application
func (*PrometheusProvider) UpdateCacheSize ¶
func (p *PrometheusProvider) UpdateCacheSize(provider string, size int64)
UpdateCacheSize implements Provider interface
func (*PrometheusProvider) UpdateEventQueueSize ¶ added in v1.0.5
func (p *PrometheusProvider) UpdateEventQueueSize(size int64)
UpdateEventQueueSize implements Provider interface
type Provider ¶
type Provider interface {
// RecordHTTPRequest records metrics for an HTTP request
RecordHTTPRequest(method, path, status string, duration time.Duration)
// IncRequestsInFlight increments the in-flight requests counter
IncRequestsInFlight()
// DecRequestsInFlight decrements the in-flight requests counter
DecRequestsInFlight()
// RecordDBQuery records metrics for a database query
RecordDBQuery(operation, schema, entity, table string, duration time.Duration, err error)
// RecordCacheHit records a cache hit
RecordCacheHit(provider string)
// RecordCacheMiss records a cache miss
RecordCacheMiss(provider string)
// UpdateCacheSize updates the cache size metric
UpdateCacheSize(provider string, size int64)
// RecordEventPublished records an event publication
RecordEventPublished(source, eventType string)
// RecordEventProcessed records an event processing with its status
RecordEventProcessed(source, eventType, status string, duration time.Duration)
// UpdateEventQueueSize updates the event queue size metric
UpdateEventQueueSize(size int64)
// RecordPanic records a panic event
RecordPanic(methodName string)
// Handler returns an HTTP handler for exposing metrics (e.g., /metrics endpoint)
Handler() http.Handler
}
Provider defines the interface for metric collection
type Resetter ¶ added in v1.3.5
type Resetter interface {
Reset()
}
Resetter is optionally implemented by providers that can clear their recorded stats.
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
// contains filtered or unexported fields
}
ResponseWriter wraps http.ResponseWriter to capture status code
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter
func (*ResponseWriter) WriteHeader ¶
func (rw *ResponseWriter) WriteHeader(code int)