Documentation
¶
Overview ¶
Package metrics provides Prometheus metrics collection for the CodeAI application.
Index ¶
- func ClassifyError(err error) string
- func ClassifyHTTPError(statusCode int) string
- func DefaultPathNormalizer(path string) string
- func HTTPMiddleware(registry *Registry) func(http.Handler) http.Handler
- func HTTPMiddlewareWithOptions(registry *Registry, opts MiddlewareOptions) func(http.Handler) http.Handler
- func Handler() http.Handler
- func SetGlobal(r *Registry)
- func StartQueryContext(ctx context.Context, operation Operation, table string) context.Context
- type CircuitBreakerState
- type Config
- type DBMetrics
- func (d *DBMetrics) EndQueryContext(ctx context.Context, err error)
- func (d *DBMetrics) NewQueryTimer(operation Operation, table string) *QueryTimer
- func (d *DBMetrics) RecordQuery(operation Operation, table string, duration time.Duration, err error)
- func (d *DBMetrics) RecordQueryError(operation Operation, table string, errorType string)
- func (d *DBMetrics) StartConnectionStatsCollector(db *sql.DB, interval time.Duration) func()
- func (d *DBMetrics) UpdateConnectionStats(active, idle, max int)
- func (d *DBMetrics) UpdateFromDBStats(stats sql.DBStats)
- type DBQueryContext
- type HTTPMetrics
- func (h *HTTPMetrics) ActiveRequests() interface{}
- func (h *HTTPMetrics) DecActiveRequests(method, path string)
- func (h *HTTPMetrics) IncActiveRequests(method, path string)
- func (h *HTTPMetrics) RecordRequest(method, path string, statusCode int, duration float64, reqSize, respSize int64)
- func (h *HTTPMetrics) RequestDuration() interface{}
- func (h *HTTPMetrics) RequestsTotal() interface{}
- type HistogramBucketsConfig
- type IntegrationCallTimer
- type IntegrationMetrics
- func (i *IntegrationMetrics) CallsTotal() interface{}
- func (i *IntegrationMetrics) CircuitState() interface{}
- func (i *IntegrationMetrics) NewCallTimer(serviceName, endpoint string) *IntegrationCallTimer
- func (i *IntegrationMetrics) RecordCall(serviceName, endpoint string, statusCode int, duration time.Duration)
- func (i *IntegrationMetrics) RecordCallWithStatus(serviceName, endpoint string, success bool, duration time.Duration)
- func (i *IntegrationMetrics) RecordError(serviceName, endpoint, errorType string)
- func (i *IntegrationMetrics) RecordRetry(serviceName, endpoint string)
- func (i *IntegrationMetrics) SetCircuitBreakerState(serviceName string, state CircuitBreakerState)
- type MiddlewareOptions
- type Operation
- type QueryStatus
- type QueryTimer
- type Registry
- func (r *Registry) Config() Config
- func (r *Registry) DB() *DBMetrics
- func (r *Registry) HTTP() *HTTPMetrics
- func (r *Registry) Handler() http.Handler
- func (r *Registry) HandlerWithAuth(authFn func(r *http.Request) bool) http.Handler
- func (r *Registry) Integration() *IntegrationMetrics
- func (r *Registry) PrometheusRegistry() *prometheus.Registry
- func (r *Registry) RegisterMetricsRoute(mux interface{ ... })
- func (r *Registry) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Registry) Workflow() *WorkflowMetrics
- type WorkflowExecutionTimer
- type WorkflowMetrics
- func (w *WorkflowMetrics) ActiveCount() interface{}
- func (w *WorkflowMetrics) DecActiveWorkflows(workflowName string)
- func (w *WorkflowMetrics) ExecutionsTotal() interface{}
- func (w *WorkflowMetrics) IncActiveWorkflows(workflowName string)
- func (w *WorkflowMetrics) NewExecutionTimer(workflowName string) *WorkflowExecutionTimer
- func (w *WorkflowMetrics) NewStepTimer(workflowName, stepName string) *WorkflowStepTimer
- func (w *WorkflowMetrics) RecordExecution(workflowName string, status WorkflowStatus, duration time.Duration)
- func (w *WorkflowMetrics) RecordStep(workflowName, stepName string, duration time.Duration)
- func (w *WorkflowMetrics) SetActiveWorkflows(workflowName string, count int)
- type WorkflowStatus
- type WorkflowStepTimer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClassifyError ¶
ClassifyError classifies an error into a type for metrics.
func ClassifyHTTPError ¶
ClassifyHTTPError classifies an HTTP status code into an error type.
func DefaultPathNormalizer ¶
DefaultPathNormalizer normalizes paths by replacing dynamic segments with placeholders.
func HTTPMiddleware ¶
HTTPMiddleware returns an HTTP middleware that records metrics for each request.
func HTTPMiddlewareWithOptions ¶
func HTTPMiddlewareWithOptions(registry *Registry, opts MiddlewareOptions) func(http.Handler) http.Handler
HTTPMiddlewareWithOptions returns an HTTP middleware with custom options.
Types ¶
type CircuitBreakerState ¶
type CircuitBreakerState string
CircuitBreakerState represents the state of a circuit breaker.
const ( CircuitBreakerClosed CircuitBreakerState = "closed" CircuitBreakerHalfOpen CircuitBreakerState = "half-open" CircuitBreakerOpen CircuitBreakerState = "open" )
func (CircuitBreakerState) Value ¶
func (s CircuitBreakerState) Value() float64
CircuitBreakerStateValue returns the numeric value for a circuit breaker state.
type Config ¶
type Config struct {
// Namespace is the prefix for all metrics (default: "codeai")
Namespace string
// Subsystem groups related metrics (e.g., "http", "database")
Subsystem string
// DefaultLabels are applied to all metrics
DefaultLabels map[string]string
// EnableProcessMetrics enables Go process metrics (CPU, memory, goroutines)
EnableProcessMetrics bool
// EnableRuntimeMetrics enables Go runtime metrics
EnableRuntimeMetrics bool
// HistogramBuckets allows customizing default histogram buckets
HistogramBuckets HistogramBucketsConfig
}
Config holds configuration for the metrics module.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the default metrics configuration.
func (Config) WithEnvironment ¶
WithEnvironment sets the environment label.
func (Config) WithInstance ¶
WithInstance sets the instance label.
func (Config) WithVersion ¶
WithVersion sets the version label.
type DBMetrics ¶
type DBMetrics struct {
// contains filtered or unexported fields
}
DBMetrics provides methods to record database-related metrics.
func (*DBMetrics) EndQueryContext ¶
EndQueryContext records query metrics from context.
func (*DBMetrics) NewQueryTimer ¶
func (d *DBMetrics) NewQueryTimer(operation Operation, table string) *QueryTimer
NewQueryTimer creates a new query timer.
func (*DBMetrics) RecordQuery ¶
func (d *DBMetrics) RecordQuery(operation Operation, table string, duration time.Duration, err error)
RecordQuery records metrics for a database query.
func (*DBMetrics) RecordQueryError ¶
RecordQueryError records a query error with error type classification.
func (*DBMetrics) StartConnectionStatsCollector ¶
StartConnectionStatsCollector starts a goroutine that periodically updates connection stats from a sql.DB instance.
func (*DBMetrics) UpdateConnectionStats ¶
UpdateConnectionStats updates database connection pool metrics.
func (*DBMetrics) UpdateFromDBStats ¶
UpdateFromDBStats updates metrics from sql.DBStats.
type DBQueryContext ¶
DBQueryContext stores query timing information in context.
type HTTPMetrics ¶
type HTTPMetrics struct {
// contains filtered or unexported fields
}
HTTPMetrics provides methods to record HTTP-related metrics.
func (*HTTPMetrics) ActiveRequests ¶
func (h *HTTPMetrics) ActiveRequests() interface{}
ActiveRequests returns the gauge for active requests (for testing).
func (*HTTPMetrics) DecActiveRequests ¶
func (h *HTTPMetrics) DecActiveRequests(method, path string)
DecActiveRequests decrements the active request count.
func (*HTTPMetrics) IncActiveRequests ¶
func (h *HTTPMetrics) IncActiveRequests(method, path string)
IncActiveRequests increments the active request count.
func (*HTTPMetrics) RecordRequest ¶
func (h *HTTPMetrics) RecordRequest(method, path string, statusCode int, duration float64, reqSize, respSize int64)
RecordRequest records all metrics for an HTTP request.
func (*HTTPMetrics) RequestDuration ¶
func (h *HTTPMetrics) RequestDuration() interface{}
RequestDuration returns the histogram for request duration (for testing).
func (*HTTPMetrics) RequestsTotal ¶
func (h *HTTPMetrics) RequestsTotal() interface{}
RequestsTotal returns the counter for total HTTP requests (for testing).
type HistogramBucketsConfig ¶
type HistogramBucketsConfig struct {
// HTTPDuration buckets for HTTP request duration in seconds
HTTPDuration []float64
// HTTPSize buckets for HTTP request/response size in bytes
HTTPSize []float64
// DBDuration buckets for database query duration in seconds
DBDuration []float64
// WorkflowDuration buckets for workflow execution duration in seconds
WorkflowDuration []float64
// IntegrationDuration buckets for external API call duration in seconds
IntegrationDuration []float64
}
HistogramBucketsConfig holds custom bucket configurations for different metric types.
func DefaultHistogramBuckets ¶
func DefaultHistogramBuckets() HistogramBucketsConfig
DefaultHistogramBuckets returns the default histogram bucket configurations.
type IntegrationCallTimer ¶
type IntegrationCallTimer struct {
// contains filtered or unexported fields
}
IntegrationCallTimer provides a convenient way to time external API calls.
func (*IntegrationCallTimer) Done ¶
func (t *IntegrationCallTimer) Done(statusCode int)
Done records the call duration and status.
func (*IntegrationCallTimer) Error ¶
func (t *IntegrationCallTimer) Error(errorType string)
Error records a failed call with error classification.
func (*IntegrationCallTimer) Retry ¶
func (t *IntegrationCallTimer) Retry()
Retry records a retry attempt and resets the timer.
func (*IntegrationCallTimer) RetryCount ¶
func (t *IntegrationCallTimer) RetryCount() int
RetryCount returns the number of retry attempts made.
func (*IntegrationCallTimer) Success ¶
func (t *IntegrationCallTimer) Success()
Success records a successful call.
type IntegrationMetrics ¶
type IntegrationMetrics struct {
// contains filtered or unexported fields
}
IntegrationMetrics provides methods to record external integration metrics.
func (*IntegrationMetrics) CallsTotal ¶
func (i *IntegrationMetrics) CallsTotal() interface{}
CallsTotal returns the counter for total integration calls (for testing).
func (*IntegrationMetrics) CircuitState ¶
func (i *IntegrationMetrics) CircuitState() interface{}
CircuitState returns the gauge for circuit breaker state (for testing).
func (*IntegrationMetrics) NewCallTimer ¶
func (i *IntegrationMetrics) NewCallTimer(serviceName, endpoint string) *IntegrationCallTimer
NewCallTimer creates a new integration call timer.
func (*IntegrationMetrics) RecordCall ¶
func (i *IntegrationMetrics) RecordCall(serviceName, endpoint string, statusCode int, duration time.Duration)
RecordCall records metrics for an external API call.
func (*IntegrationMetrics) RecordCallWithStatus ¶
func (i *IntegrationMetrics) RecordCallWithStatus(serviceName, endpoint string, success bool, duration time.Duration)
RecordCallWithStatus is a convenience method that accepts a boolean for success/failure.
func (*IntegrationMetrics) RecordError ¶
func (i *IntegrationMetrics) RecordError(serviceName, endpoint, errorType string)
RecordError records an integration error.
func (*IntegrationMetrics) RecordRetry ¶
func (i *IntegrationMetrics) RecordRetry(serviceName, endpoint string)
RecordRetry records a retry attempt.
func (*IntegrationMetrics) SetCircuitBreakerState ¶
func (i *IntegrationMetrics) SetCircuitBreakerState(serviceName string, state CircuitBreakerState)
SetCircuitBreakerState sets the circuit breaker state for a service.
type MiddlewareOptions ¶
type MiddlewareOptions struct {
// PathNormalizer customizes how paths are normalized for metrics grouping.
// If nil, the default normalizer is used.
PathNormalizer func(string) string
// SkipPaths contains paths that should not be recorded in metrics.
SkipPaths []string
// MaxPathCardinality limits the number of unique paths tracked.
// Paths beyond this limit will be recorded as "/other".
// 0 means unlimited (default).
MaxPathCardinality int
}
MiddlewareOptions configures the HTTP metrics middleware.
type Operation ¶
type Operation string
Operation represents a database operation type.
func DetectOperation ¶
DetectOperation parses a SQL query to determine its operation type.
type QueryStatus ¶
type QueryStatus string
QueryStatus represents the result status of a database query.
const ( QueryStatusSuccess QueryStatus = "success" QueryStatusError QueryStatus = "error" )
type QueryTimer ¶
type QueryTimer struct {
// contains filtered or unexported fields
}
QueryTimer provides a convenient way to time database queries.
func (*QueryTimer) Done ¶
func (qt *QueryTimer) Done(err error)
Done records the query duration and any error.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages all Prometheus metrics for CodeAI.
func Global ¶
func Global() *Registry
Global returns the global registry instance, initializing it with default config if needed.
func NewRegistry ¶
NewRegistry creates a new metrics registry with the given configuration.
func (*Registry) HTTP ¶
func (r *Registry) HTTP() *HTTPMetrics
HTTP returns the HTTP metrics interface for the registry.
func (*Registry) HandlerWithAuth ¶
HandlerWithAuth returns an HTTP handler for the Prometheus metrics endpoint that requires authentication via the provided auth function.
func (*Registry) Integration ¶
func (r *Registry) Integration() *IntegrationMetrics
Integration returns the integration metrics interface for the registry.
func (*Registry) PrometheusRegistry ¶
func (r *Registry) PrometheusRegistry() *prometheus.Registry
PrometheusRegistry returns the underlying Prometheus registry.
func (*Registry) RegisterMetricsRoute ¶
func (r *Registry) RegisterMetricsRoute(mux interface { Handle(pattern string, handler http.Handler) })
RegisterMetricsRoute registers the /metrics endpoint on a Chi router. Example usage:
r := chi.NewRouter() registry := metrics.NewRegistry(metrics.DefaultConfig()) registry.RegisterMetricsRoute(r)
func (*Registry) ServeHTTP ¶
func (r *Registry) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements http.Handler for the Registry.
func (*Registry) Workflow ¶
func (r *Registry) Workflow() *WorkflowMetrics
Workflow returns the workflow metrics interface for the registry.
type WorkflowExecutionTimer ¶
type WorkflowExecutionTimer struct {
// contains filtered or unexported fields
}
WorkflowExecutionTimer provides a convenient way to time workflow executions.
func (*WorkflowExecutionTimer) Cancelled ¶
func (t *WorkflowExecutionTimer) Cancelled()
Cancelled records the workflow execution as cancelled.
func (*WorkflowExecutionTimer) Done ¶
func (t *WorkflowExecutionTimer) Done(status WorkflowStatus)
Done records the workflow execution duration and status.
func (*WorkflowExecutionTimer) Failure ¶
func (t *WorkflowExecutionTimer) Failure()
Failure records the workflow execution as failed.
func (*WorkflowExecutionTimer) Success ¶
func (t *WorkflowExecutionTimer) Success()
Success records the workflow execution as successful.
func (*WorkflowExecutionTimer) Timeout ¶
func (t *WorkflowExecutionTimer) Timeout()
Timeout records the workflow execution as timed out.
type WorkflowMetrics ¶
type WorkflowMetrics struct {
// contains filtered or unexported fields
}
WorkflowMetrics provides methods to record workflow-related metrics.
func (*WorkflowMetrics) ActiveCount ¶
func (w *WorkflowMetrics) ActiveCount() interface{}
ActiveCount returns the gauge for active workflow count (for testing).
func (*WorkflowMetrics) DecActiveWorkflows ¶
func (w *WorkflowMetrics) DecActiveWorkflows(workflowName string)
DecActiveWorkflows decrements the active workflow count.
func (*WorkflowMetrics) ExecutionsTotal ¶
func (w *WorkflowMetrics) ExecutionsTotal() interface{}
ExecutionsTotal returns the counter for total workflow executions (for testing).
func (*WorkflowMetrics) IncActiveWorkflows ¶
func (w *WorkflowMetrics) IncActiveWorkflows(workflowName string)
IncActiveWorkflows increments the active workflow count.
func (*WorkflowMetrics) NewExecutionTimer ¶
func (w *WorkflowMetrics) NewExecutionTimer(workflowName string) *WorkflowExecutionTimer
NewExecutionTimer creates a new workflow execution timer.
func (*WorkflowMetrics) NewStepTimer ¶
func (w *WorkflowMetrics) NewStepTimer(workflowName, stepName string) *WorkflowStepTimer
NewStepTimer creates a new workflow step timer.
func (*WorkflowMetrics) RecordExecution ¶
func (w *WorkflowMetrics) RecordExecution(workflowName string, status WorkflowStatus, duration time.Duration)
RecordExecution records metrics for a completed workflow execution.
func (*WorkflowMetrics) RecordStep ¶
func (w *WorkflowMetrics) RecordStep(workflowName, stepName string, duration time.Duration)
RecordStep records metrics for a completed workflow step.
func (*WorkflowMetrics) SetActiveWorkflows ¶
func (w *WorkflowMetrics) SetActiveWorkflows(workflowName string, count int)
SetActiveWorkflows sets the active workflow count to a specific value.
type WorkflowStatus ¶
type WorkflowStatus string
WorkflowStatus represents the outcome status of a workflow execution.
const ( WorkflowStatusSuccess WorkflowStatus = "success" WorkflowStatusFailure WorkflowStatus = "failure" WorkflowStatusCancelled WorkflowStatus = "cancelled" WorkflowStatusTimeout WorkflowStatus = "timeout" )
type WorkflowStepTimer ¶
type WorkflowStepTimer struct {
// contains filtered or unexported fields
}
WorkflowStepTimer provides a convenient way to time workflow steps.