policy

package module
v1.3.10 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

README

policy-go

A high-performance policy evaluation library for OpenTelemetry telemetry data in Go. Built with Hyperscan for fast regex matching and designed for hot-reload support.

Features

  • High-Performance Matching: Uses Intel Hyperscan for vectorized regex evaluation
  • Multi-Telemetry Support: Evaluate logs, metrics, and traces with type-safe APIs
  • Hot Reload: File-based policy providers support automatic reloading on change
  • Thread-Safe: Immutable snapshots for concurrent evaluation
  • Extensible: Provider interface for custom policy sources (file, HTTP, gRPC)
  • Statistics: Per-policy hit/drop/sample counters with atomic operations
  • Rate Limiting: Lock-free per-policy rate limiting with configurable windows
  • AND Semantics: Multiple matchers in a policy are AND'd together

Installation

go get github.com/usetero/policy-go
Requirements
  • Go 1.21+
  • Hyperscan library (via gohs)

On macOS with Homebrew:

brew install hyperscan

On Ubuntu/Debian:

apt-get install libhyperscan-dev

Quick Start

package main

import (
    "fmt"
    "log"
    "time"

    "github.com/usetero/policy-go"
)

// Define your log record type
type LogRecord struct {
    Body               []byte
    SeverityText       []byte
    TraceID            []byte
    LogAttributes      map[string]any
    ResourceAttributes map[string]any
}

// Implement a match function to extract field values
func matchLog(r *LogRecord, ref policy.LogFieldRef) []byte {
    // Handle field lookups
    if ref.IsField() {
        switch ref.Field {
        case policy.LogFieldBody:
            return r.Body
        case policy.LogFieldSeverityText:
            return r.SeverityText
        case policy.LogFieldTraceID:
            return r.TraceID
        default:
            return nil
        }
    }

    // Handle attribute lookups
    var attrs map[string]any
    switch {
    case ref.IsResourceAttr():
        attrs = r.ResourceAttributes
    case ref.IsRecordAttr():
        attrs = r.LogAttributes
    default:
        return nil
    }
    return traversePath(attrs, ref.AttrPath)
}

func traversePath(m map[string]any, path []string) []byte {
    if len(path) == 0 || m == nil {
        return nil
    }
    val, ok := m[path[0]]
    if !ok {
        return nil
    }
    if len(path) == 1 {
        switch v := val.(type) {
        case string:
            return []byte(v)
        case []byte:
            return v
        }
        return nil
    }
    if nested, ok := val.(map[string]any); ok {
        return traversePath(nested, path[1:])
    }
    return nil
}

func main() {
    // Create a registry
    registry := policy.NewPolicyRegistry()

    // Create a file provider with hot reload
    provider := policy.NewFileProvider("policies.json",
        policy.WithPollInterval(30*time.Second),
        policy.WithOnError(func(err error) {
            log.Printf("Policy error: %v", err)
        }),
    )
    defer provider.Stop()

    // Register the provider
    handle, err := registry.Register(provider)
    if err != nil {
        log.Fatal(err)
    }
    defer handle.Unregister()

    // Create an engine
    engine := policy.NewPolicyEngine(registry)

    // Evaluate a log record
    record := &LogRecord{
        Body:         []byte("debug trace message"),
        SeverityText: []byte("INFO"),
        LogAttributes: map[string]any{
            "http": map[string]any{
                "method": "GET",
            },
        },
    }

    result := policy.EvaluateLog(engine, record, matchLog)
    fmt.Printf("Result: %s\n", result) // "drop" if matched by policy
}

Core Concepts

PolicyRegistry

The registry manages policies from multiple providers. When policies change, it automatically recompiles the Hyperscan database and produces a new immutable snapshot.

registry := policy.NewPolicyRegistry()

// Register providers
handle, _ := registry.Register(fileProvider)
handle, _ := registry.Register(httpProvider)

// Collect stats
stats := registry.CollectStats()
PolicyEngine

The engine evaluates telemetry against compiled policies. It holds a reference to the registry and automatically uses the latest snapshot for each evaluation.

engine := policy.NewPolicyEngine(registry)

