evaluator

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildCacheKey added in v0.16.0

func BuildCacheKey(flagID string, version uint64, meta CachedDimMeta, evalCtx proto.Message) string

BuildCacheKey constructs a dimension-classified cache key from the flag ID, version stamp, dimension metadata, and evaluation context. Values are length-prefixed to prevent delimiter collision.

func InitTracer added in v0.4.0

func InitTracer(ctx context.Context, serviceName, version string) (shutdown func(context.Context) error, err error)

InitTracer sets up the OpenTelemetry TracerProvider.

When OTEL_EXPORTER_OTLP_ENDPOINT is set, spans are exported via gRPC to the configured collector. When unset, a noop provider is registered so all tracing calls are zero-cost no-ops.

Returns a shutdown function that flushes buffered spans.

func NormalizeConnectURL added in v0.13.0

func NormalizeConnectURL(raw string) string

NormalizeConnectURL ensures a URL has an http:// or https:// scheme, which Connect-Go requires. Bare "host:port" strings get http:// prepended.

func ParseDescriptorSet added in v0.16.0

func ParseDescriptorSet(data []byte) (*protoregistry.Files, *protoregistry.Types, error)

ParseDescriptorSet parses a serialized FileDescriptorSet and returns the file and type registries. This is useful when callers need access to the proto descriptors beyond just flag definitions (e.g., discovering the EvaluationContext message).

Types

type CacheConfig

type CacheConfig struct {
	KillTTL       time.Duration
	FlagTTL       time.Duration
	JitterPercent int
	FetchTimeout  time.Duration
}

CacheConfig controls cache TTLs and sizes.

type CacheStore

type CacheStore struct {
	// contains filtered or unexported fields
}

CacheStore provides caching for all evaluator data.

Ristretto caches provide fast lookups with TTL-based freshness. When an entry expires, it is evicted. To satisfy the design requirement that stale data is served indefinitely during server outages, a parallel staleFlagMap retains the last-known values without TTL. The stale map is consulted only when the Ristretto cache misses AND the server fetch fails.

func NewCacheStore

func NewCacheStore(cfg CacheStoreConfig) (*CacheStore, error)

NewCacheStore creates a cache store.

func (*CacheStore) CachedFlagCount

func (s *CacheStore) CachedFlagCount() int32

CachedFlagCount returns the approximate number of cached flag states.

func (*CacheStore) Close

func (s *CacheStore) Close()

Close releases cache resources.

func (*CacheStore) FlushAll

func (s *CacheStore) FlushAll()

FlushAll evicts all entries from the hot cache (Ristretto) and the stale fallback map, forcing cold-start fetches on the next evaluation.

func (*CacheStore) FlushHot added in v0.14.0

func (s *CacheStore) FlushHot()

FlushHot evicts entries from the hot cache (Ristretto) only. The stale fallback map is preserved, simulating natural TTL expiry.

func (*CacheStore) GetFlagState

func (s *CacheStore) GetFlagState(flagID string) *CachedFlagState

GetFlagState returns the cached state for a flag, or nil on miss. When flagTTL is 0 (write-through mode), always returns nil to force a fresh fetch.

func (*CacheStore) GetKillSet

func (s *CacheStore) GetKillSet() *KillSet

GetKillSet returns the current kill set.

func (*CacheStore) GetStaleFlagState

func (s *CacheStore) GetStaleFlagState(flagID string) *CachedFlagState

GetStaleFlagState returns the last-known state from the stale fallback map.

func (*CacheStore) SetFlagState

func (s *CacheStore) SetFlagState(state *CachedFlagState)

SetFlagState caches a flag state with TTL + jitter. When flagTTL is 0 (write-through mode), only the stale fallback map is populated.

func (*CacheStore) SetKillSet

func (s *CacheStore) SetKillSet(ks *KillSet)

SetKillSet atomically replaces the kill set.

func (*CacheStore) WaitAll

func (s *CacheStore) WaitAll()

WaitAll blocks until the Ristretto cache has processed all pending writes and evictions.

type CacheStoreConfig

type CacheStoreConfig struct {
	FlagTTL       time.Duration
	JitterPercent int
}

CacheStoreConfig configures cache sizes and TTLs.

type CachedCondition added in v0.16.0

type CachedCondition struct {
	Program cel.Program          // compiled CEL program; nil for "otherwise"
	Value   *pbflagsv1.FlagValue // the value to return when this condition matches
	Source  string               // original CEL expression text (empty for "otherwise")
}

