cortex

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: MIT Imports: 8 Imported by: 0

README

Cortex

A general-purpose rules engine for Go supporting multiple rule types, sequential evaluation, and config-driven rule definitions.

GoVersion License Zero Dependencies Go Reference Go Report Card

Features

  • Five Rule Types: Assignment, Formula, Allocation, Lookup, Buildup
  • Expression DSL: Simple expressions for config-driven formulas
  • Thread-Safe: Concurrent-safe evaluation context
  • Observable: Pluggable logging, metrics, and tracing
  • Zero Dependencies: stdlib only

Installation

go get github.com/kolosys/cortex

Quick Start

package main

import (
    "context"
    "fmt"
    "math"

    "github.com/kolosys/cortex"
)

func main() {
    engine := cortex.New("payroll", cortex.DefaultConfig())

    // Register lookup table
    engine.RegisterLookup(cortex.NewRangeLookup("tax_brackets", []cortex.RangeEntry[float64]{
        {Min: 0, Max: 50000, Value: 0.10},
        {Min: 50000, Max: 100000, Value: 0.22},
        {Min: 100000, Max: math.Inf(1), Value: 0.35},
    }))

    // Add rules
    engine.AddRules(
        cortex.MustAssignment(cortex.AssignmentConfig{
            ID: "salary", Target: "salary", Value: 75000.0,
        }),
        cortex.MustLookup(cortex.LookupConfig{
            ID: "rate", Table: "tax_brackets", Key: "salary", Target: "tax_rate",
        }),
        cortex.MustFormula(cortex.FormulaConfig{
            ID: "tax", Target: "tax", Expression: "salary * tax_rate",
        }),
        cortex.MustAllocation(cortex.AllocationConfig{
            ID: "split", Source: "salary", Strategy: cortex.StrategyPercentage,
            Targets: []cortex.AllocationTarget{
                {Key: "dept_eng", Amount: 60},
                {Key: "dept_ops", Amount: 40},
            },
        }),
    )

    // Evaluate
    evalCtx := cortex.NewEvalContext()
    result, _ := engine.Evaluate(context.Background(), evalCtx)

    fmt.Printf("Success: %v, Rules: %d\n", result.Success, result.RulesEvaluated)

    tax, _ := evalCtx.GetFloat64("tax")
    fmt.Printf("Tax: $%.2f\n", tax) // Tax: $16500.00
}

Rule Types

Assignment

Set values directly on the context:

cortex.MustAssignment(cortex.AssignmentConfig{
    ID:     "set-salary",
    Target: "salary",
    Value:  75000.0,
})
Formula

Calculate values using expressions or Go functions:

// Expression-based
cortex.MustFormula(cortex.FormulaConfig{
    ID:         "calc-tax",
    Target:     "tax",
    Expression: "salary * tax_rate",
})

// Function-based
cortex.MustFormula(cortex.FormulaConfig{
    ID:     "calc-bonus",
    Target: "bonus",
    Formula: func(ctx context.Context, e *cortex.EvalContext) (any, error) {
        salary, _ := e.GetFloat64("salary")
        return salary * 0.10, nil
    },
})
Allocation

Distribute values across targets:

cortex.MustAllocation(cortex.AllocationConfig{
    ID:       "split",
    Source:   "budget",
    Strategy: cortex.StrategyPercentage,
    Targets: []cortex.AllocationTarget{
        {Key: "eng", Amount: 50},
        {Key: "ops", Amount: 30},
        {Key: "admin", Amount: 20},
    },
})

Strategies: StrategyPercentage, StrategyFixed, StrategyWeighted, StrategyEqual, StrategyRatio

Lookup

Retrieve values from lookup tables:

// Map lookup
engine.RegisterLookup(cortex.NewMapLookup("status", map[string]int{
    "active": 1, "inactive": 0,
}))

// Range lookup (tax brackets)
engine.RegisterLookup(cortex.NewRangeLookup("rates", []cortex.RangeEntry[float64]{
    {Min: 0, Max: 50000, Value: 0.10},
    {Min: 50000, Max: 100000, Value: 0.22},
}))

cortex.MustLookup(cortex.LookupConfig{
    ID:     "get-rate",
    Table:  "rates",
    Key:    "income",
    Target: "rate",
})
Buildup

Accumulate values (running totals):

cortex.MustBuildup(cortex.BuildupConfig{
    ID:        "add-total",
    Buildup:   "running_total",
    Operation: cortex.BuildupSum,
    Source:    "amount",
    Target:    "current_total",
})

Operations: BuildupSum, BuildupMin, BuildupMax, BuildupAvg, BuildupCount, BuildupProduct

Expression DSL

Supported in config-driven formulas:

Arithmetic:  +, -, *, /, %
Comparison:  ==, !=, <, >, <=, >=
Logical:     &&, ||, !
Functions:   min, max, abs, floor, ceil, round, if, sqrt, pow

Examples:
  "base_salary * tax_rate"
  "if(age >= 65, senior_discount, 0)"
  "round(total * 0.0825, 2)"

Config-Driven Rules (JSON)

import "github.com/kolosys/cortex/parse"

json := `{
    "version": "1.0",
    "name": "payroll",
    "rules": [
        {"id": "salary", "type": "assignment", "config": {"target": "salary", "value": 75000}},
        {"id": "tax", "type": "formula", "config": {"target": "tax", "expression": "salary * 0.22"}}
    ]
}`

parser := parse.NewParser()
engine, _ := parser.ParseAndBuildEngine("payroll", []byte(json), nil)

