Files
releases/v1/plugins/server/metrics/config.go
T
Sebastian Spaink 40dd2b90d2 config: migrate server.encoding and server.decoding validation to Rego (#8903)
Follow-up to #8900. Moves the gzip encoding and decoding config
validation off the Go `validateAndInjectDefaults` methods and onto
embedded Rego policies, injecting defaults and reporting value errors.
Each config registers its recognized options via
`config.RegisterConfigSpec` so unknown-option warnings live with the
owning struct. Field type validation stays in the Go decode step.

---------

Signed-off-by: Sebastian Spaink <sebastianspaink@gmail.com>
2026-08-04 11:05:36 -05:00

82 lines
2.1 KiB
Go

package metrics
import (
"context"
_ "embed"
"github.com/open-policy-agent/opa/internal/configpolicy"
"github.com/open-policy-agent/opa/v1/config"
)
var defaultHTTPRequestBuckets = []float64{
1e-6, // 1 microsecond
5e-6,
1e-5,
5e-5,
1e-4,
5e-4,
1e-3, // 1 millisecond
0.01,
0.1,
1, // 1 second
}
//go:embed validate.rego
var validationModule string
var validationPolicy = configpolicy.New(
"opa/config/server/metrics/validate.rego",
validationModule,
"data.opa.config.server.metrics = x",
)
func init() {
config.RegisterConfigSpec(config.SpecsFromStruct[Config]("server", "metrics")...)
}
// Config represents the configuration for the Server.Metrics settings
type Config struct {
Prom *Prom `json:"prom,omitempty"`
}
// Prom represents the configuration for the Server.Metrics.Prom settings
type Prom struct {
HTTPRequestDurationSeconds *HTTPRequestDurationSeconds `json:"http_request_duration_seconds,omitempty"`
}
// HTTPRequestDurationSeconds represents the configuration for the Server.Metrics.Prom.HTTPRequestDurationSeconds settings
type HTTPRequestDurationSeconds struct {
Buckets []float64 `json:"buckets,omitempty"` // the float64 array of buckets representing seconds or division of a second
}
// ConfigBuilder assists in the construction of the plugin configuration.
type ConfigBuilder struct {
raw []byte
}
// NewConfigBuilder returns a new ConfigBuilder to build and parse the server config
func NewConfigBuilder() *ConfigBuilder {
return &ConfigBuilder{}
}
// WithBytes sets the raw server config
func (b *ConfigBuilder) WithBytes(config []byte) *ConfigBuilder {
b.raw = config
return b
}
// Parse returns a valid Config object with defaults injected.
func (b *ConfigBuilder) Parse() (*Config, error) {
return b.ParseWithContext(context.Background())
}
// ParseWithContext returns a valid Config object with defaults injected, using
// ctx to evaluate the validation policy.
func (b *ConfigBuilder) ParseWithContext(ctx context.Context) (*Config, error) {
var result Config
if _, err := configpolicy.EvalConfigInto(ctx, validationPolicy, b.raw, &result); err != nil {
return nil, err
}
return &result, nil
}