// Evaluate logs
result := policy.EvaluateLog(engine, logRecord, matchLogFunc)

// Evaluate metrics
result := policy.EvaluateMetric(engine, metricRecord, matchMetricFunc)

// Evaluate traces/spans
result := policy.EvaluateTrace(engine, spanRecord, matchTraceFunc)

switch result {
case policy.ResultNoMatch:
    // No policy matched - pass through
case policy.ResultKeep:
    // Matched a keep policy (or under rate limit)
case policy.ResultDrop:
    // Matched a drop policy (or over rate limit)
case policy.ResultSample:
    // Sampled (for metrics without sample key)
}
Match Functions

Instead of implementing an interface, you provide a match function that extracts field values from your telemetry types. This allows maximum flexibility in how you represent your data.

// LogMatchFunc extracts values from log records
type LogMatchFunc[T any] func(record T, ref LogFieldRef) []byte

// MetricMatchFunc extracts values from metrics
type MetricMatchFunc[T any] func(record T, ref MetricFieldRef) []byte

// TraceMatchFunc extracts values from spans
type TraceMatchFunc[T any] func(record T, ref TraceFieldRef) []byte

Example match function for logs:

func matchLog(r *MyLogRecord, ref policy.LogFieldRef) []byte {
    // Handle field lookups
    if ref.IsField() {
        switch ref.Field {
        case policy.LogFieldBody:
            return r.Body
        case policy.LogFieldSeverityText:
            return r.SeverityText
        default:
            return nil
        }
    }

    // Handle attribute lookups
    var attrs map[string]any
    switch {
    case ref.IsResourceAttr():
        attrs = r.ResourceAttributes
    case ref.IsRecordAttr():
        attrs = r.LogAttributes
    case ref.IsScopeAttr():
        attrs = r.ScopeAttributes
    default:
        return nil
    }
    return traversePath(attrs, ref.AttrPath)
}
Field References

Field references (LogFieldRef, MetricFieldRef, TraceFieldRef) describe what value to extract. Use helper methods to determine the reference type:

ref.IsField()        // Is this a direct field (body, name, etc.)?
ref.IsResourceAttr() // Is this a resource attribute?
ref.IsRecordAttr()   // Is this a record/span/datapoint attribute?
ref.IsScopeAttr()    // Is this a scope attribute?
ref.IsEventAttr()    // Is this an event attribute? (traces only)
ref.IsLinkAttr()     // Is this a link attribute? (traces only)

ref.Field            // The field enum value
ref.AttrPath         // The attribute path (e.g., ["http", "method"])
Attribute Scopes
  • AttrScopeResource: Resource-level attributes (service.name, etc.)
  • AttrScopeScope: Instrumentation scope attributes
  • AttrScopeRecord: Record-level attributes (log attributes, span attributes, datapoint attributes)
  • AttrScopeEvent: Span event attributes (traces only)
  • AttrScopeLink: Span link attributes (traces only)

Configuration

Config File

Use a JSON configuration file to define providers:

{
  "policy_providers": [
    {
      "type": "file",
      "id": "local-policies",
      "path": "/etc/tero/policies.json",
      "poll_interval_secs": 30
    }
  ]
}
Loading Config
config, err := policy.LoadConfig("config.json")
if err != nil {
    log.Fatal(err)
}

loader := policy.NewConfigLoader(registry).
    WithOnError(func(err error) {
        log.Printf("Provider error: %v", err)
    })

providers, err := loader.Load(config)
if err != nil {
    log.Fatal(err)
}
defer policy.StopAll(providers)
defer policy.UnregisterAll(providers)

Policy Format

Policies are defined in JSON format following the Tero Policy Specification:

