Documentation
¶
Overview ¶
Package ruleengine evaluates typed propositions over immutable fact contexts. It deliberately provides no authorization, feature-rollout, validation, workflow, persistence, or action-execution semantics.
Example ¶
package main
import (
"context"
"fmt"
ruleengine "github.com/faustbrian/go-rule-engine"
)
func main() {
country := ruleengine.MustPath("shipment", "country")
weight := ruleengine.MustPath("shipment", "weight_grams")
set := ruleengine.RuleSet{ID: "location-routing", Rules: []ruleengine.Rule{{
ID: "finland-heavy",
Priority: 100,
When: ruleengine.All(
ruleengine.Compare(ruleengine.OpEqual,
ruleengine.Variable(country), ruleengine.Literal(ruleengine.String("FI"))),
ruleengine.Compare(ruleengine.OpGreaterOrEqual,
ruleengine.Variable(weight), ruleengine.Literal(ruleengine.Int(1_000))),
),
}}}
plan, _, err := ruleengine.NewCompiler(ruleengine.DefaultLimits()).Compile(context.Background(), set)
if err != nil {
panic(err)
}
facts, err := ruleengine.NewContext(
ruleengine.Fact{Path: country, Value: ruleengine.String("FI"), Owner: ruleengine.OwnerResource},
ruleengine.Fact{Path: weight, Value: ruleengine.Int(1_500), Owner: ruleengine.OwnerResource},
)
if err != nil {
panic(err)
}
result := plan.Evaluate(context.Background(), facts)
fmt.Println(result.Decision == ruleengine.Matched)
fmt.Println(result.MatchedRules)
}
Output: true [finland-heavy]
Index ¶
- func CanonicalHash(set RuleSet) (string, error)
- func IsCode(err error, code Code) bool
- func MarshalCanonical(set RuleSet) ([]byte, error)
- func ParseJSON(data []byte, limits Limits) (RuleSet, []Diagnostic, error)
- type Code
- type Compiler
- func (compiler Compiler) CanonicalHash(set RuleSet) (string, error)
- func (compiler Compiler) Compile(ctx context.Context, set RuleSet) (Plan, []Diagnostic, error)
- func (compiler Compiler) CompileCached(ctx context.Context, set RuleSet, cache PlanCache) (Plan, []Diagnostic, error)
- func (compiler Compiler) MarshalCanonical(set RuleSet) ([]byte, error)
- func (compiler Compiler) ParseJSON(data []byte) (RuleSet, []Diagnostic, error)
- type ConflictStrategy
- type Context
- type Decision
- type Diagnostic
- type Error
- type Explanation
- type Fact
- type FactResolver
- type Kind
- type Limits
- type MemoryPlanCache
- type Operand
- type Operator
- type OperatorName
- type Owner
- type Path
- type Plan
- type PlanCache
- type Predicate
- type PredicateFunc
- type Result
- type Rule
- type RuleID
- type RuleSet
- type Severity
- type Signature
- type Value
- func (v Value) BoolValue() (bool, bool)
- func (v Value) DurationValue() (time.Duration, bool)
- func (v Value) FloatValue() (float64, bool)
- func (v Value) IntValue() (int64, bool)
- func (v Value) Interface() any
- func (v Value) Kind() Kind
- func (v Value) ListValue() ([]Value, bool)
- func (v Value) StringValue() (string, bool)
- func (v Value) TimeValue() (time.Time, bool)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CanonicalHash ¶
CanonicalHash returns the lowercase SHA-256 digest of MarshalCanonical.
func MarshalCanonical ¶
MarshalCanonical serializes a definition containing only built-in operators with stable ordering and field representation. Custom predicates cannot be serialized.
Types ¶
type Code ¶
type Code string
Code classifies errors without exposing fact values.
const ( // CodeInvalidLimit begins the stable machine-readable error code set. CodeInvalidLimit Code = "invalid_limit" // CodeInvalidPath reports a malformed fact path. CodeInvalidPath Code = "invalid_path" // CodeDuplicateFact reports a repeated fact path. CodeDuplicateFact Code = "duplicate_fact" // CodeInvalidFact reports a malformed fact value. CodeInvalidFact Code = "invalid_fact" // CodeInvalidRule reports a malformed rule definition. CodeInvalidRule Code = "invalid_rule" // CodeDuplicateRule reports a repeated rule identifier. CodeDuplicateRule Code = "duplicate_rule" // CodeUnknownOperator reports an unregistered operator. CodeUnknownOperator Code = "unknown_operator" // CodeTypeMismatch reports incompatible value kinds. CodeTypeMismatch Code = "type_mismatch" // CodeLimitExceeded reports an exhausted resource budget. CodeLimitExceeded Code = "limit_exceeded" // CodeEvaluation reports a predicate evaluation failure. CodeEvaluation Code = "evaluation_error" // CodeConflict reports incompatible matches or facts. CodeConflict Code = "conflict" // CodeCycle reports a derivation dependency cycle. CodeCycle Code = "cycle" // CodeInvalidJSON reports a malformed JSON AST. CodeInvalidJSON Code = "invalid_json" // CodeNotSerializable reports an unsupported canonical value. CodeNotSerializable Code = "not_serializable" // CodeCache reports a plan cache failure. CodeCache Code = "cache_error" )
type Compiler ¶
type Compiler struct {
// contains filtered or unexported fields
}
Compiler validates rule sets and produces immutable plans.
func NewCompiler ¶
NewCompiler creates a compiler containing only built-in operators.
func NewCompilerWithOperators ¶
NewCompilerWithOperators creates an isolated operator registry. Built-in names and duplicate custom names cannot be replaced.
func (Compiler) CanonicalHash ¶
CanonicalHash returns the lowercase SHA-256 digest of compiler's canonical representation, including definitions using its registered custom operators.
func (Compiler) CompileCached ¶
func (compiler Compiler) CompileCached(ctx context.Context, set RuleSet, cache PlanCache) (Plan, []Diagnostic, error)
CompileCached returns a matching cached plan or compiles and stores a new plan. Cache entries with a different embedded hash are ignored.
func (Compiler) MarshalCanonical ¶
MarshalCanonical serializes a definition with stable ordering and field representation using compiler's registered custom operators. Custom predicates cannot be serialized.
type ConflictStrategy ¶
type ConflictStrategy uint8
ConflictStrategy controls how ordered matches are selected.
const ( // FirstMatch selects only the first deterministically ordered match. FirstMatch ConflictStrategy = iota // CollectAll selects every unique matching rule. CollectAll // ErrorOnMultiple rejects more than one unique match. ErrorOnMultiple )
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is an immutable snapshot of supplied facts.
func NewContext ¶
NewContext builds a context with DefaultLimits.
func NewContextWithLimits ¶
NewContextWithLimits validates and copies all facts.
type Diagnostic ¶
Diagnostic describes a safe compile finding without operand values.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is a safe diagnostic error. Its message never contains fact values.
type Explanation ¶
Explanation records one bounded rule evaluation without fact values.
type FactResolver ¶
FactResolver supplies explicitly requested missing facts. Implementations must be deterministic; EvaluateResolved invokes paths in lexical order.
type Kind ¶
type Kind uint8
Kind is the exact runtime type of a Value.
const ( // KindMissing represents an absent path rather than a supplied value. KindMissing Kind = iota // KindNull represents an explicitly supplied null. KindNull // KindBool represents a boolean. KindBool // KindInt represents a signed 64-bit integer. KindInt // KindFloat represents a finite 64-bit floating-point number. KindFloat // KindString represents valid UTF-8 text. KindString // KindTime represents an instant with no monotonic clock reading. KindTime // KindDuration represents a time duration. KindDuration // KindList represents an ordered immutable list of values. KindList )
type Limits ¶
type Limits struct {
MaxRules int
MaxFacts int
MaxASTDepth int
MaxOperands int
MaxCollection int
MaxStringBytes int
MaxDefinitionBytes int
MaxRegexBytes int
MaxIdentifierBytes int
MaxTags int
MaxTagBytes int
MaxPathBytes int
MaxPathSegments int
MaxIterations int
MaxDerivedFacts int
MaxDiagnostics int
MaxExplanation int
EvaluationTimeout time.Duration
}
Limits bounds compilation and evaluation work. Zero values are invalid; callers should start with DefaultLimits and reduce values as needed.
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns conservative process-local limits.
type MemoryPlanCache ¶
type MemoryPlanCache struct {
// contains filtered or unexported fields
}
MemoryPlanCache is a bounded concurrency-safe LRU plan cache.
func NewMemoryPlanCache ¶
func NewMemoryPlanCache(capacity int) (*MemoryPlanCache, error)
NewMemoryPlanCache constructs a cache with a strict positive capacity.
func (*MemoryPlanCache) Len ¶
func (cache *MemoryPlanCache) Len() int
Len returns the current entry count.
type Operand ¶
type Operand interface {
// contains filtered or unexported methods
}
Operand resolves a typed value from a literal or fact variable.
type Operator ¶
type Operator interface {
Name() OperatorName
Signatures() []Signature
Evaluate(context.Context, Value, Value) (bool, error)
}
Operator is an explicitly registered, typed, concurrency-safe extension. Implementations must be deterministic and must honor context cancellation.
type OperatorName ¶
type OperatorName string
OperatorName is a stable operator identifier.
const ( // OpEqual begins the stable built-in operator name set. OpEqual OperatorName = "equal" // OpNotEqual tests exact inequality. OpNotEqual OperatorName = "not_equal" // OpLessThan tests strict lower ordering. OpLessThan OperatorName = "less_than" // OpLessOrEqual tests inclusive lower ordering. OpLessOrEqual OperatorName = "less_or_equal" // OpGreaterThan tests strict higher ordering. OpGreaterThan OperatorName = "greater_than" // OpGreaterOrEqual tests inclusive higher ordering. OpGreaterOrEqual OperatorName = "greater_or_equal" // OpIn tests list membership. OpIn OperatorName = "in" // OpNotIn tests list non-membership. OpNotIn OperatorName = "not_in" // OpContains tests substring or list membership. OpContains OperatorName = "contains" // OpStartsWith tests a string prefix. OpStartsWith OperatorName = "starts_with" // OpEndsWith tests a string suffix. OpEndsWith OperatorName = "ends_with" // OpMatches tests a bounded regular expression. OpMatches OperatorName = "matches" )
type Owner ¶
type Owner uint8
Owner describes which integration supplied a fact. It has no authorization semantics.
const ( // OwnerUnspecified records facts without supplied provenance. OwnerUnspecified Owner = iota // OwnerSubject records facts supplied by the evaluated subject. OwnerSubject // OwnerResource records facts supplied by the evaluated resource. OwnerResource // OwnerEnvironment records facts supplied by the environment. OwnerEnvironment )
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path identifies a fact without reflection or model discovery.
type Plan ¶
type Plan struct {
// contains filtered or unexported fields
}
Plan is an immutable, concurrency-safe execution plan.
func (Plan) EvaluateResolved ¶
EvaluateResolved resolves only required paths absent from the base context, validates every returned value, then evaluates the completed snapshot.
type PlanCache ¶
type PlanCache interface {
Get(context.Context, string) (Plan, bool, error)
Put(context.Context, string, Plan) error
}
PlanCache stores compiled immutable plans by canonical definition hash.
type Predicate ¶
Predicate evaluates supplied facts without side effects.
func Compare ¶
func Compare(operator OperatorName, left, right Operand) Predicate
Compare creates a typed binary comparison.
type PredicateFunc ¶
PredicateFunc adapts a function as an explicit extension predicate.
type Result ¶
type Result struct {
Decision Decision
MatchedRules []string
Explanation []Explanation
Errors []error
Duration time.Duration
DerivedFacts Context
}
Result is the complete inspectable evaluation result.
type Rule ¶
type Rule struct {
ID RuleID
Namespace string
Priority int
Tags []string
When Predicate
Derive []Fact
}
Rule is a proposition with stable metadata and optional derived facts.
type RuleSet ¶
type RuleSet struct {
ID string
Namespace string
Strategy ConflictStrategy
Rules []Rule
}
RuleSet is an independently compiled collection of rules.
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is a typed fact or operand value.
func (Value) DurationValue ¶
DurationValue returns the duration and whether the kind matches.
func (Value) FloatValue ¶
FloatValue returns the float and whether the kind matches.
func (Value) StringValue ¶
StringValue returns the string and whether the kind matches.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
adapters
|
|
|
math
module
|
|
|
measurement
module
|
|
|
temporal
module
|
|
|
Package jsonast exposes the bounded versioned JSON rule-definition DSL.
|
Package jsonast exposes the bounded versioned JSON rule-definition DSL. |