Evaluation Modes

  • ModeFailFast (default): Stop on first error
  • ModeCollectAll: Evaluate all rules, collect errors
  • ModeContinueOnError: Log errors, continue evaluation

License

MIT

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

Constants

This section is empty.

Variables

View Source
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) ID

func (r *AllocationRule) ID() string

func (*AllocationRule) Name

func (r *AllocationRule) Name() string

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

func (r *AssignmentRule) ID() string

func (*AssignmentRule) Name

func (r *AssignmentRule) Name() string

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.

func (*Buildup) Add

func (b *Buildup) Add(value float64)

Add adds a value to the buildup.

func (*Buildup) Count

func (b *Buildup) Count() int64

Count returns the number of values added.

func (*Buildup) Current

func (b *Buildup) Current() float64

Current returns the current accumulated value.

func (*Buildup) Reset

func (b *Buildup) Reset(initial float64)

Reset resets the buildup to its initial state.

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.

func (*BuildupRule) ID

func (r *BuildupRule) ID() string

func (*BuildupRule) Name

func (r *BuildupRule) Name() string

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.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration.

type Engine

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

Engine evaluates rules in sequence.

func New

func New(name string, config *Config) *Engine

New creates a new rules engine.

func (*Engine) AddRule

func (e *Engine) AddRule(rule Rule) error

AddRule adds a rule to the engine.

func (*Engine) AddRules

func (e *Engine) AddRules(rules ...Rule) error

AddRules adds multiple rules to the engine.

func (*Engine) Clone

func (e *Engine) Clone(name string) *Engine

Clone creates a copy of the engine with the same configuration and lookups, but without any rules.

func (*Engine) Close

func (e *Engine) Close() error

Close closes the engine.

func (*Engine) Config

func (e *Engine) Config() *Config

Config returns the engine configuration.

func (*Engine) Evaluate

func (e *Engine) Evaluate(ctx context.Context, evalCtx *EvalContext) (*Result, error)

Evaluate runs all rules against the provided context.

func (*Engine) Lookups

func (e *Engine) Lookups() int

Lookups returns the number of registered lookups.

func (*Engine) Name

func (e *Engine) Name() string

Name returns the engine name.

func (*Engine) RegisterLookup

func (e *Engine) RegisterLookup(lookup Lookup) error

RegisterLookup registers a lookup table.

func (*Engine) RegisterLookups

func (e *Engine) RegisterLookups(lookups ...Lookup) error

RegisterLookups registers multiple lookup tables.

func (*Engine) Rules

func (e *Engine) Rules() int

Rules returns the number of rules.

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

func (e *EvalContext) Lookup(tableName string, key any) (any, bool, error)

Lookup performs a lookup in the specified table.

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 EvalMode

type EvalMode int

EvalMode determines how errors are handled during evaluation.

const (
	// ModeFailFast stops evaluation on first error.
	ModeFailFast EvalMode = iota

	// ModeCollectAll evaluates all rules and collects all errors.
	ModeCollectAll

	// ModeContinueOnError logs errors but continues evaluation.
	ModeContinueOnError
)

func (EvalMode) String

func (m EvalMode) String() string

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

func (r *FormulaRule) ID() string

func (*FormulaRule) Inputs

func (r *FormulaRule) Inputs() []string

Inputs returns the required input keys.

func (*FormulaRule) Name

func (r *FormulaRule) Name() string

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.

func (*LookupRule) ID

func (r *LookupRule) ID() string

func (*LookupRule) Name

func (r *LookupRule) Name() string

func (*LookupRule) Table

func (r *LookupRule) Table() string

Table returns the lookup table name.

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.

func (*MapLookup[K, V]) Get

func (l *MapLookup[K, V]) Get(key any) (any, bool)

func (*MapLookup[K, V]) Name

func (l *MapLookup[K, V]) Name() string

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

type Observability struct {
	Logger  Logger
	Metrics Metrics
	Tracer  Tracer
}

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]) Get

func (l *RangeLookup[V]) Get(key any) (any, bool)

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

func (r *Result) ErrorMessages() []string

ErrorMessages returns all error messages.

func (*Result) FirstError

func (r *Result) FirstError() error

FirstError returns the first error, or nil if none.

func (*Result) HasErrors

func (r *Result) HasErrors() bool

HasErrors returns true if any errors were collected.

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

func NewRuleError(ruleID, ruleType, phase string, err error) *RuleError

NewRuleError creates a new RuleError.

func (*RuleError) Error

func (e *RuleError) Error() string

func (*RuleError) Unwrap

func (e *RuleError) Unwrap() error

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 RuleType

type RuleType string

RuleType identifies the type of rule.

const (
	RuleTypeAssignment RuleType = "assignment"
	RuleTypeFormula    RuleType = "formula"
	RuleTypeAllocation RuleType = "allocation"
	RuleTypeLookup     RuleType = "lookup"
	RuleTypeBuildup    RuleType = "buildup"
)

type TaxBracket

type TaxBracket struct {
	Min  float64
	Max  float64
	Rate float64
}

TaxBracket is a convenience type for common tax bracket lookups.

type Tracer

type Tracer interface {
	Start(ctx context.Context, name string, kv ...any) (context.Context, func(err error))
}

Tracer provides a simple tracing interface.

type ValueFunc

type ValueFunc func(ctx context.Context, evalCtx *EvalContext) (any, error)

ValueFunc computes a value dynamically based on context.

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.

Jump to

Keyboard shortcuts

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