Log Policies
{
  "policies": [
    {
      "id": "drop-debug-logs",
      "name": "Drop debug logs containing trace",
      "log": {
        "match": [
          { "log_field": "body", "regex": "debug" },
          { "log_field": "body", "regex": "trace" }
        ],
        "keep": "none"
      }
    },
    {
      "id": "drop-nginx-logs",
      "name": "Drop nginx access logs",
      "log": {
        "match": [{ "log_attribute": "ddsource", "exact": "nginx" }],
        "keep": "none"
      }
    }
  ]
}
Metric Policies
{
  "policies": [
    {
      "id": "drop-internal-metrics",
      "name": "Drop internal metrics",
      "metric": {
        "match": [{ "metric_field": "name", "starts_with": "internal." }],
        "keep": false
      }
    },
    {
      "id": "drop-histogram-metrics",
      "name": "Drop histogram type metrics",
      "metric": {
        "match": [{ "metric_field": "type", "exact": "histogram" }],
        "keep": false
      }
    }
  ]
}
Trace Policies
{
  "policies": [
    {
      "id": "sample-traces",
      "name": "Sample 10% of traces",
      "trace": {
        "match": [{ "span_field": "kind", "exact": "server" }],
        "keep": { "percentage": 10 }
      }
    },
    {
      "id": "drop-health-checks",
      "name": "Drop health check spans",
      "trace": {
        "match": [{ "span_field": "name", "exact": "/health" }],
        "keep": { "percentage": 0 }
      }
    }
  ]
}

Trace sampling uses OTel-compliant consistent probability sampling. The same trace ID always produces the same sampling decision, ensuring all spans in a trace are kept or dropped together.

Matcher Types
Log Matchers
Field Description
log_field Match on log fields: body, severity_text, trace_id, etc.
log_attribute Match on log record attributes
resource_attribute Match on resource attributes
scope_attribute Match on scope attributes
Metric Matchers
Field Description
metric_field Match on metric fields: name, type, unit, etc.
datapoint_attribute Match on datapoint attributes
resource_attribute Match on resource attributes
scope_attribute Match on scope attributes
Trace Matchers
Field Description
span_field Match on span fields: name, kind, status, etc.
span_attribute Match on span attributes
resource_attribute Match on resource attributes
scope_attribute Match on scope attributes
event_name Match on span event names
event_attribute Match on span event attributes
link_trace_id Match on span link trace IDs
link_attribute Match on span link attributes
Nested Attribute Access

Attributes can be accessed using nested paths for structured data:

{
  "log_attribute": { "path": ["http", "request", "method"] },
  "exact": "POST"
}

Shorthand forms are also supported:

  • Array: "log_attribute": ["http", "request", "method"]
  • String (single key): "log_attribute": "user_id"
Match Conditions
Condition Description
regex Match if field matches the regex pattern
exact Match if field equals the exact value
starts_with Match if field starts with the literal prefix
ends_with Match if field ends with the literal suffix
contains Match if field contains the literal substring
exists Match if field exists (true) or doesn't exist (false)
negate Invert the match condition
case_insensitive Make the match case-insensitive (works with all matchers)

The literal matchers (starts_with, ends_with, contains, exact) are optimized using Hyperscan and are more efficient than equivalent regex patterns.

Keep Actions
Action Description
"all" Keep all matching records
"none" Drop all matching records
"N%" Sample at N% (probabilistic)
"N/s" Rate limit to N records per second
"N/m" Rate limit to N records per minute
Sampling with Sample Key

For consistent sampling (same key always produces same decision), use sample_key:

{
  "id": "sample-by-trace",
  "name": "Sample 10% of logs by trace ID",
  "log": {
    "match": [{ "log_field": "body", "contains": "request" }],
    "keep": "10%",
    "sample_key": {
      "log_field": "trace_id"
    }
  }
}

The sample key can reference any field or attribute:

  • log_field: Use a log field (body, trace_id, span_id, etc.)
  • log_attribute: Use a log record attribute
  • resource_attribute: Use a resource attribute
  • scope_attribute: Use a scope attribute

When a sample key is configured:

  • Records with the same key value always get the same keep/drop decision
  • This ensures consistent sampling across distributed systems
  • If the sample key field is empty/missing, the record is kept by default
Rate Limiting

Rate limiting allows you to cap the number of records kept per time window:

{
  "id": "rate-limit-noisy-service",
  "name": "Rate limit logs from noisy service to 100/s",
  "log": {
    "match": [
      { "resource_attribute": "service.name", "exact": "noisy-service" }
    ],
    "keep": "100/s"
  }
}

