rule

package module
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 3 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

axon-rule

Composable business-rule predicates and a typed state machine for Go.

axon-rule provides two complementary systems:

  1. Rule predicates — typed, composable checks (Rule[T], AllOf, AnyOf, Not)
  2. State machine — guard-driven transitions built on top of those predicates (Machine[T], Instance[T])

Prerequisites

Build & Test

just test
just vet

Rule Predicates

Core types
Type Description
Rule[T] Interface: Check(T) Verdict
Verdict Result of a rule check: OK bool, Context any
New[T](fn) Create a Rule from a predicate function
Pass() Return a passing Verdict
FailWith(context) Return a failing Verdict with typed context
Combinators
AllOf[T](rules ...Rule[T]) Rule[T]   // passes when all rules pass
AnyOf[T](rules ...Rule[T]) Rule[T]   // passes when at least one rule passes
Not[T](rule Rule[T]) Rule[T]         // inverts a rule
AlwaysAllow[T]() Rule[T]             // always passes (useful as a default guard)
Quick example
type Order struct { Total float64; Approved bool }

type NoValue struct{}
type NotApproved struct{}

var (
    hasValue  = rule.New(func(o Order) rule.Verdict {
        if o.Total > 0 { return rule.Pass() }
        return rule.FailWith(NoValue{})
    })
    isApproved = rule.New(func(o Order) rule.Verdict {
        if o.Approved { return rule.Pass() }
        return rule.FailWith(NotApproved{})
    })
    canFulfil = rule.AllOf(hasValue, isApproved)
)

v := canFulfil.Check(Order{Total: 42.0, Approved: true})
// v.OK == true

State Machine

Types
Type Description
State Named state with optional Metadata map[string]any. Equality is name-based.
Transition[T] Edge from From State to To State, guarded by a Rule[T].
HistoryEntry Records a From, To, and Timestamp for each applied transition.
Machine[T] Immutable definition: initial state + transitions.
Instance[T] Mutable running instance of a Machine[T]. Single-owner (not goroutine-safe).
Machine API
// Construct
m := rule.NewMachine(initial, []rule.Transition[T]{...})

// Inspect
m.AvailableTransitions(current State, candidate T) []Transition[T]
m.TerminalStates() []State
m.Validate() error   // returns error if any state is unreachable from initial
Instance API
inst := rule.NewInstance(m)

inst.Current() State
inst.History() []HistoryEntry
inst.IsTerminal() bool

// Advance: apply first passing transition from current state
inst.Advance(candidate T) error

// AdvanceTo: move to a specific target state (guard must pass)
inst.AdvanceTo(target State, candidate T) error

Worked example: factory pipeline

The factory-floor build pipeline moves a build through five stages: backlog → scaffolding → building → qc → lamina

Each transition can be guarded by composed predicates.

package main

import (
    "fmt"
    "github.com/benaskins/axon-rule"
)

type Build struct {
    HasSpec     bool
    TestsPassed bool
    QCPassed    bool
}

type MissingSpec struct{}
type TestsNotPassed struct{}
type QCNotPassed struct{}

func main() {
    // States
    backlog     := rule.State{Name: "backlog"}
    scaffolding := rule.State{Name: "scaffolding"}
    building    := rule.State{Name: "building"}
    qc          := rule.State{Name: "qc"}
    lamina      := rule.State{Name: "lamina"}

    // Guards
    hasSpec := rule.New(func(b Build) rule.Verdict {
        if b.HasSpec {
            return rule.Pass()
        }
        return rule.FailWith(MissingSpec{})
    })
    testsPassed := rule.New(func(b Build) rule.Verdict {
        if b.TestsPassed {
            return rule.Pass()
        }
        return rule.FailWith(TestsNotPassed{})
    })
    qcPassed := rule.New(func(b Build) rule.Verdict {
        if b.QCPassed {
            return rule.Pass()
        }
        return rule.FailWith(QCNotPassed{})
    })

    m := rule.NewMachine(backlog, []rule.Transition[Build]{
        {From: backlog,     To: scaffolding, Guard: hasSpec},
        {From: scaffolding, To: building,    Guard: rule.AlwaysAllow[Build]()},
        {From: building,    To: qc,          Guard: testsPassed},
        {From: qc,          To: lamina,      Guard: rule.AllOf(testsPassed, qcPassed)},
    })

    if err := m.Validate(); err != nil {
        panic(err)
    }

    inst := rule.NewInstance(m)
    b := Build{HasSpec: true, TestsPassed: true, QCPassed: true}

    for !inst.IsTerminal() {
        if err := inst.Advance(b); err != nil {
            fmt.Println("blocked:", err)
            break
        }
        fmt.Println("→", inst.Current().Name)
    }
    // Output:
    // → scaffolding
    // → building
    // → qc
    // → lamina
}
Guard composition with combinators
// Require both tests and QC before entering lamina
readyForLamina := rule.AllOf(testsPassed, qcPassed)

// Accept a build if it has a spec OR was manually approved
canScaffold := rule.AnyOf(hasSpec, manuallyApproved)

// Block a build if it is flagged
notFlagged := rule.Not(isFlagged)

Documentation

Overview

Package rule provides composable business-rule predicates and a typed guard-driven state machine following the Specification pattern.

Class: primitive UseWhen: Validation logic, guard conditions, eligibility checks. Composable rules with structured failure reporting.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AllOfRule

type AllOfRule[T any] struct {
	// contains filtered or unexported fields
}

func AllOf

func AllOf[T any](rules ...Rule[T]) AllOfRule[T]