CachedCondition is a compiled condition ready for evaluation.

type CachedDimMeta added in v0.16.0

type CachedDimMeta map[string]*celenv.DimensionMeta

CachedDimMeta holds the deserialized dimension metadata for a flag, loaded from the dimension_metadata JSONB column.

func ParseDimMeta added in v0.16.0

func ParseDimMeta(data []byte) CachedDimMeta

ParseDimMeta deserializes the dimension_metadata JSONB.

type CachedFlagState

type CachedFlagState struct {
	FlagID     string
	State      pbflagsv1.State
	Value      *pbflagsv1.FlagValue
	Archived   bool
	Conditions []CachedCondition // compiled condition chain (nil for static/unconfigured flags)
	DimMeta    CachedDimMeta     // dimension classification metadata (nil for flags without conditions)
}

CachedFlagState holds cached state for a single flag.

type ConditionCache added in v0.16.0

type ConditionCache struct {
	// contains filtered or unexported fields
}

ConditionCache caches condition evaluation results keyed by dimension-classified cache keys with per-flag version stamps for invalidation on config changes.

func NewConditionCache added in v0.16.0

func NewConditionCache(maxEntries int64) (*ConditionCache, error)

NewConditionCache creates a condition result cache with the given max entries.

func (*ConditionCache) Clear added in v0.16.0

func (c *ConditionCache) Clear()

Clear evicts all entries.

func (*ConditionCache) Close added in v0.16.0

func (c *ConditionCache) Close()

Close releases cache resources.

func (*ConditionCache) FlagVersion added in v0.16.0

func (c *ConditionCache) FlagVersion(flagID string) uint64

FlagVersion returns the current cache version for a flag.

func (*ConditionCache) Get added in v0.16.0

func (c *ConditionCache) Get(key string) (val *pbflagsv1.FlagValue, noMatch bool, found bool)

Get looks up a cached condition result. Returns (value, noMatch, found). When noMatch is true, the CEL chain was evaluated and no condition matched.

func (*ConditionCache) InvalidateFlag added in v0.16.0

func (c *ConditionCache) InvalidateFlag(flagID string)

InvalidateFlag bumps the version for a flag, making all existing cache entries for that flag unreachable (they have the old version in their key). Old entries are evicted naturally by LRU.

func (*ConditionCache) Set added in v0.16.0

func (c *ConditionCache) Set(key string, val *pbflagsv1.FlagValue)

Set stores a condition match result.

func (*ConditionCache) SetNoMatch added in v0.16.0

func (c *ConditionCache) SetNoMatch(key string)

SetNoMatch stores a "no condition matched" sentinel.

func (*ConditionCache) Wait added in v0.16.0

func (c *ConditionCache) Wait()

Wait blocks until all pending writes are processed.

type ConditionEvaluator added in v0.16.0

type ConditionEvaluator struct {
	// contains filtered or unexported fields
}

ConditionEvaluator compiles stored condition JSON into CEL programs and evaluates them against an EvaluationContext proto message.

func NewConditionEvaluator added in v0.16.0

func NewConditionEvaluator(md protoreflect.MessageDescriptor, logger *slog.Logger) (*ConditionEvaluator, error)

NewConditionEvaluator creates a ConditionEvaluator from the EvaluationContext message descriptor. Returns nil if md is nil (no conditions support).

func (*ConditionEvaluator) CompileConditions added in v0.16.0

func (ce *ConditionEvaluator) CompileConditions(flagID string, conditionsJSON []byte) []CachedCondition

CompileConditions parses the conditions JSONB and compiles CEL programs. Returns nil if conditionsJSON is nil (no conditions). On compile failure, logs the error and returns nil (graceful degradation to default).

func (*ConditionEvaluator) EvaluateConditions added in v0.16.0

func (ce *ConditionEvaluator) EvaluateConditions(flagID string, conditions []CachedCondition, evalCtx proto.Message) *EvalResult

EvaluateConditions iterates the condition chain and returns the value of the first matching condition. Returns a nil Value if no condition matches or if evalCtx is nil.

func (*ConditionEvaluator) UnmarshalContext added in v0.16.0

func (ce *ConditionEvaluator) UnmarshalContext(anyCtx *anypb.Any) (proto.Message, error)

