Documentation
¶
Overview ¶
Package policy implements the Tero Policy Specification for high-performance telemetry policy evaluation and transformation.
Index ¶
- Constants
- Variables
- func IsCompilation(err error) bool
- func IsEvaluation(err error) bool
- func IsInvalidPolicy(err error) bool
- func IsProvider(err error) bool
- func SimpleLogMatcher(r *SimpleLogRecord, ref LogFieldRef) []byte
- func SimpleLogTransformer(r *SimpleLogRecord, op TransformOp) bool
- func SimpleMetricMatcher(r *SimpleMetricRecord, ref MetricFieldRef) []byte
- func SimpleSpanMatcher(r *SimpleSpanRecord, ref TraceFieldRef) []byte
- func StopAll(providers []LoadedProvider)
- func UnregisterAll(providers []LoadedProvider)
- type AttrScope
- type Config
- type ConfigLoader
- type ContentType
- type ErrorKind
- type EvaluateResult
- func EvaluateLog[T any](e *PolicyEngine, record T, match LogMatchFunc[T], opts ...LogOption[T]) EvaluateResult
- func EvaluateMetric[T any](e *PolicyEngine, metric T, match MetricMatchFunc[T]) EvaluateResult
- func EvaluateTrace[T any](e *PolicyEngine, span T, match TraceMatchFunc[T], opts ...TraceOption[T]) EvaluateResult
- type FieldRef
- type FileProvider
- type FileProviderOption
- type GrpcProvider
- type GrpcProviderConfig
- type GrpcProviderOption
- func WithGrpcDialOptions(opts ...grpc.DialOption) GrpcProviderOption
- func WithGrpcHeaders(headers map[string]string) GrpcProviderOption
- func WithGrpcInsecure() GrpcProviderOption
- func WithGrpcOnError(fn func(error)) GrpcProviderOption
- func WithGrpcOnSync(fn func()) GrpcProviderOption
- func WithGrpcPollInterval(interval time.Duration) GrpcProviderOption
- func WithGrpcServiceMetadata(metadata *ServiceMetadata) GrpcProviderOption
- func WithGrpcTLS(creds credentials.TransportCredentials) GrpcProviderOption
- type Header
- type HttpProvider
- type HttpProviderConfig
- type HttpProviderOption
- func WithContentType(ct ContentType) HttpProviderOption
- func WithHTTPClient(client *http.Client) HttpProviderOption
- func WithHTTPOnError(fn func(error)) HttpProviderOption
- func WithHTTPOnSync(fn func()) HttpProviderOption
- func WithHTTPPollInterval(interval time.Duration) HttpProviderOption
- func WithHeaders(headers map[string]string) HttpProviderOption
- func WithServiceMetadata(metadata *ServiceMetadata) HttpProviderOption
- type Keep
- type KeepAction
- type LoadedProvider
- type LogField
- type LogFieldRef
- type LogMatchFunc
- type LogMatcher
- type LogOption
- type LogSnapshot
- type LogTarget
- type LogTransformFunc
- type MetricField
- type MetricFieldRef
- type MetricMatchFunc
- type MetricSnapshot
- type Policy
- type PolicyCallback
- type PolicyEngine
- type PolicyError
- type PolicyProvider
- type PolicyRegistry
- func (r *PolicyRegistry) CollectStats() []PolicyStatsSnapshot
- func (r *PolicyRegistry) LogSnapshot() *LogSnapshot
- func (r *PolicyRegistry) MetricSnapshot() *MetricSnapshot
- func (r *PolicyRegistry) Register(provider PolicyProvider) (ProviderHandle, error)
- func (r *PolicyRegistry) SetOnRecompile(fn func())
- func (r *PolicyRegistry) Snapshot() *LogSnapshot
- func (r *PolicyRegistry) TraceSnapshot() *TraceSnapshot
- func (r *PolicyRegistry) Unregister(handle ProviderHandle)
- type PolicySnapshot
- func (s *PolicySnapshot[T]) CompiledMatchers() *engine.CompiledMatchers[T]
- func (s *PolicySnapshot[T]) GetPolicy(id string) (*engine.CompiledPolicy[T], bool)
- func (s *PolicySnapshot[T]) GetStats(policyID string) *engine.PolicyStats
- func (s *PolicySnapshot[T]) Iter() iter.Seq2[string, *engine.CompiledPolicy[T]]
- type PolicyStats
- type PolicyStatsSnapshot
- type ProviderConfig
- type ProviderHandle
- type ProviderId
- type ServiceMetadata
- type SimpleLogRecord
- type SimpleMetricRecord
- type SimpleSpanRecord
- type StatsCollector
- type TraceField
- type TraceFieldRef
- type TraceMatchFunc
- type TraceOption
- type TraceSnapshot
- type TraceTransformFunc
- type TransformKind
- type TransformOp
Constants ¶
const ( KeepAll = engine.KeepAll KeepNone = engine.KeepNone KeepSample = engine.KeepSample KeepRatePerSecond = engine.KeepRatePerSecond KeepRatePerMinute = engine.KeepRatePerMinute )
KeepAction constants.
const ( SamplingModeUnspecified = policyv1.SamplingMode_SAMPLING_MODE_UNSPECIFIED SamplingModeHashSeed = policyv1.SamplingMode_SAMPLING_MODE_HASH_SEED SamplingModeProportional = policyv1.SamplingMode_SAMPLING_MODE_PROPORTIONAL SamplingModeEqualizing = policyv1.SamplingMode_SAMPLING_MODE_EQUALIZING )
SamplingMode constants re-exported from proto.
const ( AttrScopeResource = engine.AttrScopeResource AttrScopeScope = engine.AttrScopeScope AttrScopeRecord = engine.AttrScopeRecord AttrScopeEvent = engine.AttrScopeEvent AttrScopeLink = engine.AttrScopeLink )
AttrScope constants.
const ( LogFieldBody = engine.LogFieldBody LogFieldSeverityText = engine.LogFieldSeverityText LogFieldTraceID = engine.LogFieldTraceID LogFieldSpanID = engine.LogFieldSpanID LogFieldEventName = engine.LogFieldEventName LogFieldResourceSchemaURL = engine.LogFieldResourceSchemaURL LogFieldScopeSchemaURL = engine.LogFieldScopeSchemaURL )
LogField constants.
const ( MetricFieldName = engine.MetricFieldName MetricFieldDescription = engine.MetricFieldDescription MetricFieldUnit = engine.MetricFieldUnit MetricFieldResourceSchemaURL = engine.MetricFieldResourceSchemaURL MetricFieldScopeSchemaURL = engine.MetricFieldScopeSchemaURL MetricFieldScopeName = engine.MetricFieldScopeName MetricFieldScopeVersion = engine.MetricFieldScopeVersion MetricFieldType = engine.MetricFieldType MetricFieldAggregationTemporality = engine.MetricFieldAggregationTemporality )
MetricField constants.
const ( TraceFieldName = engine.TraceFieldName TraceFieldTraceID = engine.TraceFieldTraceID TraceFieldSpanID = engine.TraceFieldSpanID TraceFieldParentSpanID = engine.TraceFieldParentSpanID TraceFieldTraceState = engine.TraceFieldTraceState TraceFieldResourceSchemaURL = engine.TraceFieldResourceSchemaURL TraceFieldScopeSchemaURL = engine.TraceFieldScopeSchemaURL TraceFieldScopeName = engine.TraceFieldScopeName TraceFieldScopeVersion = engine.TraceFieldScopeVersion TraceFieldKind = engine.TraceFieldKind TraceFieldStatus = engine.TraceFieldStatus TraceFieldEventName = engine.TraceFieldEventName TraceFieldLinkTraceID = engine.TraceFieldLinkTraceID )
TraceField constants.
const ( TransformRemove = engine.TransformRemove TransformRedact = engine.TransformRedact TransformRename = engine.TransformRename TransformAdd = engine.TransformAdd )
TransformKind constants.
Variables ¶
var DatapointAttr = engine.DatapointAttr
DatapointAttr creates a reference to a datapoint attribute.
var LogAttr = engine.LogAttr
LogAttr creates a reference to a log record attribute.
var LogBody = engine.LogBody
LogBody creates a reference to the log body field.
var LogEventName = engine.LogEventName
LogEventName creates a reference to the log event name field.
var LogResourceAttr = engine.LogResourceAttr
LogResourceAttr creates a reference to a resource attribute on a log record.
var LogResourceSchemaURL = engine.LogResourceSchemaURL
LogResourceSchemaURL creates a reference to the log resource schema URL field.
var LogScopeAttr = engine.LogScopeAttr
LogScopeAttr creates a reference to a scope attribute on a log record.
var LogScopeSchemaURL = engine.LogScopeSchemaURL
LogScopeSchemaURL creates a reference to the log scope schema URL field.
var LogSeverityText = engine.LogSeverityText
LogSeverityText creates a reference to the log severity text field.
var LogSpanID = engine.LogSpanID
LogSpanID creates a reference to the log span ID field.
var LogTraceID = engine.LogTraceID
LogTraceID creates a reference to the log trace ID field.
var MetricAggregationTemporality = engine.MetricAggregationTemporality
MetricAggregationTemporality creates a reference to the aggregation temporality field.
var MetricDescription = engine.MetricDescription
MetricDescription creates a reference to the metric description field.
var MetricName = engine.MetricName
MetricName creates a reference to the metric name field.
var MetricResourceAttr = engine.MetricResourceAttr
MetricResourceAttr creates a reference to a resource attribute on a metric.
var MetricResourceSchemaURL = engine.MetricResourceSchemaURL
MetricResourceSchemaURL creates a reference to the metric resource schema URL field.
var MetricScopeAttr = engine.MetricScopeAttr
MetricScopeAttr creates a reference to a scope attribute on a metric.
var MetricScopeName = engine.MetricScopeName
MetricScopeName creates a reference to the metric scope name field.
var MetricScopeSchemaURL = engine.MetricScopeSchemaURL
MetricScopeSchemaURL creates a reference to the metric scope schema URL field.
var MetricScopeVersion = engine.MetricScopeVersion
MetricScopeVersion creates a reference to the metric scope version field.
var MetricType = engine.MetricType
MetricType creates a reference to the metric type field.
var MetricUnit = engine.MetricUnit
MetricUnit creates a reference to the metric unit field.
var ParseKeep = engine.ParseKeep
ParseKeep parses a keep string into a Keep struct.
var SpanAttr = engine.SpanAttr
SpanAttr creates a reference to a span attribute.
var SpanEventAttr = engine.SpanEventAttr
SpanEventAttr creates a reference to a span event attribute.
var SpanEventName = engine.SpanEventName
SpanEventName creates a reference to span event names.
var SpanKind = engine.SpanKind
SpanKind creates a reference to the span kind field.
var SpanLinkAttr = engine.SpanLinkAttr
SpanLinkAttr creates a reference to a span link attribute.
var SpanLinkTraceID = engine.SpanLinkTraceID
SpanLinkTraceID creates a reference to span link trace IDs.
var SpanName = engine.SpanName
SpanName creates a reference to the span name field.
var SpanParentSpanID = engine.SpanParentSpanID
SpanParentSpanID creates a reference to the parent span ID field.
var SpanSamplingThreshold = engine.SpanSamplingThreshold
SpanSamplingThreshold creates a reference to the sampling threshold virtual field. Used for writing the effective th value back to tracestate after sampling.
var SpanSpanID = engine.SpanSpanID
SpanSpanID creates a reference to the span ID field.
var SpanStatus = engine.SpanStatus
SpanStatus creates a reference to the span status field.
var SpanTraceID = engine.SpanTraceID
SpanTraceID creates a reference to the span trace ID field.
var SpanTraceState = engine.SpanTraceState
SpanTraceState creates a reference to the trace state field.
var TraceResourceAttr = engine.TraceResourceAttr
TraceResourceAttr creates a reference to a resource attribute on a span.
var TraceResourceSchemaURL = engine.TraceResourceSchemaURL
TraceResourceSchemaURL creates a reference to the trace resource schema URL field.
var TraceScopeAttr = engine.TraceScopeAttr
TraceScopeAttr creates a reference to a scope attribute on a span.
var TraceScopeName = engine.TraceScopeName
TraceScopeName creates a reference to the scope name field.
var TraceScopeSchemaURL = engine.TraceScopeSchemaURL
TraceScopeSchemaURL creates a reference to the scope schema URL field.
var TraceScopeVersion = engine.TraceScopeVersion
TraceScopeVersion creates a reference to the scope version field.
Functions ¶
func IsCompilation ¶
IsCompilation returns true if the error is a compilation error.
func IsEvaluation ¶
IsEvaluation returns true if the error is an evaluation error.
func IsInvalidPolicy ¶
IsInvalidPolicy returns true if the error is an invalid policy error.
func IsProvider ¶
IsProvider returns true if the error is a provider error.
func SimpleLogMatcher ¶ added in v1.2.0
func SimpleLogMatcher(r *SimpleLogRecord, ref LogFieldRef) []byte
SimpleLogMatcher is a LogMatchFunc implementation for SimpleLogRecord.
func SimpleLogTransformer ¶ added in v1.3.0
func SimpleLogTransformer(r *SimpleLogRecord, op TransformOp) bool
SimpleLogTransformer is a LogTransformFunc implementation for SimpleLogRecord. It applies transform operations by mutating the record in place. Returns true if the targeted field was present (hit), false if absent (miss).
func SimpleMetricMatcher ¶ added in v1.2.0
func SimpleMetricMatcher(r *SimpleMetricRecord, ref MetricFieldRef) []byte
SimpleMetricMatcher is a MetricMatchFunc implementation for SimpleMetricRecord.
func SimpleSpanMatcher ¶ added in v1.2.0
func SimpleSpanMatcher(r *SimpleSpanRecord, ref TraceFieldRef) []byte
SimpleSpanMatcher is a TraceMatchFunc implementation for SimpleSpanRecord.
func StopAll ¶
func StopAll(providers []LoadedProvider)
StopAll stops all providers that support stopping.
func UnregisterAll ¶
func UnregisterAll(providers []LoadedProvider)
UnregisterAll unregisters all providers.
Types ¶
type Config ¶
type Config struct {
Providers []ProviderConfig `json:"policy_providers" mapstructure:"policy_providers"`
}
Config represents the root configuration for policy providers.
func LoadConfig ¶
LoadConfig loads a configuration from a JSON file.
func ParseConfig ¶
ParseConfig parses a configuration from JSON bytes.
type ConfigLoader ¶
type ConfigLoader struct {
// contains filtered or unexported fields
}
ConfigLoader creates providers from a configuration.
func NewConfigLoader ¶
func NewConfigLoader(registry *PolicyRegistry) *ConfigLoader
NewConfigLoader creates a new ConfigLoader.
func (*ConfigLoader) Load ¶
func (l *ConfigLoader) Load(config *Config) ([]LoadedProvider, error)
Load creates and registers providers from the configuration. Returns the loaded providers in the order they appear in the config.
func (*ConfigLoader) WithOnError ¶
func (l *ConfigLoader) WithOnError(fn func(error)) *ConfigLoader
WithOnError sets a callback for provider errors. This callback is passed to providers that support it.
type ContentType ¶
type ContentType int
ContentType specifies the encoding format for HTTP requests.
const ( // ContentTypeProtobuf uses protobuf encoding (default, more efficient). ContentTypeProtobuf ContentType = iota // ContentTypeJSON uses JSON encoding (useful for debugging). ContentTypeJSON )
func (ContentType) String ¶
func (c ContentType) String() string
String returns the MIME type for the content type.
type EvaluateResult ¶
type EvaluateResult int
EvaluateResult represents the result of policy evaluation.
const ( // ResultNoMatch indicates no policy matched the telemetry. ResultNoMatch EvaluateResult = iota // ResultKeep indicates the telemetry should be kept. ResultKeep // ResultKeepWithTransform indicates the telemetry should be kept and transformed. ResultKeepWithTransform // ResultDrop indicates the telemetry should be dropped. ResultDrop // ResultSample indicates the telemetry was sampled (kept or dropped based on percentage). ResultSample // ResultRateLimit indicates the telemetry was rate limited. ResultRateLimit )
func EvaluateLog ¶ added in v1.2.0
func EvaluateLog[T any](e *PolicyEngine, record T, match LogMatchFunc[T], opts ...LogOption[T]) EvaluateResult
EvaluateLog checks a log record against the current policies and returns the result. This method uses index-based arrays instead of maps for better performance.
The match function is called to extract field values from the record. Optional behaviors can be provided via LogOption functions (e.g., WithLogTransform).
func EvaluateMetric ¶ added in v1.2.0
func EvaluateMetric[T any](e *PolicyEngine, metric T, match MetricMatchFunc[T]) EvaluateResult
EvaluateMetric checks a metric against the current policies and returns the result. This method uses index-based arrays instead of maps for better performance.
The match function is called to extract field values from the metric. Consumers provide this function to bridge their metric type to the policy engine.
func EvaluateTrace ¶ added in v1.2.0
func EvaluateTrace[T any](e *PolicyEngine, span T, match TraceMatchFunc[T], opts ...TraceOption[T]) EvaluateResult
EvaluateTrace checks a span against the current policies and returns the result. This method uses index-based arrays instead of maps for better performance.
The match function is called to extract field values from the span. Consumers provide this function to bridge their span type to the policy engine.
Optional TraceOption parameters can be provided to enable threshold write-back after sampling decisions. Use WithTraceTransform to receive the effective threshold.
func (EvaluateResult) String ¶
func (r EvaluateResult) String() string
type FieldRef ¶ added in v1.2.0
FieldRef represents a reference to a field or attribute. Use the constructor functions to create references.
type FileProvider ¶
type FileProvider struct {
// contains filtered or unexported fields
}
FileProvider loads policies from a JSON file. It implements the PolicyProvider interface.
func NewFileProvider ¶
func NewFileProvider(path string, opts ...FileProviderOption) *FileProvider
NewFileProvider creates a new FileProvider that reads from the given path.
func (*FileProvider) Load ¶
func (f *FileProvider) Load() ([]*policyv1.Policy, error)
Load reads and parses policies from the file.
func (*FileProvider) SetStatsCollector ¶
func (f *FileProvider) SetStatsCollector(collector StatsCollector)
SetStatsCollector registers a stats collector function.
func (*FileProvider) Stop ¶
func (f *FileProvider) Stop()
Stop stops the file watcher if it is running.
func (*FileProvider) Subscribe ¶
func (f *FileProvider) Subscribe(callback PolicyCallback) error
Subscribe registers a callback for policy changes. If a poll interval is configured, the provider will start watching for file changes.
type FileProviderOption ¶
type FileProviderOption func(*FileProvider)
FileProviderOption configures a FileProvider.
func WithOnError ¶
func WithOnError(fn func(error)) FileProviderOption
WithOnError sets a callback that is invoked when an error occurs during polling. This is useful for logging or monitoring reload failures.
func WithOnReload ¶
func WithOnReload(fn func()) FileProviderOption
WithOnReload sets a callback that is invoked after a successful reload. This is useful for logging or monitoring successful reloads.
func WithPollInterval ¶
func WithPollInterval(interval time.Duration) FileProviderOption
WithPollInterval sets the polling interval for file changes. When set, the provider will periodically check if the file has been modified and reload policies if changes are detected. Default is 0, which disables polling.
type GrpcProvider ¶
type GrpcProvider struct {
// contains filtered or unexported fields
}
GrpcProvider loads policies from a gRPC endpoint using the PolicyService.Sync RPC.
func NewGrpcProvider ¶
func NewGrpcProvider(target string, opts ...GrpcProviderOption) *GrpcProvider
NewGrpcProvider creates a new gRPC policy provider.
func (*GrpcProvider) Load ¶
func (p *GrpcProvider) Load() ([]*policyv1.Policy, error)
Load performs an immediate sync and returns the current policies.
func (*GrpcProvider) SetStatsCollector ¶
func (p *GrpcProvider) SetStatsCollector(collector StatsCollector)
SetStatsCollector registers a stats collector for sync requests.
func (*GrpcProvider) Stop ¶
func (p *GrpcProvider) Stop()
Stop stops the polling loop and closes the connection.
func (*GrpcProvider) Subscribe ¶
func (p *GrpcProvider) Subscribe(callback PolicyCallback) error
Subscribe registers a callback for policy changes and starts polling.
type GrpcProviderConfig ¶
type GrpcProviderConfig struct {
// Target is the gRPC server address (required).
// Format: "host:port" or "dns:///host:port"
Target string
// Headers are additional gRPC metadata headers to include in requests.
Headers map[string]string
// PollInterval is how often to check for policy updates.
// Default is 60 seconds.
PollInterval time.Duration
// ServiceMetadata identifies this client to the policy server.
ServiceMetadata *ServiceMetadata
// DialOptions are additional gRPC dial options.
DialOptions []grpc.DialOption
// UseTLS enables TLS for the connection.
// If false, insecure credentials are used.
UseTLS bool
// TLSCredentials are custom TLS credentials.
// If nil and UseTLS is true, system credentials are used.
TLSCredentials credentials.TransportCredentials
// OnError is called when a sync error occurs.
OnError func(error)
// OnSync is called after a successful sync.
OnSync func()
}
GrpcProviderConfig configures a gRPC policy provider.
type GrpcProviderOption ¶
type GrpcProviderOption func(*GrpcProviderConfig)
GrpcProviderOption configures a GrpcProvider.
func WithGrpcDialOptions ¶
func WithGrpcDialOptions(opts ...grpc.DialOption) GrpcProviderOption
WithGrpcDialOptions sets additional gRPC dial options.
func WithGrpcHeaders ¶
func WithGrpcHeaders(headers map[string]string) GrpcProviderOption
WithGrpcHeaders sets additional gRPC metadata headers.
func WithGrpcInsecure ¶
func WithGrpcInsecure() GrpcProviderOption
WithGrpcInsecure disables TLS (for testing or internal networks).
func WithGrpcOnError ¶
func WithGrpcOnError(fn func(error)) GrpcProviderOption
WithGrpcOnError sets an error callback.
func WithGrpcOnSync ¶
func WithGrpcOnSync(fn func()) GrpcProviderOption
WithGrpcOnSync sets a sync success callback.
func WithGrpcPollInterval ¶
func WithGrpcPollInterval(interval time.Duration) GrpcProviderOption
WithGrpcPollInterval sets the polling interval.
func WithGrpcServiceMetadata ¶
func WithGrpcServiceMetadata(metadata *ServiceMetadata) GrpcProviderOption
WithGrpcServiceMetadata sets the client metadata for sync requests.
func WithGrpcTLS ¶
func WithGrpcTLS(creds credentials.TransportCredentials) GrpcProviderOption
WithGrpcTLS enables TLS for the connection.
type Header ¶
type Header struct {
Name string `json:"name" mapstructure:"name"`
Value string `json:"value" mapstructure:"value"`
}
Header represents an HTTP header for provider configuration.
type HttpProvider ¶
type HttpProvider struct {
// contains filtered or unexported fields
}
HttpProvider loads policies from an HTTP endpoint using the sync protocol.
func NewHttpProvider ¶
func NewHttpProvider(url string, opts ...HttpProviderOption) *HttpProvider
NewHttpProvider creates a new HTTP policy provider.
func (*HttpProvider) Load ¶
func (p *HttpProvider) Load() ([]*policyv1.Policy, error)
Load performs an immediate sync and returns the current policies.
func (*HttpProvider) SetStatsCollector ¶
func (p *HttpProvider) SetStatsCollector(collector StatsCollector)
SetStatsCollector registers a stats collector for sync requests.
func (*HttpProvider) Subscribe ¶
func (p *HttpProvider) Subscribe(callback PolicyCallback) error
Subscribe registers a callback for policy changes and starts polling.
type HttpProviderConfig ¶
type HttpProviderConfig struct {
// URL is the endpoint to poll for policy updates (required).
URL string
// Headers are additional HTTP headers to include in requests.
Headers map[string]string
// PollInterval is how often to check for policy updates.
// Default is 60 seconds.
PollInterval time.Duration
// ServiceMetadata identifies this client to the policy server.
ServiceMetadata *ServiceMetadata
// ContentType specifies the encoding format (protobuf or JSON).
// Default is protobuf.
ContentType ContentType
// HTTPClient allows providing a custom HTTP client.
// If nil, http.DefaultClient is used.
HTTPClient *http.Client
// OnError is called when a sync error occurs.
OnError func(error)
// OnSync is called after a successful sync.
OnSync func()
}
HttpProviderConfig configures an HTTP policy provider.
type HttpProviderOption ¶
type HttpProviderOption func(*HttpProviderConfig)
HttpProviderOption configures an HttpProvider.
func WithContentType ¶
func WithContentType(ct ContentType) HttpProviderOption
WithContentType sets the content type for requests.
func WithHTTPClient ¶
func WithHTTPClient(client *http.Client) HttpProviderOption
WithHTTPClient sets a custom HTTP client.
func WithHTTPOnError ¶
func WithHTTPOnError(fn func(error)) HttpProviderOption
WithHTTPOnError sets an error callback.
func WithHTTPOnSync ¶
func WithHTTPOnSync(fn func()) HttpProviderOption
WithHTTPOnSync sets a sync success callback.
func WithHTTPPollInterval ¶
func WithHTTPPollInterval(interval time.Duration) HttpProviderOption
WithHTTPPollInterval sets the polling interval.
func WithHeaders ¶
func WithHeaders(headers map[string]string) HttpProviderOption
WithHeaders sets additional HTTP headers.
func WithServiceMetadata ¶
func WithServiceMetadata(metadata *ServiceMetadata) HttpProviderOption
WithServiceMetadata sets the client metadata for sync requests.
type LoadedProvider ¶
type LoadedProvider struct {
ID string
Handle ProviderHandle
Provider PolicyProvider
}
LoadedProvider holds information about a loaded provider.
type LogFieldRef ¶ added in v1.2.0
type LogFieldRef = engine.LogFieldRef
LogFieldRef is a field reference for log records.
type LogMatchFunc ¶ added in v1.2.0
LogMatchFunc extracts field values from a log record of type T. Consumers implement this function to bridge their record type to the policy engine.
type LogOption ¶ added in v1.3.0
type LogOption[T any] func(*logOptions[T])
LogOption configures optional behavior for EvaluateLog.
func WithLogTransform ¶ added in v1.3.0
func WithLogTransform[T any](fn LogTransformFunc[T]) LogOption[T]
WithLogTransform sets a transform function that is called for each transform operation on the winning policy. The function is called once per TransformOp, in order: removes, redacts, renames, adds.
type LogSnapshot ¶ added in v1.2.0
type LogSnapshot = PolicySnapshot[engine.LogField]
Type aliases for convenience
type LogTransformFunc ¶ added in v1.3.0
type LogTransformFunc[T any] func(record T, op TransformOp) bool
LogTransformFunc applies a single transform operation to a log record of type T. Consumers implement this function to bridge their record type to the policy engine. Returns true if the targeted field was present (hit), false if absent (miss).
type MetricField ¶ added in v1.0.1
type MetricField = engine.MetricField
MetricField represents a metric-specific field.
type MetricFieldRef ¶ added in v1.2.0
type MetricFieldRef = engine.MetricFieldRef
MetricFieldRef is a field reference for metrics.
type MetricMatchFunc ¶ added in v1.2.0
MetricMatchFunc extracts field values from a metric of type T. Consumers implement this function to bridge their record type to the policy engine.
type MetricSnapshot ¶ added in v1.2.0
type MetricSnapshot = PolicySnapshot[engine.MetricField]
type PolicyCallback ¶
PolicyCallback is called when policies are updated by a provider.
type PolicyEngine ¶
type PolicyEngine struct {
// contains filtered or unexported fields
}
PolicyEngine evaluates telemetry against compiled policies.
func NewPolicyEngine ¶
func NewPolicyEngine(registry *PolicyRegistry) *PolicyEngine
NewPolicyEngine creates a new PolicyEngine with the given registry.
type PolicyError ¶
PolicyError represents an error in policy operations.
func NewError ¶
func NewError(kind ErrorKind, message string) *PolicyError
NewError creates a new PolicyError.
func WrapError ¶
func WrapError(kind ErrorKind, message string, cause error) *PolicyError
WrapError creates a new PolicyError wrapping an existing error.
func (*PolicyError) Error ¶
func (e *PolicyError) Error() string
func (*PolicyError) Unwrap ¶
func (e *PolicyError) Unwrap() error
type PolicyProvider ¶
type PolicyProvider interface {
// Load performs an immediate load and returns the current policies.
Load() ([]*policyv1.Policy, error)
// Subscribe registers a callback for policy changes.
// The callback is invoked immediately with current policies,
// and again whenever policies change.
Subscribe(callback PolicyCallback) error
// SetStatsCollector registers a function to collect stats for reporting.
// Providers can use this to include stats in sync requests to backends.
SetStatsCollector(collector StatsCollector)
}
PolicyProvider is the interface for policy sources. Providers load policies and notify the registry of changes.
type PolicyRegistry ¶
type PolicyRegistry struct {
// contains filtered or unexported fields
}
PolicyRegistry manages policies from multiple providers. It recompiles the Hyperscan database when policies change and produces read-only snapshots for evaluation.
func NewPolicyRegistry ¶
func NewPolicyRegistry() *PolicyRegistry
NewPolicyRegistry creates a new PolicyRegistry.
func (*PolicyRegistry) CollectStats ¶
func (r *PolicyRegistry) CollectStats() []PolicyStatsSnapshot
CollectStats atomically reads and resets stats for all policies, returning snapshots of the delta since the last call. This is the StatsCollector implementation that gets registered with providers.
func (*PolicyRegistry) LogSnapshot ¶ added in v1.2.0
func (r *PolicyRegistry) LogSnapshot() *LogSnapshot
LogSnapshot returns the current read-only snapshot of compiled log policies. The snapshot is safe for concurrent use and remains valid even after new policies are loaded (the registry maintains the old snapshot until all references are released via garbage collection).
func (*PolicyRegistry) MetricSnapshot ¶ added in v1.2.0
func (r *PolicyRegistry) MetricSnapshot() *MetricSnapshot
MetricSnapshot returns the current read-only snapshot of compiled metric policies. The snapshot is safe for concurrent use and remains valid even after new policies are loaded (the registry maintains the old snapshot until all references are released via garbage collection).
func (*PolicyRegistry) Register ¶
func (r *PolicyRegistry) Register(provider PolicyProvider) (ProviderHandle, error)
Register adds a provider to the registry. The provider's policies are loaded immediately and the registry is recompiled.
func (*PolicyRegistry) SetOnRecompile ¶
func (r *PolicyRegistry) SetOnRecompile(fn func())
SetOnRecompile sets a callback that is invoked after recompilation. Used for testing to know when policies have been updated.
func (*PolicyRegistry) Snapshot ¶
func (r *PolicyRegistry) Snapshot() *LogSnapshot
Snapshot returns the current read-only snapshot of compiled log policies. Deprecated: Use LogSnapshot instead.
func (*PolicyRegistry) TraceSnapshot ¶ added in v1.2.0
func (r *PolicyRegistry) TraceSnapshot() *TraceSnapshot
TraceSnapshot returns the current read-only snapshot of compiled trace policies. The snapshot is safe for concurrent use and remains valid even after new policies are loaded (the registry maintains the old snapshot until all references are released via garbage collection).
func (*PolicyRegistry) Unregister ¶
func (r *PolicyRegistry) Unregister(handle ProviderHandle)
Unregister removes a provider from the registry.
type PolicySnapshot ¶
PolicySnapshot is an immutable, read-only view of compiled policies for a single telemetry type. It is safe for concurrent use across multiple goroutines. Snapshots are managed by the PolicyRegistry - when policies are reloaded, old snapshots remain valid until garbage collected.
func (*PolicySnapshot[T]) CompiledMatchers ¶
func (s *PolicySnapshot[T]) CompiledMatchers() *engine.CompiledMatchers[T]
CompiledMatchers returns the compiled matchers for this snapshot.
func (*PolicySnapshot[T]) GetPolicy ¶
func (s *PolicySnapshot[T]) GetPolicy(id string) (*engine.CompiledPolicy[T], bool)
GetPolicy returns a compiled policy by ID.
func (*PolicySnapshot[T]) GetStats ¶
func (s *PolicySnapshot[T]) GetStats(policyID string) *engine.PolicyStats
GetStats returns the stats for a policy, or nil if not found.
func (*PolicySnapshot[T]) Iter ¶
func (s *PolicySnapshot[T]) Iter() iter.Seq2[string, *engine.CompiledPolicy[T]]
Iter returns an iterator over all policies in the snapshot.
type PolicyStatsSnapshot ¶
type PolicyStatsSnapshot = engine.PolicyStatsSnapshot
Re-export types from internal/engine.
type ProviderConfig ¶
type ProviderConfig struct {
Type string `json:"type" mapstructure:"type"`
ID string `json:"id" mapstructure:"id"`
// File provider options
Path string `json:"path,omitempty" mapstructure:"path"`
PollIntervalSecs *int `json:"poll_interval_secs,omitempty" mapstructure:"poll_interval_secs"`
// HTTP provider options (for future use)
URL string `json:"url,omitempty" mapstructure:"url"`
Headers []Header `json:"headers,omitempty" mapstructure:"headers"`
ContentType string `json:"content_type,omitempty" mapstructure:"content_type"`
}
ProviderConfig represents a single provider configuration. The Type field determines which provider to instantiate.
func (*ProviderConfig) PollInterval ¶
func (p *ProviderConfig) PollInterval() time.Duration
PollInterval returns the poll interval as a time.Duration. Returns 0 if not configured.
func (*ProviderConfig) Validate ¶
func (p *ProviderConfig) Validate() error
Validate checks that the provider configuration is valid.
type ProviderHandle ¶
type ProviderHandle struct {
// contains filtered or unexported fields
}
ProviderHandle is returned when registering a provider. Use it to unregister the provider later.
func (*ProviderHandle) Unregister ¶
func (h *ProviderHandle) Unregister()
Unregister removes this provider from the registry.
type ProviderId ¶
type ProviderId uint64
ProviderId is a unique identifier for a registered provider.
type ServiceMetadata ¶
type ServiceMetadata struct {
// ServiceName is the name of the service (required).
ServiceName string
// ServiceNamespace is the namespace the service belongs to (required).
ServiceNamespace string
// ServiceInstanceID is a unique identifier for this service instance (required).
ServiceInstanceID string
// ServiceVersion is the version of the service (required).
ServiceVersion string
// SupportedStages lists which policy stages this client can handle.
SupportedStages []policyv1.PolicyStage
// Labels are additional metadata labels.
Labels map[string]string
// ResourceAttributes are additional resource attributes beyond the required ones.
ResourceAttributes map[string]string
}
ServiceMetadata describes the client's identity for policy sync requests. This is used by HTTP and gRPC providers to identify themselves to the policy server.
func (*ServiceMetadata) ToProto ¶
func (m *ServiceMetadata) ToProto() *policyv1.ClientMetadata
ToProto converts ServiceMetadata to the proto ClientMetadata type.
type SimpleLogRecord ¶
type SimpleLogRecord struct {
Body []byte
SeverityText []byte
TraceID []byte
SpanID []byte
EventName []byte
ResourceSchemaURL []byte
ScopeSchemaURL []byte
LogAttributes map[string]any
ResourceAttributes map[string]any
ScopeAttributes map[string]any
}
SimpleLogRecord is a simple implementation for testing that works with LogMatchFunc. Attribute maps support nested structures via map[string]any values.
type SimpleMetricRecord ¶ added in v1.2.0
type SimpleMetricRecord struct {
Name []byte
Description []byte
Unit []byte
Type []byte // e.g., "gauge", "sum", "histogram"
AggregationTemporality []byte // e.g., "delta", "cumulative"
ScopeName []byte
ScopeVersion []byte
ResourceSchemaURL []byte
ScopeSchemaURL []byte
DatapointAttributes map[string]any
ResourceAttributes map[string]any
ScopeAttributes map[string]any
}
SimpleMetricRecord is a simple implementation for testing that works with MetricMatchFunc. Attribute maps support nested structures via map[string]any values.
type SimpleSpanRecord ¶ added in v1.2.0
type SimpleSpanRecord struct {
Name []byte
TraceID []byte
SpanID []byte
ParentSpanID []byte
TraceState []byte
Kind []byte // e.g., "server", "client", "internal"
Status []byte // e.g., "ok", "error", "unset"
ScopeName []byte
ScopeVersion []byte
ResourceSchemaURL []byte
ScopeSchemaURL []byte
EventNames [][]byte
EventAttributes []map[string]any
LinkTraceIDs [][]byte
LinkAttributes []map[string]any
SpanAttributes map[string]any
ResourceAttributes map[string]any
ScopeAttributes map[string]any
}
SimpleSpanRecord is a simple implementation for testing that works with TraceMatchFunc. Attribute maps support nested structures via map[string]any values.
type StatsCollector ¶
type StatsCollector func() []PolicyStatsSnapshot
StatsCollector is a function that returns current stats for all policies. Registered with providers so they can include stats in sync requests.
type TraceField ¶ added in v1.0.1
type TraceField = engine.TraceField
TraceField represents a trace/span-specific field.
type TraceFieldRef ¶ added in v1.2.0
type TraceFieldRef = engine.TraceFieldRef
TraceFieldRef is a field reference for traces/spans.
type TraceMatchFunc ¶ added in v1.2.0
TraceMatchFunc extracts field values from a span of type T. Consumers implement this function to bridge their record type to the policy engine.
type TraceOption ¶ added in v1.3.10
type TraceOption[T any] func(*traceOptions[T])
TraceOption configures optional behavior for EvaluateTrace.
func WithTraceTransform ¶ added in v1.3.10
func WithTraceTransform[T any](fn TraceTransformFunc[T]) TraceOption[T]
WithTraceTransform sets a transform function that is called after a sampling decision to write the effective threshold back to the span's tracestate.
type TraceSnapshot ¶ added in v1.2.0
type TraceSnapshot = PolicySnapshot[engine.TraceField]
type TraceTransformFunc ¶ added in v1.3.10
TraceTransformFunc writes a sampling threshold value to a span of type T. Called after a sampling decision to write the effective `th` value back to tracestate. The ref identifies the target field (SpanSamplingThreshold) and value is the encoded hex threshold string.
type TransformKind ¶ added in v1.3.0
type TransformKind = engine.TransformKind
TransformKind identifies the type of transform operation.
type TransformOp ¶ added in v1.3.0
type TransformOp = engine.TransformOp
TransformOp is a single compiled transform operation.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
http
command
|
|
|
internal
|
|
|
engine
Package engine contains the policy evaluation engine implementation.
|
Package engine contains the policy evaluation engine implementation. |
|
jsonpolicy
Package jsonpolicy handles JSON parsing of policy files.
|
Package jsonpolicy handles JSON parsing of policy files. |
|
proto
|
|