Documentation
¶
Overview ¶
Package cortex provides a rules engine for business logic evaluation.
Cortex supports five rule types:
- Assignment: Set values directly on the context
- Formula: Calculate values using expressions or functions
- Allocation: Distribute values across multiple targets
- Lookup: Retrieve values from lookup tables
- Buildup: Accumulate/aggregate values (running totals, sums, etc.)
Example:
engine := cortex.New("payroll", cortex.DefaultConfig())
engine.RegisterLookup(cortex.NewRangeLookup("tax_brackets", brackets))
engine.AddRules(
cortex.MustAssignment(cortex.AssignmentConfig{...}),
cortex.MustFormula(cortex.FormulaConfig{...}),
)
result, err := engine.Evaluate(ctx, cortex.NewEvalContext())
Index ¶
- Variables
- func GetTyped[T any](e *EvalContext, key string) (T, bool)
- func SetTyped[T any](e *EvalContext, key string, value T)
- type AllocationConfig
- type AllocationRule
- func (r *AllocationRule) Dependencies() []string
- func (r *AllocationRule) Description() string
- func (r *AllocationRule) Evaluate(ctx context.Context, evalCtx *EvalContext) error
- func (r *AllocationRule) ID() string
- func (r *AllocationRule) Name() string
- func (r *AllocationRule) Source() string
- func (r *AllocationRule) Strategy() AllocationStrategy
- func (r *AllocationRule) Targets() []AllocationTarget
- type AllocationStrategy
- type AllocationTarget
- type AssignmentConfig
- type AssignmentRule
- type Buildup
- type BuildupConfig
- type BuildupOperation
- type BuildupRule
- type Config
- type Engine
- func (e *Engine) AddRule(rule Rule) error
- func (e *Engine) AddRules(rules ...Rule) error
- func (e *Engine) Clone(name string) *Engine
- func (e *Engine) Close() error
- func (e *Engine) Config() *Config
- func (e *Engine) Evaluate(ctx context.Context, evalCtx *EvalContext) (*Result, error)
- func (e *Engine) Lookups() int
- func (e *Engine) Name() string
- func (e *Engine) RegisterLookup(lookup Lookup) error
- func (e *Engine) RegisterLookups(lookups ...Lookup) error
- func (e *Engine) Rules() int
- func (e *Engine) WithObservability(obs *Observability) *Engine
- type EvalContext
- func (e *EvalContext) Clone() *EvalContext
- func (e *EvalContext) Delete(key string)
- func (e *EvalContext) Duration() time.Duration
- func (e *EvalContext) ErrorCount() int64
- func (e *EvalContext) Get(key string) (any, bool)
- func (e *EvalContext) GetBool(key string) (bool, error)
- func (e *EvalContext) GetBuildup(key string) (*Buildup, bool)
- func (e *EvalContext) GetFloat64(key string) (float64, error)
- func (e *EvalContext) GetInt(key string) (int, error)
- func (e *EvalContext) GetMetadata(key string) (string, bool)
- func (e *EvalContext) GetOrCreateBuildup(key string, op BuildupOperation, initial float64) *Buildup
- func (e *EvalContext) GetString(key string) (string, error)
- func (e *EvalContext) Halt(ruleID string)
- func (e *EvalContext) HaltedBy() string
- func (e *EvalContext) Has(key string) bool
- func (e *EvalContext) IsHalted() bool
- func (e *EvalContext) Keys() []string
- func (e *EvalContext) Lookup(tableName string, key any) (any, bool, error)
- func (e *EvalContext) RegisterLookup(lookup Lookup)
- func (e *EvalContext) RulesEvaluated() int64
- func (e *EvalContext) Set(key string, value any)
- func (e *EvalContext) SetMetadata(key, value string)
- func (e *EvalContext) Values() map[string]any
- type EvalMode
- type FormulaConfig
- type FormulaFunc
- type FormulaRule
- func (r *FormulaRule) Dependencies() []string
- func (r *FormulaRule) Description() string
- func (r *FormulaRule) Evaluate(ctx context.Context, evalCtx *EvalContext) error
- func (r *FormulaRule) Expression() string
- func (r *FormulaRule) ID() string
- func (r *FormulaRule) Inputs() []string
- func (r *FormulaRule) Name() string
- func (r *FormulaRule) SetFormulaFunc(fn FormulaFunc)
- func (r *FormulaRule) Target() string
- type Logger
- type Lookup
- type LookupConfig
- type LookupRule
- type MapLookup
- type Metrics
- type Observability
- type RangeEntry
- type RangeLookup
- type Result
- type Rule
- type RuleError
- type RuleMetadata
- type RuleType
- type TaxBracket
- type Tracer
- type ValueFunc
Constants ¶
This section is empty.
Variables ¶
var ( ErrRuleNotFound = errors.New("cortex: rule not found") ErrLookupNotFound = errors.New("cortex: lookup table not found") ErrKeyNotFound = errors.New("cortex: key not found in lookup") ErrValueNotFound = errors.New("cortex: value not found in context") ErrBuildupNotFound = errors.New("cortex: buildup not found") ErrInvalidRule = errors.New("cortex: invalid rule configuration") ErrInvalidExpression = errors.New("cortex: invalid expression") ErrTypeMismatch = errors.New("cortex: type mismatch") ErrDivisionByZero = errors.New("cortex: division by zero") ErrAllocationSum = errors.New("cortex: allocation percentages must sum to 100") ErrCircularDep = errors.New("cortex: circular dependency detected") ErrEvaluation = errors.New("cortex: evaluation failed") ErrShortCircuit = errors.New("cortex: evaluation short-circuited") ErrEngineClosed = errors.New("cortex: engine is closed") ErrTimeout = errors.New("cortex: evaluation timeout") ErrNilContext = errors.New("cortex: nil evaluation context") ErrDuplicateRule = errors.New("cortex: duplicate rule ID") ErrDuplicateLookup = errors.New("cortex: duplicate lookup table name") )
Sentinel errors for common failure cases.
Functions ¶
func GetTyped ¶
func GetTyped[T any](e *EvalContext, key string) (T, bool)
GetTyped retrieves a typed value from the context.
func SetTyped ¶
func SetTyped[T any](e *EvalContext, key string, value T)
SetTyped stores a typed value in the context.
Types ¶
type AllocationConfig ¶
type AllocationConfig struct {
ID string
Name string
Description string
Deps []string
// Source is the context key containing the value to allocate.
Source string
// Strategy is the distribution method.
Strategy AllocationStrategy
// Targets are the allocation destinations.
Targets []AllocationTarget
// Remainder is an optional context key for the rounding remainder.
Remainder string
// Precision is the decimal precision (default 2).
Precision int
}
AllocationConfig configures an allocation rule.
type AllocationRule ¶
type AllocationRule struct {
// contains filtered or unexported fields
}
AllocationRule distributes a value across multiple targets.
func MustAllocation ¶
func MustAllocation(cfg AllocationConfig) *AllocationRule
MustAllocation creates a new allocation rule, panicking on error.
func NewAllocation ¶
func NewAllocation(cfg AllocationConfig) (*AllocationRule, error)
NewAllocation creates a new allocation rule.
func (*AllocationRule) Dependencies ¶
func (r *AllocationRule) Dependencies() []string
func (*AllocationRule) Description ¶
func (r *AllocationRule) Description() string
func (*AllocationRule) Evaluate ¶
func (r *AllocationRule) Evaluate(ctx context.Context, evalCtx *EvalContext) error
Evaluate distributes the source value across targets.
func (*AllocationRule) Source ¶
func (r *AllocationRule) Source() string
Source returns the source key.
func (*AllocationRule) Strategy ¶
func (r *AllocationRule) Strategy() AllocationStrategy
Strategy returns the allocation strategy.
func (*AllocationRule) Targets ¶
func (r *AllocationRule) Targets() []AllocationTarget
Targets returns the allocation targets.
type AllocationStrategy ¶
type AllocationStrategy int
AllocationStrategy defines how values are distributed.
const ( // StrategyPercentage distributes by percentage (must sum to 100). StrategyPercentage AllocationStrategy = iota // StrategyFixed distributes fixed amounts. StrategyFixed // StrategyWeighted distributes by relative weights. StrategyWeighted // StrategyEqual distributes equally among all targets. StrategyEqual // StrategyRatio distributes by ratio (e.g., 2:3:5). StrategyRatio )
func ParseAllocationStrategy ¶
func ParseAllocationStrategy(s string) (AllocationStrategy, error)
ParseAllocationStrategy parses a string into an AllocationStrategy.
func (AllocationStrategy) String ¶
func (s AllocationStrategy) String() string
type AllocationTarget ¶
type AllocationTarget struct {
Key string // context key to set
Amount float64 // percentage, fixed amount, weight, or ratio (based on strategy)
}
AllocationTarget specifies a single allocation destination.
type AssignmentConfig ¶
type AssignmentConfig struct {
ID string
Name string
Description string
Deps []string
// Target is the context key to set.
Target string
// Value is the static value to assign (mutually exclusive with ValueFunc).
Value any
// ValueFunc computes the value dynamically (mutually exclusive with Value).
ValueFunc ValueFunc
}
AssignmentConfig configures an assignment rule.
type AssignmentRule ¶
type AssignmentRule struct {
// contains filtered or unexported fields
}
AssignmentRule sets a value on the evaluation context.
func MustAssignment ¶
func MustAssignment(cfg AssignmentConfig) *AssignmentRule
MustAssignment creates a new assignment rule, panicking on error.
func NewAssignment ¶
func NewAssignment(cfg AssignmentConfig) (*AssignmentRule, error)
NewAssignment creates a new assignment rule.
func (*AssignmentRule) Dependencies ¶
func (r *AssignmentRule) Dependencies() []string
func (*AssignmentRule) Description ¶
func (r *AssignmentRule) Description() string
func (*AssignmentRule) Evaluate ¶
func (r *AssignmentRule) Evaluate(ctx context.Context, evalCtx *EvalContext) error
Evaluate sets the value on the evaluation context.
func (*AssignmentRule) Target ¶
func (r *AssignmentRule) Target() string
Target returns the target key for this assignment.
type Buildup ¶
type Buildup struct {
Name string
Operation BuildupOperation
// contains filtered or unexported fields
}
Buildup represents a running accumulator.
type BuildupConfig ¶
type BuildupConfig struct {
ID string
Name string
Description string
Deps []string
// Buildup is the buildup accumulator name (created if not exists).
Buildup string
// Operation is the accumulation operation.
Operation BuildupOperation
// Source is the context key containing the value to add.
Source string
// Initial is the initial value for the buildup (if created).
Initial float64
// Target is an optional context key to write the current value after adding.
Target string
}
BuildupConfig configures a buildup rule.
type BuildupOperation ¶
type BuildupOperation int
BuildupOperation defines how values are accumulated.
const ( // BuildupSum adds values together. BuildupSum BuildupOperation = iota // BuildupMin keeps the minimum value. BuildupMin // BuildupMax keeps the maximum value. BuildupMax // BuildupAvg computes running average. BuildupAvg // BuildupCount counts occurrences. BuildupCount // BuildupProduct multiplies values together. BuildupProduct )
func ParseBuildupOperation ¶
func ParseBuildupOperation(s string) (BuildupOperation, error)
ParseBuildupOperation parses a string into a BuildupOperation.
func (BuildupOperation) String ¶
func (op BuildupOperation) String() string
type BuildupRule ¶
type BuildupRule struct {
// contains filtered or unexported fields
}
BuildupRule accumulates values (running totals, aggregations).
func MustBuildup ¶
func MustBuildup(cfg BuildupConfig) *BuildupRule
MustBuildup creates a new buildup rule, panicking on error.
func NewBuildup ¶
func NewBuildup(cfg BuildupConfig) (*BuildupRule, error)
NewBuildup creates a new buildup rule.
func (*BuildupRule) BuildupName ¶
func (r *BuildupRule) BuildupName() string
BuildupName returns the buildup accumulator name.
func (*BuildupRule) Dependencies ¶
func (r *BuildupRule) Dependencies() []string
func (*BuildupRule) Description ¶
func (r *BuildupRule) Description() string
func (*BuildupRule) Evaluate ¶
func (r *BuildupRule) Evaluate(ctx context.Context, evalCtx *EvalContext) error
Evaluate adds to the buildup accumulator.
type Config ¶
type Config struct {
// Mode determines error handling behavior.
Mode EvalMode
// Timeout for entire evaluation (0 = no timeout).
Timeout time.Duration
// ShortCircuit allows rules to halt evaluation early.
ShortCircuit bool
// EnableMetrics enables detailed metrics collection.
EnableMetrics bool
// MaxRules limits the number of rules (0 = unlimited).
MaxRules int
}
Config configures the engine behavior.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Config with sensible defaults.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine evaluates rules in sequence.
func (*Engine) Clone ¶
Clone creates a copy of the engine with the same configuration and lookups, but without any rules.
func (*Engine) RegisterLookup ¶
RegisterLookup registers a lookup table.
func (*Engine) RegisterLookups ¶
RegisterLookups registers multiple lookup tables.
func (*Engine) WithObservability ¶
func (e *Engine) WithObservability(obs *Observability) *Engine
WithObservability sets observability hooks.
type EvalContext ¶
type EvalContext struct {
ID string
// contains filtered or unexported fields
}
EvalContext holds the state during rule evaluation. It provides thread-safe access to values, buildups, and lookups.
func NewEvalContext ¶
func NewEvalContext() *EvalContext
NewEvalContext creates a new evaluation context.
func (*EvalContext) Clone ¶
func (e *EvalContext) Clone() *EvalContext
Clone creates a shallow copy of the context.
func (*EvalContext) Delete ¶
func (e *EvalContext) Delete(key string)
Delete removes a value from the context.
func (*EvalContext) Duration ¶
func (e *EvalContext) Duration() time.Duration
Duration returns the time since context creation.
func (*EvalContext) ErrorCount ¶
func (e *EvalContext) ErrorCount() int64
ErrorCount returns the number of errors encountered.
func (*EvalContext) Get ¶
func (e *EvalContext) Get(key string) (any, bool)
Get retrieves a value from the context.
func (*EvalContext) GetBool ¶
func (e *EvalContext) GetBool(key string) (bool, error)
GetBool retrieves a bool value from the context.
func (*EvalContext) GetBuildup ¶
func (e *EvalContext) GetBuildup(key string) (*Buildup, bool)
GetBuildup returns a buildup accumulator for the given key.
func (*EvalContext) GetFloat64 ¶
func (e *EvalContext) GetFloat64(key string) (float64, error)
GetFloat64 retrieves a float64 value from the context.
func (*EvalContext) GetInt ¶
func (e *EvalContext) GetInt(key string) (int, error)
GetInt retrieves an int value from the context.
func (*EvalContext) GetMetadata ¶
func (e *EvalContext) GetMetadata(key string) (string, bool)
GetMetadata retrieves a metadata value.
func (*EvalContext) GetOrCreateBuildup ¶
func (e *EvalContext) GetOrCreateBuildup(key string, op BuildupOperation, initial float64) *Buildup
GetOrCreateBuildup returns an existing buildup or creates a new one.
func (*EvalContext) GetString ¶
func (e *EvalContext) GetString(key string) (string, error)
GetString retrieves a string value from the context.
func (*EvalContext) Halt ¶
func (e *EvalContext) Halt(ruleID string)
Halt stops evaluation with the given rule ID.
func (*EvalContext) HaltedBy ¶
func (e *EvalContext) HaltedBy() string
HaltedBy returns the rule ID that halted evaluation.
func (*EvalContext) Has ¶
func (e *EvalContext) Has(key string) bool
Has checks if a key exists in the context.
func (*EvalContext) IsHalted ¶
func (e *EvalContext) IsHalted() bool
IsHalted returns true if evaluation has been halted.
func (*EvalContext) Keys ¶
func (e *EvalContext) Keys() []string
Keys returns all keys in the context.
func (*EvalContext) RegisterLookup ¶
func (e *EvalContext) RegisterLookup(lookup Lookup)
RegisterLookup registers a lookup table in the context.
func (*EvalContext) RulesEvaluated ¶
func (e *EvalContext) RulesEvaluated() int64
RulesEvaluated returns the number of rules evaluated.
func (*EvalContext) Set ¶
func (e *EvalContext) Set(key string, value any)
Set stores a value in the context.
func (*EvalContext) SetMetadata ¶
func (e *EvalContext) SetMetadata(key, value string)
SetMetadata sets a metadata key-value pair.
func (*EvalContext) Values ¶
func (e *EvalContext) Values() map[string]any
Values returns a copy of all values in the context.
type FormulaConfig ¶
type FormulaConfig struct {
ID string
Name string
Description string
Deps []string
// Target is the context key to store the result.
Target string
// Inputs are the required input keys (for dependency tracking).
Inputs []string
// Formula is the Go function for complex rules.
Formula FormulaFunc
// Expression is the expression string for config-driven rules.
// (Mutually exclusive with Formula)
Expression string
}
FormulaConfig configures a formula rule.
type FormulaFunc ¶
type FormulaFunc func(ctx context.Context, evalCtx *EvalContext) (any, error)
FormulaFunc computes a value from the evaluation context.
func Add ¶
func Add(a, b string) FormulaFunc
Add returns a FormulaFunc that adds two context values.
func Conditional ¶
func Conditional(condition string, thenVal, elseVal any) FormulaFunc
Conditional returns a FormulaFunc that returns thenVal if condition is true, else elseVal.
func Divide ¶
func Divide(a, b string) FormulaFunc
Divide returns a FormulaFunc that divides a by b.
func Multiply ¶
func Multiply(a, b string) FormulaFunc
Multiply returns a FormulaFunc that multiplies two context values.
func Percentage ¶
func Percentage(value string, percent float64) FormulaFunc
Percentage returns a FormulaFunc that calculates a percentage of a value.
func Subtract ¶
func Subtract(a, b string) FormulaFunc
Subtract returns a FormulaFunc that subtracts b from a.
type FormulaRule ¶
type FormulaRule struct {
// contains filtered or unexported fields
}
FormulaRule calculates a value using a function or expression.
func MustFormula ¶
func MustFormula(cfg FormulaConfig) *FormulaRule
MustFormula creates a new formula rule, panicking on error.
func NewFormula ¶
func NewFormula(cfg FormulaConfig) (*FormulaRule, error)
NewFormula creates a new formula rule.
func (*FormulaRule) Dependencies ¶
func (r *FormulaRule) Dependencies() []string
func (*FormulaRule) Description ¶
func (r *FormulaRule) Description() string
func (*FormulaRule) Evaluate ¶
func (r *FormulaRule) Evaluate(ctx context.Context, evalCtx *EvalContext) error
Evaluate computes and stores the formula result.
func (*FormulaRule) Expression ¶
func (r *FormulaRule) Expression() string
Expression returns the expression string (if any).
func (*FormulaRule) Inputs ¶
func (r *FormulaRule) Inputs() []string
Inputs returns the required input keys.
func (*FormulaRule) SetFormulaFunc ¶
func (r *FormulaRule) SetFormulaFunc(fn FormulaFunc)
SetFormulaFunc sets the formula function (used by expression parser).
func (*FormulaRule) Target ¶
func (r *FormulaRule) Target() string
Target returns the target key for this formula.
type Logger ¶
type Logger interface {
Debug(msg string, kv ...any)
Info(msg string, kv ...any)
Warn(msg string, kv ...any)
Error(msg string, err error, kv ...any)
}
Logger provides a simple logging interface.
type Lookup ¶
type Lookup interface {
// Name returns the lookup table name.
Name() string
// Get retrieves a value by key.
Get(key any) (any, bool)
}
Lookup represents a lookup table.
type LookupConfig ¶
type LookupConfig struct {
ID string
Name string
Description string
Deps []string
// Table is the lookup table name (must be registered).
Table string
// Key is the context key to use as lookup key.
Key string
// Target is the context key to store the result.
Target string
// Default is the value if not found (ignored if Required is true).
Default any
// Required causes an error if the lookup key is not found.
Required bool
}
LookupConfig configures a lookup rule.
type LookupRule ¶
type LookupRule struct {
// contains filtered or unexported fields
}
LookupRule retrieves a value from a lookup table.
func MustLookup ¶
func MustLookup(cfg LookupConfig) *LookupRule
MustLookup creates a new lookup rule, panicking on error.
func NewLookup ¶
func NewLookup(cfg LookupConfig) (*LookupRule, error)
NewLookup creates a new lookup rule.
func (*LookupRule) Dependencies ¶
func (r *LookupRule) Dependencies() []string
func (*LookupRule) Description ¶
func (r *LookupRule) Description() string
func (*LookupRule) Evaluate ¶
func (r *LookupRule) Evaluate(ctx context.Context, evalCtx *EvalContext) error
Evaluate performs the lookup and sets the result.
type MapLookup ¶
type MapLookup[K comparable, V any] struct { // contains filtered or unexported fields }
MapLookup provides a simple map-based lookup implementation.
func NewMapLookup ¶
func NewMapLookup[K comparable, V any](name string, items map[K]V) *MapLookup[K, V]
NewMapLookup creates a new map-based lookup table.
type Metrics ¶
type Metrics interface {
Inc(name string, kv ...any)
Add(name string, v float64, kv ...any)
Histogram(name string, v float64, kv ...any)
}
Metrics provides a simple metrics interface.
type Observability ¶
Observability holds observability hooks for the engine.
type RangeEntry ¶
type RangeEntry[V any] struct { Min float64 // inclusive Max float64 // exclusive (use math.Inf(1) for unbounded) Value V }
RangeEntry represents a single range in a range lookup.
type RangeLookup ¶
type RangeLookup[V any] struct { // contains filtered or unexported fields }
RangeLookup provides range-based lookup (e.g., tax brackets).
func NewRangeLookup ¶
func NewRangeLookup[V any](name string, ranges []RangeEntry[V]) *RangeLookup[V]
NewRangeLookup creates a new range-based lookup table.
func NewTaxBracketLookup ¶
func NewTaxBracketLookup(name string, brackets []TaxBracket) *RangeLookup[float64]
NewTaxBracketLookup creates a range lookup for tax brackets.
func (*RangeLookup[V]) Name ¶
func (l *RangeLookup[V]) Name() string
type Result ¶
type Result struct {
// ID is the evaluation context ID.
ID string
// Success indicates if all rules evaluated without error.
Success bool
// RulesEvaluated is the number of rules that were run.
RulesEvaluated int
// RulesFailed is the number of rules that failed.
RulesFailed int
// Errors contains all collected errors (in CollectAll mode).
Errors []RuleError
// Duration is the total evaluation time.
Duration time.Duration
// HaltedBy is the rule ID that halted evaluation (if any).
HaltedBy string
// Context is the final evaluation context state.
Context *EvalContext
}
Result contains the outcome of a rule evaluation.
func (*Result) ErrorMessages ¶
ErrorMessages returns all error messages.
func (*Result) FirstError ¶
FirstError returns the first error, or nil if none.
type Rule ¶
type Rule interface {
// ID returns the unique identifier for this rule.
ID() string
// Evaluate executes the rule against the provided context.
Evaluate(ctx context.Context, evalCtx *EvalContext) error
}
Rule represents any rule that can be evaluated against an EvalContext.
type RuleError ¶
type RuleError struct {
RuleID string
RuleType string
Phase string // "validate", "evaluate"
Err error
}
RuleError wraps an error with rule context.
func NewRuleError ¶
NewRuleError creates a new RuleError.
type RuleMetadata ¶
type RuleMetadata interface {
Rule
// Name returns a human-readable name for the rule.
Name() string
// Description returns a description of what the rule does.
Description() string
// Dependencies returns the IDs of other rules this rule depends on.
Dependencies() []string
}
RuleMetadata provides optional metadata about a rule.
type TaxBracket ¶
TaxBracket is a convenience type for common tax bracket lookups.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package expr provides a simple expression DSL for cortex formulas.
|
Package expr provides a simple expression DSL for cortex formulas. |
|
Package parse provides JSON parsing for cortex rule definitions.
|
Package parse provides JSON parsing for cortex rule definitions. |