UnmarshalContext deserializes an anypb.Any into a dynamic proto message matching the EvaluationContext type. Returns nil if the Any is nil.

type Config

type Config struct {
	Descriptors string
	Upstream    string
	Listen      string
	Admin       string
	Database    string
	Cache       CacheConfig
	EnvName     string
	EnvColor    string
}

Config is the shared evaluator/admin configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with all default values applied.

func LoadConfig

func LoadConfig() Config

LoadConfig reads configuration from environment variable overrides on top of defaults. It does not validate the result — each binary is responsible for checking that the fields it requires are populated.

type DBFetcher

type DBFetcher struct {
	// contains filtered or unexported fields
}

DBFetcher fetches flag state directly from PostgreSQL. It implements Fetcher (for the Evaluator), KillFetcher (for the KillPoller), and StateServer (for the Service to serve state RPCs in root mode).

func NewDBFetcher

func NewDBFetcher(pool *pgxpool.Pool, tracker *HealthTracker, logger *slog.Logger, m *Metrics, tracer trace.Tracer, opts ...DBFetcherOption) *DBFetcher

NewDBFetcher creates a fetcher backed by direct database access.

func (*DBFetcher) FetchFlagState

func (f *DBFetcher) FetchFlagState(ctx context.Context, flagID string) (*CachedFlagState, error)

FetchFlagState implements Fetcher.

func (*DBFetcher) GetFlagStateProto

func (f *DBFetcher) GetFlagStateProto(ctx context.Context, flagID string) (*pbflagsv1.GetFlagStateResponse, error)

GetFlagStateProto implements StateServer.

func (*DBFetcher) GetKilledFlags

func (f *DBFetcher) GetKilledFlags(ctx context.Context) (*KillSet, error)

GetKilledFlags implements KillFetcher.

func (*DBFetcher) GetKilledFlagsProto

func (f *DBFetcher) GetKilledFlagsProto(ctx context.Context) (*pbflagsv1.GetKilledFlagsResponse, error)

GetKilledFlagsProto implements StateServer.

func (*DBFetcher) GetOverridesProto

func (f *DBFetcher) GetOverridesProto(_ context.Context, _ string, _ []string) (*pbflagsv1.GetOverridesResponse, error)

GetOverridesProto implements StateServer. Overrides table has been removed; always returns an empty response.

type DBFetcherOption added in v0.16.0

type DBFetcherOption func(*DBFetcher)

DBFetcherOption configures optional DBFetcher behavior.

func WithDBConditionEvaluator added in v0.16.0

func WithDBConditionEvaluator(ce *ConditionEvaluator) DBFetcherOption

WithDBConditionEvaluator sets the condition evaluator for compiling conditions loaded from the database.

type DescriptorWatcher

type DescriptorWatcher struct {
	// contains filtered or unexported fields
}

DescriptorWatcher monitors the descriptors file for changes and syncs definitions to the DB in standalone mode.

func NewDescriptorWatcher

func NewDescriptorWatcher(
	path string,
	pollInterval time.Duration,
	sighupCh <-chan os.Signal,
	logger *slog.Logger,
) *DescriptorWatcher

NewDescriptorWatcher creates a descriptor file watcher.

func (*DescriptorWatcher) Run

func (w *DescriptorWatcher) Run(ctx context.Context)

Run starts the watcher. Blocks until ctx is cancelled.

func (*DescriptorWatcher) SetSyncAndReload added in v0.11.0

func (w *DescriptorWatcher) SetSyncAndReload(fn SyncAndReloadFunc)

SetSyncAndReload sets the sync callback for monolithic mode. When set, descriptor file changes trigger: parse → sync to DB.

type EvalResult added in v0.16.0

type EvalResult struct {
	Value             *pbflagsv1.FlagValue
	ConditionsChecked int // how many CEL programs were evaluated
}

EvalResult holds the result and metadata from condition evaluation.

type Evaluator

type Evaluator struct {
	// contains filtered or unexported fields
}

Evaluator resolves flag values using the precedence chain: kill set → conditions (CEL) → global state → stale cache → compiled default.

func NewEvaluator

func NewEvaluator(cache *CacheStore, fetcher Fetcher, logger *slog.Logger, m *Metrics, tracer trace.Tracer, opts ...EvaluatorOption) *Evaluator

NewEvaluator creates an Evaluator.

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(ctx context.Context, flagID, entityID string) (value *pbflagsv1.FlagValue, source pbflagsv1.EvaluationSource)