Rate limiting features:

  • Lock-free implementation: Uses atomic operations for thread-safe access without mutexes
  • Per-policy rate limiters: Each policy with rate limiting gets its own limiter
  • Automatic window reset: Windows reset inline on first request after expiry
  • Two time windows: Use /s for per-second or /m for per-minute limits

When the rate limit is exceeded, records are dropped (ResultDrop). When under the limit, records are kept (ResultKeep).

AND Semantics

All matchers within a single policy are AND'd together. A policy only matches when ALL of its matchers match:

{
  "match": [
    { "log_field": "body", "regex": "debug" },
    { "log_field": "body", "regex": "trace" }
  ]
}

This policy matches logs where the body contains BOTH "debug" AND "trace".

File Provider

The file provider loads policies from a JSON file and supports hot reload:

provider := policy.NewFileProvider("policies.json",
    policy.WithPollInterval(30*time.Second),  // Check every 30 seconds
    policy.WithOnReload(func() {
        log.Println("Policies reloaded")
    }),
    policy.WithOnError(func(err error) {
        log.Printf("Error: %v", err)
    }),
)
defer provider.Stop()

Statistics

The registry maintains per-policy statistics with atomic counters:

stats := registry.CollectStats()
for _, s := range stats {
    fmt.Printf("Policy %s: match_hits=%d match_misses=%d\n",
        s.PolicyID, s.MatchHits, s.MatchMisses)
}

TODO

Zero-Allocation Optimizations

The current implementation allocates ~16-25 objects per evaluation. To achieve zero-allocation evaluation:

  • Pool matchCounts slice in PolicyEngine.Evaluate()
  • Pool disqualified slice in PolicyEngine.Evaluate()
  • Pool Hyperscan scratch space per-database
  • Pool match result slices from db.Scan()
  • Use dense index arrays instead of maps for policy match tracking
  • Pre-allocate result slices in hot paths
Telemetry Type Support
  • Log policies (log field)
  • Metric policies (metric field)
  • Trace policies (trace field) with OTel-compliant consistent sampling
Provider Support
  • File provider with hot reload
  • HTTP provider (poll-based)
  • gRPC provider (streaming)
Additional Features
  • Nested attribute path access (e.g., http.request.method)
  • Optimized literal matchers (starts_with, ends_with, contains)
  • Case-insensitive matching via Hyperscan flags
  • Sampling with hash-based determinism via sample_key
  • Rate limiting support (N/s, N/m) with lock-free implementation
  • Transform actions (keep with modifications)
  • Policy validation CLI tool
  • Prometheus metrics exporter for stats

License

Apache 2.0 - See LICENSE for details.

Documentation

Overview

Package policy implements the Tero Policy Specification for high-performance telemetry policy evaluation and transformation.

Index

Constants

View Source
const (
	KeepAll           = engine.KeepAll
	KeepNone          = engine.KeepNone
	KeepSample        = engine.KeepSample
	KeepRatePerSecond = engine.KeepRatePerSecond
	KeepRatePerMinute = engine.KeepRatePerMinute
)

KeepAction constants.

SamplingMode constants re-exported from proto.

View Source
const (
	AttrScopeResource = engine.AttrScopeResource
	AttrScopeScope    = engine.AttrScopeScope
	AttrScopeRecord   = engine.AttrScopeRecord
	AttrScopeEvent    = engine.AttrScopeEvent
	AttrScopeLink     = engine.AttrScopeLink
)

AttrScope constants.

View Source
const (
	LogFieldBody              = engine.LogFieldBody
	LogFieldSeverityText      = engine.LogFieldSeverityText
	LogFieldTraceID           = engine.LogFieldTraceID
	LogFieldSpanID            = engine.LogFieldSpanID
	LogFieldEventName         = engine.LogFieldEventName
	LogFieldResourceSchemaURL = engine.LogFieldResourceSchemaURL
	LogFieldScopeSchemaURL    = engine.LogFieldScopeSchemaURL
)

LogField constants.

View Source
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.

View Source
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.

View Source
const (
	TransformRemove = engine.TransformRemove
	TransformRedact = engine.TransformRedact
	TransformRename = engine.TransformRename
	TransformAdd    = engine.TransformAdd
)

