rulesengine

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 25 Imported by: ? modules, 0 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.

Documentation

Overview

Package rules is a declarative pipeline engine: business logic lives in Rule structs (one file = one rule), composition lives in YAML, and the Engine sews them together at boot.

Why

Inspired by the rule engine in dataplan.de's API. Same idea — each Rule is a single, named, reusable unit; pipelines stitch them into bigger flows — but the composition is declared in YAML instead of fluent Go calls. Two consequences worth knowing:

  • The YAML can change the order of steps, add branches, skip a rule under a condition (when:), without touching the Go code that implements the rules.
  • All validation happens at Engine.Build: missing rules, overlapping writes inside a parallel group, unparseable `when:` expressions — every error you can catch statically surfaces at boot, not during the first request.

Flow

+----------+   Run(ctx, req, "name")   +-----------------+
| http     | ------------------------> | Engine          |
| handler  |                           |                 |
|          | <------ Result (dict) --- |   * registry    |
+----------+                           |   * pipelines   |
                                       |   * expr cache  |
                                       +-----------------+
                                                |
                                                v
                                       +-----------------+
                                       | Executor        |
                                       |   sequence ─┐   |
                                       |   parallel ─┤   |
                                       |   on_succ. ─┤   |
                                       |   on_fail. ─┘   |
                                       +-----------------+
                                                |
                                       per step v
                                       +-----------------+
                                       | Context         |
                                       |   .Request      |
                                       |   .Data (sync)  |
                                       |   .Logger       |
                                       +-----------------+

Quickstart

//go:embed pipelines/*.yaml
var pipelinesFS embed.FS

eng, err := rules.NewEngine().
    Register(
        &myrules.FetchOrganization{DS: ds},
        &myrules.LoadPlan{DS: ds},
        &myrules.SetAccessFlag{},
    ).
    Load(pipelinesFS, "pipelines/*.yaml").
    Build()
if err != nil { /* fail boot */ }

mux.Handle("GET /access", eng.HTTPHandler("org_access_check"))

// or inline, when the caller wants the Result to drive code:
res, err := eng.Run(r.Context(), r, "org_access_check")
var out AccessDecision
_ = res.Bind(&out)

Pipeline YAML

pipelines:
  org_access_check:
    pick: [access_granted, plan]
    flow:
      - parallel:
          - name: fetch_organization
            with: { source: header, key: X-Org-Id }
            on_failure:
              - name: deny_access
          - name: fetch_user
      - name: load_plan
        when: "data.organization != nil"
      - name: set_access_flag
        with: { min_plan: pro }

Strict mode: unknown YAML keys fail at boot. Env interpolation (${HB_FOO:-default}) is applied before parsing — same syntax rules as web/render/config.

Rule contract

A rule is a Go type that implements:

type Rule interface {
    Name() string         // matches `name:` in YAML
    Writes() []string     // keys this rule sets in Context.Data
    Run(c *Context) error // do the work
}

Writes is what makes parallel groups safe by construction: at Build time, the Engine checks that no two rules in the same `parallel:` block declare a key in common. Race-free without rule authors having to think about it.

Run signals:

  • return nil → success, next step runs
  • return rules.Skip → silently skip (when: conditions also short-circuit before Run is even called)
  • return rules.Abort("reason") → halt the pipeline; the reason ends up in the Result and is mapped to a 4xx by HTTPHandler
  • return err → real failure; on_failure runs if set, otherwise the pipeline stops and the error propagates

Index

Constants

This section is empty.

Variables

View Source
var Skip = errors.New("rules: skip")

Skip is the sentinel a Rule returns from Run when it should be silently skipped — the pipeline continues with the next step instead of treating the absence as a failure. Use this when the rule's preconditions don't hold and there's nothing meaningful to do (e.g. "no org id on the request, nothing to fetch").

For the YAML-driven equivalent see the `when:` field in pipeline schemas — that short-circuits before Run is even called.

Functions

func Abort

func Abort(reason string) error

Abort halts the pipeline cleanly with a client-facing reason. No further steps run, the error propagates up to Engine.Run, and HTTPHandler maps it to a 4xx with the reason in the body. Use it when the input is well-formed but the business logic decided "no" — unauthorized, plan too low, quota exceeded — not for unexpected failures (return a plain error for those).

The string goes ON THE WIRE: don't put user IDs, internal rule names, stack traces, or anything else operator-only here. For log-only context, use AbortWithInternal.