AllOf returns a Rule that is satisfied only when every inner rule passes. All rules are evaluated regardless of failures; violations are collected from every failing rule.

func (AllOfRule[T]) Check

func (a AllOfRule[T]) Check(candidate T) Verdict

func (AllOfRule[T]) Evaluate

func (a AllOfRule[T]) Evaluate(candidate T) Violations

Evaluate runs all rules and collects violations from every failing rule.

type AnyOfRule

type AnyOfRule[T any] struct {
	// contains filtered or unexported fields
}

func AnyOf

func AnyOf[T any](rules ...Rule[T]) AnyOfRule[T]

AnyOf returns a Rule that is satisfied when at least one inner rule passes. Short-circuits on the first success.

func (AnyOfRule[T]) Check

func (a AnyOfRule[T]) Check(candidate T) Verdict

func (AnyOfRule[T]) Evaluate

func (a AnyOfRule[T]) Evaluate(candidate T) Violations

Evaluate returns no violations if any rule passes; otherwise collects all.

type HistoryEntry

type HistoryEntry struct {
	From      State
	To        State
	Timestamp time.Time
}

HistoryEntry records a single state transition with its timestamp.

type Instance

type Instance[T any] struct {
	// contains filtered or unexported fields
}

Instance[T] is a running instance of a Machine[T]. It tracks the current state and transition history. Instance is not safe for concurrent use; it follows a single-owner pattern.

func NewInstance

func NewInstance[T any](machine *Machine[T]) *Instance[T]

NewInstance creates an Instance starting at the machine's initial state.

func (*Instance[T]) Advance

func (i *Instance[T]) Advance(candidate T) error

Advance evaluates candidate against all available transitions from the current state and applies the first passing one. Returns an error if no transition is available.

func (*Instance[T]) AdvanceTo

func (i *Instance[T]) AdvanceTo(target State, candidate T) error

AdvanceTo finds the transition from the current state to target, checks its guard, and applies it. Returns an error if the transition is not found or the guard fails.

func (*Instance[T]) Current

func (i *Instance[T]) Current() State

Current returns the current state.

func (*Instance[T]) History

func (i *Instance[T]) History() []HistoryEntry

History returns a copy of the transition history.

func (*Instance[T]) IsTerminal

func (i *Instance[T]) IsTerminal() bool

IsTerminal reports whether the current state is a terminal state.

type Machine

type Machine[T any] struct {
	// contains filtered or unexported fields
}

Machine[T] is an immutable state machine definition. It stores the initial state and the full set of transitions.

func NewMachine

func NewMachine[T any](initial State, transitions []Transition[T]) *Machine[T]

NewMachine creates a Machine with the given initial state and transitions. The transitions slice is copied so the machine is immutable after construction.

func (*Machine[T]) AvailableTransitions

func (m *Machine[T]) AvailableTransitions(current State, candidate T) []Transition[T]

AvailableTransitions returns all transitions from current whose guard passes for candidate.

func (*Machine[T]) TerminalStates

func (m *Machine[T]) TerminalStates() []State

TerminalStates returns all states that have no outgoing transitions. A state is terminal if it appears in any transition (as From or To) but never as From.

func (*Machine[T]) Validate

func (m *Machine[T]) Validate() error

Validate checks the machine for structural errors. It returns an error if any state is not reachable from the initial state.

type Negated

type Negated struct{}

Negated is the violation context produced when a Not rule fails.

type NotRule

type NotRule[T any] struct {
	// contains filtered or unexported fields
}

func Not

func Not[T any](r Rule[T]) NotRule[T]

Not returns a Rule that inverts another rule. It is satisfied when the inner rule fails. Produces a Negated violation when the inner rule passes.

func (NotRule[T]) Check

func (n NotRule[T]) Check(candidate T) Verdict

func (NotRule[T]) Evaluate

func (n NotRule[T]) Evaluate(candidate T) Violations

Evaluate produces a violation when the inner rule passes (i.e. Not fails).

type Rule

type Rule[T any] interface {
	Check(candidate T) Verdict
}

Rule defines a single business rule for a candidate of type T.

func AlwaysAllow

func AlwaysAllow[T any]() Rule[T]

AlwaysAllow returns a Rule whose Check always returns a passing Verdict.

func New

func New[T any](fn func(T) Verdict) Rule[T]

New creates a Rule from a predicate function.

type State

type State struct {
	Name     string
	Metadata map[string]any
}

State represents a named state in a state machine. Equality is based on Name only; Metadata is informational.

func (State) Equal

func (s State) Equal(other State) bool

Equal reports whether two States are equal by name.

type Transition

type Transition[T any] struct {
	From  State
	To    State
	Guard Rule[T]
}

Transition defines a guarded edge between two states. Guard is evaluated against the subject to determine if the transition is allowed.

type Verdict

type Verdict struct {
	OK      bool
	Context any
}

Verdict is the return value of a predicate function.

func FailWith

func FailWith(context any) Verdict

FailWith returns a failed verdict with a typed context. The context type name becomes the violation code.

func Pass

func Pass() Verdict

Pass returns a successful verdict.

type Violation

type Violation struct {
	Code    string
	Context any
}

Violation records a rule that was not satisfied. Code is derived from the type name of Context.

type Violations

type Violations struct {
	Items []Violation
}

Violations holds the outcome of evaluating rules against a candidate.

func (Violations) Codes

func (v Violations) Codes() []string

Codes returns the codes of all recorded violations.

func (Violations) IsValid

func (v Violations) IsValid() bool

IsValid returns true when no violations were recorded.

Jump to

Keyboard shortcuts

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