Evaluate resolves a single flag for an optional entity.

func (*Evaluator) EvaluateWithContext added in v0.16.0

func (e *Evaluator) EvaluateWithContext(ctx context.Context, flagID string, evalCtx proto.Message) (value *pbflagsv1.FlagValue, source pbflagsv1.EvaluationSource)

EvaluateWithContext resolves a flag using the v1 evaluation precedence: kill set → conditions (CEL) → static config value → compiled default. evalCtx is the deserialized EvaluationContext proto (may be nil).

type EvaluatorOption added in v0.14.0

type EvaluatorOption func(*Evaluator)

EvaluatorOption configures optional Evaluator behavior.

func WithConditionCache added in v0.16.0

func WithConditionCache(cc *ConditionCache) EvaluatorOption

WithConditionCache sets the cache for condition evaluation results.

func WithConditionEvaluator added in v0.16.0

func WithConditionEvaluator(ce *ConditionEvaluator) EvaluatorOption

WithConditionEvaluator enables CEL condition evaluation.

func WithFetchTimeout added in v0.14.0

func WithFetchTimeout(d time.Duration) EvaluatorOption

WithFetchTimeout sets the timeout for background refresh fetches. Defaults to 500ms if not set.

func WithInlineKillCheck added in v0.14.0

func WithInlineKillCheck() EvaluatorOption

WithInlineKillCheck enables inline kill checking. Use this when the kill set poller is not running (e.g. flagTTL <= killTTL) so kills are still checked by fetching each flag's state eagerly.

type Fetcher

type Fetcher interface {
	FetchFlagState(ctx context.Context, flagID string) (*CachedFlagState, error)
}

Fetcher fetches flag state from the remote flag server on demand.

type FlagDef

type FlagDef struct {
	FlagID    string
	FeatureID string
	FieldNum  int32
	Name      string
	FlagType  pbflagsv1.FlagType
	Layer     string // Layer name from FlagOptions.layer (e.g., "user", "entity"). Empty means global.
	Default   *pbflagsv1.FlagValue

	SupportedValues *pbflagspb.SupportedValues

	FeatureDisplayName string
	FeatureDescription string
	FeatureOwner       string
}

FlagDef is a flag definition extracted from a proto descriptor.

func ParseDescriptorFile

func ParseDescriptorFile(path string) ([]FlagDef, error)

ParseDescriptorFile reads and parses a FileDescriptorSet from the given path.

func ParseDescriptors

func ParseDescriptors(data []byte) ([]FlagDef, error)

ParseDescriptors extracts flag definitions from a serialized FileDescriptorSet.

func (*FlagDef) IsGlobalLayer

func (d *FlagDef) IsGlobalLayer() bool

IsGlobalLayer returns true if the flag layer is global (including unspecified).

type FlagServerClient

type FlagServerClient struct {
	// contains filtered or unexported fields
}

FlagServerClient talks to the upstream evaluator's FlagEvaluatorService via Connect.

func NewFlagServerClient

func NewFlagServerClient(serverURL string, tracker *HealthTracker, fetchTimeout time.Duration, m *Metrics, opts ...connect.ClientOption) *FlagServerClient

NewFlagServerClient creates a Connect client for the upstream evaluator.

func (*FlagServerClient) FetchFlagState

func (c *FlagServerClient) FetchFlagState(ctx context.Context, flagID string) (*CachedFlagState, error)

FetchFlagState implements Fetcher.

func (*FlagServerClient) GetKilledFlags

func (c *FlagServerClient) GetKilledFlags(ctx context.Context) (*KillSet, error)

GetKilledFlags fetches the current kill set from the server.

func (*FlagServerClient) StateServer

func (c *FlagServerClient) StateServer() StateServer

StateServer returns a StateServer that delegates to the upstream evaluator.

type HealthTracker

type HealthTracker struct {
	// contains filtered or unexported fields
}

HealthTracker maintains health state and computes backoff intervals.

func NewHealthTracker

func NewHealthTracker(m *Metrics) *HealthTracker

NewHealthTracker creates a tracker starting in CONNECTING state.

func (*HealthTracker) BackoffMultiplier

func (t *HealthTracker) BackoffMultiplier() int

BackoffMultiplier returns the current backoff multiplier.

0 failures → 1x, 1-2 → 2x, 3-5 → 4x, 6+ → 8x (capped)