Empty reason is normalised to "aborted" so the response body never has a missing field.

func AbortInternal

func AbortInternal(err error) string

AbortInternal returns the operator-only message attached via AbortWithInternal, or "" if err isn't an abort or the abort carried no internal context. Intended for log enrichment in the executor; do not render it on the wire — it may contain detail you wouldn't expose to a client.

func AbortReason

func AbortReason(err error) string

AbortReason returns the CLIENT-FACING reason an Abort-error was created with, or "" if err is not an abort. Safe to render to the wire; HTTPHandler uses this for the response body.

func AbortWithInternal

func AbortWithInternal(public, internal string) error

AbortWithInternal is Abort + an operator-only log message. `public` is the client-facing reason — same semantics as Abort. `internal` lands in the structured log line written by the executor and never crosses the HTTP boundary, so it's safe to include identifiers, IDs, "user X lacks role Y in org Z" detail.

Use it when the public reason should stay generic ("forbidden") but the on-call needs the specifics to debug from logs.

func IsAbort

func IsAbort(err error) bool

IsAbort reports whether err is the result of an Abort call (or wraps one). Use it when you need to branch on abort-vs-real-error outside the HTTP handler.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable reports whether err is or wraps a Retryable marker. Companion to RetryableError for callers that want to inspect an error without rebuilding the chain. The engine uses this internally too — keeping the predicate in one place.

func RetryableError

func RetryableError(err error) error

RetryableError wraps err in a Retryable marker so the engine's retry loop knows it can re-invoke the rule. Use it inside rules' Run methods when a transient failure (network blip, timeout, "service unavailable") should trigger a backoff retry rather than a hard 500:

if err := r.DS.Get(ctx, id); err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        return rulesengine.RetryableError(err)
    }
    return err
}

A nil err returns nil — convenient for one-liner returns.

Types

type Context

type Context struct {
	// Request is the HTTP request that triggered the pipeline. Always
	// non-nil for HTTP entry points; the inline form (Engine.Run with
	// req=nil) gets a stub *http.Request the engine constructs so
	// rules don't have to nil-check.
	Request *http.Request

	// Logger is the per-run logger. Pre-bound with pipeline name and
	// any correlation IDs the parent http.Request context carries
	// (request_id, device_id, organization_id from core/log).
	// Rules should use this instead of log.Default() so their lines
	// show up under the right pipeline in aggregated logs.
	Logger *log.Logger
	// contains filtered or unexported fields
}

Context is the per-pipeline-run state shared across every Rule in a flow. It's a value the Engine creates once at the top of Run and threads through every step; rules read from it, write into Data, and signal control via the error they return.

Concurrency: parallel groups run rules on multiple goroutines simultaneously. Data is therefore behind a sync.Map encapsulated in this type — callers go through Get/Set, not the map directly. The Engine validates at Build time that no two parallel rules declare overlapping Writes(), so the only legitimate races (different keys at the same time) are safe.

func NewContext

func NewContext(ctx context.Context, req *http.Request) *Context

NewContext builds a *Context outside of Engine.Run — useful for tests that exercise a single rule, or for callers that want to drive a rule manually without composing a pipeline. The Engine uses this internally; the constructor is exported so external callers don't have to reimplement the sync.Map plumbing.

ctx must be non-nil (use context.Background() if you have no real context). req may be nil; rules that read it must nil-check.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the cancellation/deadline-bearing context.Context for the running pipeline. Use it for outgoing network calls, database queries, etc., so rules cancel cleanly when the request is aborted upstream.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get returns the value stored under key by a previous rule. The boolean disambiguates "key was set to nil" from "key was never set" — most callers ignore it.

func (*Context) Set

func (c *Context) Set(key string, v any)

Set stores v under key. The Engine's Build-time validation guarantees that within a parallel group no two rules write the same key, so Set never has to coordinate beyond what sync.Map already provides.

If this Context was derived for a tracked rule call, Set also records the key in the observer so the executor's Writes()-contract verification can compare the recorded set to the rule's declaration after Run returns.

type Engine

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

Engine is the compiled, ready-to-run pipeline registry. Built once at boot via NewEngine().Register(...).Load(...).Build(), then reused for every request. Goroutine-safe after Build — the internal maps are not mutated.