TransformKind constants.

Variables

View Source
var DatapointAttr = engine.DatapointAttr

DatapointAttr creates a reference to a datapoint attribute.

View Source
var LogAttr = engine.LogAttr

LogAttr creates a reference to a log record attribute.

View Source
var LogBody = engine.LogBody

LogBody creates a reference to the log body field.

View Source
var LogEventName = engine.LogEventName

LogEventName creates a reference to the log event name field.

View Source
var LogResourceAttr = engine.LogResourceAttr

LogResourceAttr creates a reference to a resource attribute on a log record.

View Source
var LogResourceSchemaURL = engine.LogResourceSchemaURL

LogResourceSchemaURL creates a reference to the log resource schema URL field.

View Source
var LogScopeAttr = engine.LogScopeAttr

LogScopeAttr creates a reference to a scope attribute on a log record.

View Source
var LogScopeSchemaURL = engine.LogScopeSchemaURL

LogScopeSchemaURL creates a reference to the log scope schema URL field.

View Source
var LogSeverityText = engine.LogSeverityText

LogSeverityText creates a reference to the log severity text field.

View Source
var LogSpanID = engine.LogSpanID

LogSpanID creates a reference to the log span ID field.

View Source
var LogTraceID = engine.LogTraceID

LogTraceID creates a reference to the log trace ID field.

View Source
var MetricAggregationTemporality = engine.MetricAggregationTemporality

MetricAggregationTemporality creates a reference to the aggregation temporality field.

View Source
var MetricDescription = engine.MetricDescription

MetricDescription creates a reference to the metric description field.

View Source
var MetricName = engine.MetricName

MetricName creates a reference to the metric name field.

View Source
var MetricResourceAttr = engine.MetricResourceAttr

MetricResourceAttr creates a reference to a resource attribute on a metric.

View Source
var MetricResourceSchemaURL = engine.MetricResourceSchemaURL

MetricResourceSchemaURL creates a reference to the metric resource schema URL field.

View Source
var MetricScopeAttr = engine.MetricScopeAttr

MetricScopeAttr creates a reference to a scope attribute on a metric.

View Source
var MetricScopeName = engine.MetricScopeName

MetricScopeName creates a reference to the metric scope name field.

View Source
var MetricScopeSchemaURL = engine.MetricScopeSchemaURL

MetricScopeSchemaURL creates a reference to the metric scope schema URL field.

View Source
var MetricScopeVersion = engine.MetricScopeVersion

MetricScopeVersion creates a reference to the metric scope version field.

View Source
var MetricType = engine.MetricType

MetricType creates a reference to the metric type field.

View Source
var MetricUnit = engine.MetricUnit

MetricUnit creates a reference to the metric unit field.

View Source
var ParseKeep = engine.ParseKeep

ParseKeep parses a keep string into a Keep struct.

View Source
var SpanAttr = engine.SpanAttr

SpanAttr creates a reference to a span attribute.

View Source
var SpanEventAttr = engine.SpanEventAttr

SpanEventAttr creates a reference to a span event attribute.

View Source
var SpanEventName = engine.SpanEventName

SpanEventName creates a reference to span event names.

View Source
var SpanKind = engine.SpanKind

SpanKind creates a reference to the span kind field.

View Source
var SpanLinkAttr = engine.SpanLinkAttr

SpanLinkAttr creates a reference to a span link attribute.

View Source
var SpanLinkTraceID = engine.SpanLinkTraceID

SpanLinkTraceID creates a reference to span link trace IDs.

View Source
var SpanName = engine.SpanName

SpanName creates a reference to the span name field.

View Source
var SpanParentSpanID = engine.SpanParentSpanID

SpanParentSpanID creates a reference to the parent span ID field.

View Source
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.

View Source
var SpanSpanID = engine.SpanSpanID

SpanSpanID creates a reference to the span ID field.

View Source
var SpanStatus = engine.SpanStatus

SpanStatus creates a reference to the span status field.

View Source
var SpanTraceID = engine.SpanTraceID

SpanTraceID creates a reference to the span trace ID field.

View Source
var SpanTraceState = engine.SpanTraceState