func (*HealthTracker) ConsecutiveFailures

func (t *HealthTracker) ConsecutiveFailures() int32

ConsecutiveFailures returns the current failure count.

func (*HealthTracker) RecordFailure

func (t *HealthTracker) RecordFailure()

RecordFailure increments the failure counter and may transition to DEGRADED.

func (*HealthTracker) RecordSuccess

func (t *HealthTracker) RecordSuccess()

RecordSuccess resets failure count and transitions to SERVING.

func (*HealthTracker) SecondsSinceContact

func (t *HealthTracker) SecondsSinceContact() int64

SecondsSinceContact returns seconds since last successful server contact.

func (*HealthTracker) Status

Status returns the current evaluator status.

type KillFetcher

type KillFetcher interface {
	GetKilledFlags(ctx context.Context) (*KillSet, error)
}

KillFetcher fetches the current kill set. Implemented by both FlagServerClient (proxy mode) and DBFetcher (root mode).

type KillPoller

type KillPoller struct {
	// contains filtered or unexported fields
}

KillPoller runs a background loop that polls GetKilledFlags at regular intervals. On failure, the last known kill set is preserved indefinitely.

func NewKillPoller

func NewKillPoller(
	fetcher KillFetcher,
	cache *CacheStore,
	tracker *HealthTracker,
	baseTTL, timeout time.Duration,
	logger *slog.Logger,
	m *Metrics,
) *KillPoller

NewKillPoller creates a kill set poller.

func (*KillPoller) Run

func (p *KillPoller) Run(ctx context.Context)

Run starts the polling loop. Blocks until ctx is cancelled.

type KillSet

type KillSet struct {
	FlagIDs map[string]struct{}
}

KillSet holds the current set of globally killed flags.

func (*KillSet) IsKilled

func (ks *KillSet) IsKilled(flagID string) bool

IsKilled checks if a flag is globally killed.

type Metrics added in v0.4.0

type Metrics struct {
	EvaluationsTotal    *prometheus.CounterVec
	CacheHitsTotal      *prometheus.CounterVec
	CacheMissesTotal    *prometheus.CounterVec
	BackgroundRefreshes *prometheus.CounterVec
	FetchDuration       *prometheus.HistogramVec
	KillSetSize         prometheus.Gauge
	ConsecutiveFails    prometheus.Gauge
	PollerLastSuccess   prometheus.Gauge
}

Metrics holds all Prometheus metrics for the evaluator.

func NewMetrics added in v0.4.0

func NewMetrics(reg prometheus.Registerer) *Metrics

NewMetrics creates and registers all metrics with the given registerer.

func NewNoopMetrics added in v0.4.0

func NewNoopMetrics() *Metrics

NewNoopMetrics returns metrics that are not registered with any registry. Use in tests where metric values don't matter.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service implements the FlagEvaluatorService Connect handler.

func NewService

func NewService(eval *Evaluator, tracker *HealthTracker, cache *CacheStore, state StateServer) *Service

NewService creates the evaluator Connect service.

func (*Service) BulkEvaluate

BulkEvaluate resolves multiple flags at once.

func (*Service) Evaluate

Evaluate resolves a single flag value.

func (*Service) GetFlagState

GetFlagState fetches state for a single flag via the StateServer.

func (*Service) GetKilledFlags

GetKilledFlags fetches the current kill set via the StateServer.

func (*Service) GetOverrides

GetOverrides returns an empty response. The overrides table has been removed.

func (*Service) Health

Health returns the evaluator's current health and degradation status.

type StateServer

type StateServer interface {
	GetFlagStateProto(ctx context.Context, flagID string) (*pbflagsv1.GetFlagStateResponse, error)
	GetKilledFlagsProto(ctx context.Context) (*pbflagsv1.GetKilledFlagsResponse, error)
	GetOverridesProto(ctx context.Context, entityID string, flagIDs []string) (*pbflagsv1.GetOverridesResponse, error)
}

StateServer serves flag state RPCs. In root mode this reads from DB (via DBFetcher), in proxy mode it delegates to an upstream evaluator.

type SyncAndReloadFunc added in v0.11.0

type SyncAndReloadFunc func(ctx context.Context, defs []FlagDef) error

SyncAndReloadFunc is called by the DescriptorWatcher in monolithic mode. It receives the parsed definitions and syncs them to the DB. If it returns an error, the sync is considered failed.

Jump to

Keyboard shortcuts

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