Lifecycle:

  1. NewEngine() — empty builder.
  2. Register(rules...) — add Rule instances. Each rule's Name() becomes the lookup key; duplicates are caught at Build.
  3. Load(fsys, glob) — schedule YAML files for parsing. Multiple calls accumulate; duplicate pipeline names across files are caught at Build.
  4. Build() — actually parse the YAML, resolve names against the registry, compile every `when:` expression, and check parallel groups for overlapping Writes(). Every error you can catch statically surfaces here.

After Build, only Run / HTTPHandler are valid calls.

func NewEngine

func NewEngine() *Engine

NewEngine returns an empty Engine builder. Chain Register, Load and Build to make it usable.

func (*Engine) Build

func (e *Engine) Build() error

Build resolves every staged pipeline against the registered rules, compiles `when:` expressions, and runs the parallel overlap check. Idempotent: calling Build twice returns the cached result (success or error) — so callers can re-trigger Build in a dev hot-reload loop without paying the parse cost twice.

Errors at this stage are configuration bugs the operator should fix in YAML or in the rules table: missing rule name, ambiguous step shape, conflicting writes in a parallel group, malformed `when:` expression. The Engine refuses to Run until Build succeeds.

func (*Engine) HTTPHandler

func (e *Engine) HTTPHandler(pipeline string) http.HandlerFunc

HTTPHandler returns an http.HandlerFunc that runs the named pipeline against the incoming request and serialises the Result as JSON. The handler is the wire-level entry point — composing it with the canonical middleware bundle (RequestID, Recover, AccessLog) is the caller's job:

mux.Handle("GET /access", eng.HTTPHandler("org_access_check"))

Status code mapping:

  • rule succeeded → 200 OK + Result body
  • rule returned Abort → 403 Forbidden + {"reason": "...", "_abort": "..."}
  • rule returned an error → 500 Internal Server Error + {"error": "..."}
  • pipeline not found → 500 (a missing pipeline is a config bug, not a request bug — the operator gets the noisy log)

Build() must have completed successfully before this handler serves traffic; if Build hasn't been called yet, the first request triggers it lazily (Run does this for us).

func (*Engine) Load

func (e *Engine) Load(fsys fs.FS, glob string) *Engine

Load schedules YAML pipeline files at fsys/glob for parsing during Build. Call it once per (fsys, glob) tuple; multiple calls across different filesystems are merged. Resolution happens at Build, not here — Load itself never fails.

func (*Engine) Plan

func (e *Engine) Plan(ctx context.Context, req *http.Request, pipelineName string, data map[string]any) ([]PlanStep, error)

Plan returns a static view of `pipelineName` — what steps would execute (and which `when:` guards would pass) given the data the caller seeds. It does NOT invoke any Rule.Run, so the result is safe to call against arbitrary inputs without side effects.

The static view is most useful for:

  • Debugging branchy pipelines: "if I feed this Data, which steps fire and which `when:` guards block?"
  • PR review: rendering the resolved flow next to the diff so reviewers can read it without simulating the YAML.
  • Tooling (future CLI in service-tools).

`data` is optional — pass nil for an "empty Data" plan, useful when you only want to see the static structure and don't need the `when:` results to reflect a particular request state. Passing a populated map evaluates `when:` against it so the returned WhenResult fields are meaningful for that input.

`req` is also optional. Rules that read from `request.headers` in their `when:` need a non-nil req for the evaluation to match what would happen at runtime.

Errors:

  • "unknown pipeline" if the name isn't registered (same wording Engine.Run uses).
  • engine not built — same lazy-build behaviour as Run.

func (*Engine) Register

func (e *Engine) Register(rules ...Rule) *Engine

Register adds rules to the engine's lookup table. Duplicate Name() values are tolerated here (last-write-wins) and only flagged when there's a legitimate ambiguity at Build — for now it just overwrites, since the typical service registers exactly one instance per Rule type.

Returns the receiver so calls chain naturally:

eng := rules.NewEngine().
    Register(&FetchOrg{DS: ds}, &LoadPlan{DS: ds}).
    Load(fs, "pipelines/*.yaml")

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, req *http.Request, pipelineName string) (Result, error)

Run executes the named pipeline against req and returns the Result (Context.Data filtered through pipeline.pick if declared).

Errors:

  • rules.IsAbort(err) → business logic returned "no" cleanly; callers usually map this to a 4xx with AbortReason(err).
  • *RuleError → a rule's Run returned a non-sentinel error; wrap in 500 by default.
  • everything else → engine-level failure (unknown pipeline, `when:` evaluation error, etc.). Almost always 500.

