metrics

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package metrics provides Prometheus metrics collection for the CodeAI application.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClassifyError

func ClassifyError(err error) string

ClassifyError classifies an error into a type for metrics.

func ClassifyHTTPError

func ClassifyHTTPError(statusCode int) string

ClassifyHTTPError classifies an HTTP status code into an error type.

func DefaultPathNormalizer

func DefaultPathNormalizer(path string) string

DefaultPathNormalizer normalizes paths by replacing dynamic segments with placeholders.

func HTTPMiddleware

func HTTPMiddleware(registry *Registry) func(http.Handler) http.Handler

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.

func Handler

func Handler() http.Handler

Handler returns the global registry's HTTP handler.

func SetGlobal

func SetGlobal(r *Registry)

SetGlobal sets the global registry instance.

func StartQueryContext

func StartQueryContext(ctx context.Context, operation Operation, table string) context.Context

StartQueryContext adds query timing information to the context.

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

func (c Config) WithEnvironment(env string) Config

WithEnvironment sets the environment label.

func (Config) WithInstance

func (c Config) WithInstance(instance string) Config

WithInstance sets the instance label.

func (Config) WithVersion

func (c Config) WithVersion(version string) Config

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

func (d *DBMetrics) EndQueryContext(ctx context.Context, err error)

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

func (d *DBMetrics) RecordQueryError(operation Operation, table string, errorType string)

RecordQueryError records a query error with error type classification.

func (*DBMetrics) StartConnectionStatsCollector

func (d *DBMetrics) StartConnectionStatsCollector(db *sql.DB, interval time.Duration) func()

StartConnectionStatsCollector starts a goroutine that periodically updates connection stats from a sql.DB instance.

func (*DBMetrics) UpdateConnectionStats

func (d *DBMetrics) UpdateConnectionStats(active, idle, max int)

UpdateConnectionStats updates database connection pool metrics.

func (*DBMetrics) UpdateFromDBStats

func (d *DBMetrics) UpdateFromDBStats(stats sql.DBStats)

UpdateFromDBStats updates metrics from sql.DBStats.

type DBQueryContext

type DBQueryContext struct {
	StartTime time.Time
	Operation Operation
	Table     string
}

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.

const (
	OperationSelect Operation = "SELECT"
	OperationInsert Operation = "INSERT"
	OperationUpdate Operation = "UPDATE"
	OperationDelete Operation = "DELETE"
	OperationOther  Operation = "OTHER"
)

func DetectOperation

func DetectOperation(query string) Operation

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

func NewRegistry(config Config) *Registry

NewRegistry creates a new metrics registry with the given configuration.

func (*Registry) Config

func (r *Registry) Config() Config

Config returns the registry configuration.

func (*Registry) DB

func (r *Registry) DB() *DBMetrics

DB returns the database metrics interface for the registry.

func (*Registry) HTTP

func (r *Registry) HTTP() *HTTPMetrics

HTTP returns the HTTP metrics interface for the registry.

func (*Registry) Handler

func (r *Registry) Handler() http.Handler

Handler returns an HTTP handler for the Prometheus metrics endpoint.

func (*Registry) HandlerWithAuth

func (r *Registry) HandlerWithAuth(authFn func(r *http.Request) bool) http.Handler

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.

func (*WorkflowStepTimer) Done

func (t *WorkflowStepTimer) Done()

Done records the step duration.

Jump to

Keyboard shortcuts

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