SpanTraceState creates a reference to the trace state field.

View Source
var TraceResourceAttr = engine.TraceResourceAttr

TraceResourceAttr creates a reference to a resource attribute on a span.

View Source
var TraceResourceSchemaURL = engine.TraceResourceSchemaURL

TraceResourceSchemaURL creates a reference to the trace resource schema URL field.

View Source
var TraceScopeAttr = engine.TraceScopeAttr

TraceScopeAttr creates a reference to a scope attribute on a span.

View Source
var TraceScopeName = engine.TraceScopeName

TraceScopeName creates a reference to the scope name field.

View Source
var TraceScopeSchemaURL = engine.TraceScopeSchemaURL

TraceScopeSchemaURL creates a reference to the scope schema URL field.

View Source
var TraceScopeVersion = engine.TraceScopeVersion

TraceScopeVersion creates a reference to the scope version field.

Functions

func IsCompilation

func IsCompilation(err error) bool

IsCompilation returns true if the error is a compilation error.

func IsEvaluation

func IsEvaluation(err error) bool

IsEvaluation returns true if the error is an evaluation error.

func IsInvalidPolicy

func IsInvalidPolicy(err error) bool

IsInvalidPolicy returns true if the error is an invalid policy error.

func IsProvider

func IsProvider(err error) bool

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 AttrScope added in v1.0.1

type AttrScope = engine.AttrScope

AttrScope identifies the scope for attribute lookups.

type Config

type Config struct {
	Providers []ProviderConfig `json:"policy_providers" mapstructure:"policy_providers"`
}

Config represents the root configuration for policy providers.

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig loads a configuration from a JSON file.

func ParseConfig

func ParseConfig(data []byte) (*Config, error)

ParseConfig parses a configuration from JSON bytes.

func ParseConfigReader

func ParseConfigReader(r io.Reader) (*Config, error)

ParseConfigReader parses a configuration from a reader.

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 ErrorKind

type ErrorKind int

ErrorKind categorizes policy errors.

const (
	// ErrInvalidPolicy indicates a policy failed validation.
	ErrInvalidPolicy ErrorKind = iota
	// ErrCompilation indicates pattern compilation failed.
	ErrCompilation
	// ErrProvider indicates a provider operation failed.
	ErrProvider
	// ErrEvaluation indicates evaluation failed.
	ErrEvaluation
)

func (ErrorKind) String

func (k ErrorKind) String() string

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

type FieldRef[T engine.FieldType] = engine.FieldRef[T]

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

WithGrpcTLS enables TLS for the connection.

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) Stop

func (p *HttpProvider) Stop()

Stop stops the polling loop.

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 Keep

type Keep = engine.Keep

Re-export engine types.

type KeepAction

type KeepAction = engine.KeepAction

Re-export engine types.

type LoadedProvider

type LoadedProvider struct {
	ID       string
	Handle   ProviderHandle
	Provider PolicyProvider
}

LoadedProvider holds information about a loaded provider.

type LogField

type LogField = engine.LogField

LogField represents a log-specific field.

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

type LogMatchFunc[T any] func(record T, ref LogFieldRef) []byte

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 LogMatcher

type LogMatcher = policyv1.LogMatcher

LogMatcher is the proto log matcher type.

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 LogTarget

type LogTarget = policyv1.LogTarget

LogTarget is the proto log target type.

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

type MetricMatchFunc[T any] func(record T, ref MetricFieldRef) []byte

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 Policy

type Policy = policyv1.Policy

Policy is the proto policy type.

type PolicyCallback

type PolicyCallback func(policies []*policyv1.Policy)

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

type PolicyError struct {
	Kind    ErrorKind
	Message string
	Cause   error
}

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

type PolicySnapshot[T engine.FieldType] struct {
	// contains filtered or unexported fields
}

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 PolicyStats

type PolicyStats = engine.PolicyStats

Re-export types from internal/engine.

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

type TraceMatchFunc[T any] func(record T, ref TraceFieldRef) []byte

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

type TraceTransformFunc[T any] func(span T, ref TraceFieldRef, value string)

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.

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

Jump to

Keyboard shortcuts

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