req may be nil; rules that read c.Request must nil-check, but most don't (the pipeline is usually driven by HTTPHandler).

func (*Engine) Snapshot

func (e *Engine) Snapshot() Snapshot

Snapshot returns the current Snapshot. Safe to call any time after Build; the engine's pipeline map is set once and never mutated after, so concurrent Run / Snapshot calls share the underlying data without locks. Returns a Snapshot with no pipelines if the engine has none.

type PipelineChange

type PipelineChange struct {
	// Pipeline is the pipeline's name (key in the engine's
	// pipeline map).
	Pipeline string

	// Kind is "added" | "removed" | "modified".
	//   - "added"    → pipeline appeared in next that wasn't in prev.
	//   - "removed"  → pipeline gone in next that was in prev.
	//   - "modified" → pipeline present in both with a different
	//     set of step fingerprints; AddedRules / RemovedRules /
	//     ChangedRules carry the specifics.
	Kind string

	// AddedRules are rule names that appear in next but not prev,
	// deduplicated. Only populated for Kind == "modified".
	AddedRules []string

	// RemovedRules are rule names in prev not in next, deduplicated.
	// Only populated for Kind == "modified".
	RemovedRules []string

	// ChangedRules are rule names present in both prev and next
	// but with at least one fingerprint whose ConfigHash differs
	// (`with:` or `when:` changed). Deduplicated. Only populated
	// for Kind == "modified".
	ChangedRules []string
}

PipelineChange describes how one pipeline differs between two snapshots. Produced by Snapshot.Diff. Kind discriminates the three transitions; the other fields are populated only for the kind they belong to.

type PlanStep

type PlanStep struct {
	// Pipeline is the name of the pipeline this step belongs to.
	// Always set, mirrors the argument to Engine.Plan.
	Pipeline string

	// Depth is the indentation level — 0 for top-level entries in
	// flow, +1 for each parallel / sequence / on_success /
	// on_failure level descended into. Used to render trees.
	Depth int

	// Kind is "rule" | "parallel" | "sequence" | "branch" where
	// "branch" wraps on_success / on_failure containers (their
	// Name carries which one).
	Kind string

	// Name is the rule name for Kind == "rule", "" for the group
	// containers, and "on_success" / "on_failure" for branches.
	Name string

	// When is the raw expression source from YAML, "" if none.
	When string

	// WhenResult records the static evaluation of When at plan
	// time: nil if there's no When, *true if it evaluated truthy
	// against the supplied Data, *false otherwise. A When that
	// errored stays nil with WhenError populated.
	WhenResult *bool

	// WhenError holds the evaluation error if When could not be
	// evaluated against the supplied Data (typical: a referenced
	// field on `data` is missing). "" when the expression evaluated
	// cleanly or the step has no When.
	WhenError string

	// With is the YAML `with:` config attached to a rule step. Nil
	// for group containers.
	With StepConfig

	// Writes lists the keys a rule step declared in Writes(). Nil
	// for group containers.
	Writes []string
}

PlanStep is one node in the static view of a pipeline produced by Engine.Plan. The slice form is a DFS pre-order walk: a parent (parallel / sequence / a rule with branches) appears before its children, with Depth incremented for each level of nesting. That layout makes "render as an indented tree" trivial.

type Result

type Result map[string]any

Result is the value Engine.Run returns: the snapshot of Context.Data after the pipeline finishes, optionally filtered through the pipeline's `pick:` list. Plain map[string]any so the HTTP handler can json.Marshal it without ceremony, and callers inside the app can Bind it to a typed struct when they want strong typing.

func (Result) Bind

func (r Result) Bind(v any) error

Bind decodes the Result into v via a JSON round-trip. Convenient for turning the dict the pipeline produced into a typed model the rest of the code already understands:

var d AccessDecision
if err := res.Bind(&d); err != nil { ... }

v must be a pointer to a struct (or any json-unmarshalable target). The round-trip is the price of keeping Result a plain map without committing to a reflection-based mapper — JSON tags on the destination struct are honoured exactly as everywhere else in the repo.

func (Result) Pick

func (r Result) Pick(keys ...string) Result

Pick returns a Result containing only the named keys. Missing keys are silently omitted — the contract is "give me at most these fields", not "fail if any is absent". Use it to whittle an internal Context.Data down to the response payload (the Engine applies the pipeline's `pick:` list this way).

Empty keys = return Result unchanged (a copy, not the receiver, so the caller can't mutate the original through it).

type Retryable

type Retryable interface {
	Retryable() bool
}

Retryable is the opt-in interface a rule's error type can implement to signal "this is transient — try again". The executor checks it via errors.As inside the retry loop, so any error in the chain can carry the marker (typically the bottom of a wrap stack).

Without a Retryable in the chain (and without a context.DeadlineExceeded from a per-attempt timeout) the engine treats the failure as permanent and propagates immediately.

type Rule

type Rule interface {
	Name() string
	Writes() []string
	Run(c *Context, with StepConfig) error
}

Rule is the unit of business logic the engine executes. Implement it on a struct that carries the dependencies the rule needs (datasource, config, clock, …) and register an instance with Engine.Register.

Three methods, no surprises:

  • Name returns the identifier YAML pipelines reference under `name:`. Convention is snake_case — lowercase + underscore: "fetch_organization", "load_plan", "set_access_flag". Must be unique per Engine. The same convention applies to pipeline names; nothing in the engine layer uses hyphens.
  • Writes returns every key this rule sets in Context.Data. The Engine uses this list at Build time to verify that no two rules sharing a `parallel:` block declare overlapping keys — that's how parallel execution stays race-free without rule authors thinking about locks. Return nil if the rule only reads or only signals via error.
  • Run does the work. with carries the YAML `with:` config for this specific step invocation; rules that don't take config can ignore it. See errors.go for the contract on Skip and Abort sentinels.

Rules should be safe to share across goroutines — the Engine reuses the same instance for every request. Per-request state goes in Context.Data; per-step config arrives via the with parameter. Nothing on the receiver should mutate during Run.

type RuleError

type RuleError struct {
	Rule string
	Err  error
}

RuleError wraps an error returned from Run with the rule name that produced it. The Engine wraps every non-Skip, non-Abort error this way so log lines and HTTP responses can identify which rule failed without the rule itself having to format that into its message.

func (*RuleError) Error

func (e *RuleError) Error() string

func (*RuleError) Unwrap

func (e *RuleError) Unwrap() error

type Snapshot

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

Snapshot is an opaque view of every pipeline currently compiled in the engine. Built by Engine.Snapshot, consumed by Diff for the dev hot-reload log. Internals (per-pipeline digests, per- step fingerprints) are unexported because no caller needs to introspect them — the public surface is "take a snapshot, diff it against another".

Shape is intentionally flat under the hood: groups (parallel / sequence / pipeline) and branches (on_success / on_failure) are recursively walked in DFS order so the diff sees every rule invocation regardless of nesting. That's enough for "what changed" logs; a future Plan-style API can expose the full tree alongside this one rather than fattening Snapshot.

func (Snapshot) Diff

func (s Snapshot) Diff(prev Snapshot) []PipelineChange

Diff returns the set of pipelines that changed between prev and s — pipelines added in s, removed from prev, or whose step fingerprints differ. Pipelines byte-equal across both snapshots are omitted.

Ordering: returned slice is sorted by pipeline name so callers (the dev hot-reload log) emit a stable, easy-to-scan sequence.

type StepConfig

type StepConfig map[string]any

StepConfig is a typed view over the `with:` map declared on a YAML step. Stored as map[string]any (yaml.v3's default for untyped maps) and accessed via the typed helpers below so rule code reads `with.String("key")` instead of casting any.

func (StepConfig) Bool

func (s StepConfig) Bool(key string) bool

Bool returns the value at key as a bool, or false if missing or not a bool. Mirrors String for the boolean YAML scalar.

func (StepConfig) Has

func (s StepConfig) Has(key string) bool

Has reports whether key is present in the config map, regardless of its value type. Lets rules distinguish "key set to false" from "key absent" when the difference matters.

func (StepConfig) Int

func (s StepConfig) Int(key string) int

Int returns the value at key as an int. YAML.v3 decodes integer scalars as int (not int64) into map[string]any, so this is the natural fetch path. Missing or non-int → 0.

func (StepConfig) String

func (s StepConfig) String(key string) string

String returns the value at key as a string, or "" if missing or not a string. Use it for header names, source identifiers, etc. — the common YAML scalar.

Jump to

Keyboard shortcuts

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