cel

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Overview

Package cel is the CEL environment of the factory's rules and the runtime expressions of the catalog (design/workstreams/dispatcher-core/LLD/cel-and-expressions.md):

  • Env declares the typed environment (event, actor, item, run, approval, provider, params, inputs, task, now) and the custom functions, and compiles expressions once (cached).
  • Program evaluates a where (EvalBool) or a value (EvalValue) under the cost limit and the evaluation timeout, returning typed errors (never panicking).
  • CompileTree and EvalTree handle "=CEL" leaves in YAML trees (dispatch.inputs, set).
  • MergeParams, Substitute and SubstituteRule do the "{{ params.x }}" substitution of catalog load.

The package is pure: no I/O and no clock. `now` comes from the caller in the Activation.

Index

Constants

View Source
const (
	// DefaultCostLimit is the runtime cost limit of one evaluation (cel.CostLimit).
	DefaultCostLimit uint64 = 10_000
	// DefaultTimeout bounds one evaluation's wall-clock time.
	DefaultTimeout = 50 * time.Millisecond
	// DefaultInterruptCheckFrequency is how many comprehension iterations run between checks
	// of the evaluation context (cel.InterruptCheckFrequency).
	DefaultInterruptCheckFrequency uint = 100
)

Limits (LLD §Compilation and limits).

View Source
const (
	VarEvent    = "event"
	VarActor    = "actor"
	VarItem     = "item"
	VarRun      = "run"
	VarApproval = "approval"
	VarProvider = "provider"
	VarParams   = "params"
	VarInputs   = "inputs"
	VarTask     = "task"
	VarNow      = "now"
)

Variable names of the environment.

View Source
const EstimateSizeHint = 100

EstimateSizeHint is the size the cost estimate assumes for every list, map and string that comes from the activation (cel-go cannot know them statically).

View Source
const ExprPrefix = "="

ExprPrefix starts a runtime CEL value: "=event.object.ref".

Variables

View Source
var (
	// ErrMissing: a map key, attribute or list index is absent ("no such key", "index out of
	// bounds").
	ErrMissing = errors.New("missing key or attribute")
	// ErrType: an operator or function got a value of the wrong type ("no such overload"), or
	// a where returned something other than a bool, or a value is not a YAML value.
	ErrType = errors.New("wrong type")
	// ErrCostLimit: the evaluation cost went over the environment's cost limit.
	ErrCostLimit = errors.New("cost limit exceeded")
	// ErrTimeout: the evaluation ran longer than the environment's timeout.
	ErrTimeout = errors.New("evaluation timeout")
	// ErrNotCompiled: EvalTree found a "=" leaf that is not in the ProgramIndex.
	ErrNotCompiled = errors.New("expression not compiled")
)

Sentinel causes, matched with errors.Is on an *EvalError.

View Source
var (
	// ErrUnknownParam: a placeholder or an override names a param the rule doesn't declare.
	ErrUnknownParam = errors.New("unknown param")
	// ErrPlaceholder: a "{{ … }}" that is not "{{ params.<name> }}".
	ErrPlaceholder = errors.New("invalid placeholder")
	// ErrInterpolate: a param embedded in a longer string is a map, a list or null.
	ErrInterpolate = errors.New("param cannot be interpolated into a string")
)

Sentinel causes of a *ParamError, matched with errors.Is.

View Source
var ErrParamType = errors.New("substituted value has the wrong type")

ErrParamType: a substituted value doesn't fit the field it lands in, e.g. a string param in dispatch.harness, which wants an object or an expression.

Functions

func CELSource

func CELSource(s string) (src string, ok bool)

CELSource reports whether s is a "=CEL" value and returns its CEL source (s without the "="). A literal string that starts with "=" is written with a backslash, `\=` (in YAML double quotes, "\\=..."); it is not CEL.

func EvalTree

func EvalTree(ctx context.Context, v any, a Activation, progs ProgramIndex) (any, error)

EvalTree returns a copy of v in which every "=CEL" leaf is replaced by its value and every literal string is unescaped (Unescape); other values pass through unchanged. The programs come from progs. v itself is never modified.

The first failing leaf (map keys sorted) stops the walk: its *EvalError has Path set, and is ErrNotCompiled when the leaf is not in progs. The rule engine skips the whole rule's actions on any error (LLD §Evaluation).

func MergeParams

func MergeParams(declared, defaults, overrides map[string]any) (map[string]any, error)

MergeParams returns the effective params of a rule in a RuleSet: the rule's declared params (with their defaults), then the RuleSet's defaults, then the RuleSet's overrides for the rule; later layers win, a whole top-level value at a time (catalog LLD: rule params ← ruleset defaults ← ruleset overrides[rule]). A default for a param the rule doesn't declare is ignored; an override for one is a *ParamError with ErrUnknownParam (one per key, joined). The inputs are not modified.

func Substitute

func Substitute(v any, params map[string]any) (any, error)

Substitute returns a copy of v in which every "{{ params.<name> }}" in a string leaf is replaced:

  • a string that is exactly one placeholder becomes the param's value, keeping its type (harness: "{{ params.harness }}" becomes the harness object);
  • otherwise each placeholder is replaced by the param formatted as text (strings as they are, numbers and bools in their YAML form); a map, list or null param there is an error (ErrInterpolate).

Substituted text is not scanned again. Map keys are not substituted. A placeholder that is not "params.<name>" is ErrPlaceholder; an undeclared name is ErrUnknownParam. Every failing leaf is reported (joined *ParamError, Path set); v is not modified.

func SubstituteRule

func SubstituteRule(r *v1alpha1.Rule, params map[string]any) (*v1alpha1.Rule, error)

SubstituteRule returns a copy of r whose spec.actions have had Substitute applied with params (normally MergeParams' result), decoded back strictly into v1alpha1 types and validated. So harness: "{{ params.harness }}" becomes an ExprOr holding the object, and a param of the wrong type for its field is a *ParamError with ErrParamType. Only the actions are substituted (LLD: "any string in a Rule's actions"); the other fields of the copy are shared with r, which is not modified.

func Unescape

func Unescape(s string) string

Unescape returns the literal a string stands for: one leading backslash is dropped from a string that is backslashes followed by "=" (`\=x` → `=x`, `\\=x` → `\=x`). Other strings are returned unchanged. EvalTree applies it to every literal string leaf.

Types

type Activation

type Activation struct {
	Event, Actor, Item, Run, Approval, Provider, Params, Inputs, Task map[string]any
	Now                                                               time.Time
}

Activation is the input of one evaluation. The maps hold YAML/JSON values (map[string]any, []any, string, bool, numbers, nil); a nil map is an empty one. Now is the caller's clock reading.

type Code

type Code string

Code classifies an error for decisions and metrics ("error: <code>: <msg>").

const (
	// CodeParse: the expression is not valid CEL syntax.
	CodeParse Code = "cel.parse"
	// CodeCheck: the expression does not type-check against the environment (unknown variable
	// or function, wrong argument types, a where that cannot return bool).
	CodeCheck Code = "cel.check"
	// CodeEval: evaluation failed (missing key, wrong type, a function error).
	CodeEval Code = "cel.eval"
	// CodeLimit: evaluation exceeded the cost limit or the evaluation timeout.
	CodeLimit Code = "cel.limit"
	// CodeCanceled: the caller's context was done before evaluation finished.
	CodeCanceled Code = "cel.canceled"
)

Error codes.

type CompileError

type CompileError struct {
	Code Code
	// Expr is the CEL source, without the "=" prefix of a value leaf.
	Expr string
	// Path is the leaf's path in the tree given to CompileTree ("inputs.issue"); empty for
	// Compile.
	Path   string
	Issues []Issue
}

CompileError reports an expression that does not parse (CodeParse) or type-check (CodeCheck).

func (*CompileError) Error

func (e *CompileError) Error() string

type Env

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

Env is the CEL environment. It is safe for concurrent use. Compiled programs are cached per Env, keyed by source and kind; the cache is never evicted, so long-lived processes create one Env per catalog snapshot.

func NewEnv

func NewEnv(opts ...Option) (*Env, error)

NewEnv returns the environment of the LLD: the variables as map(string, dyn) (now is a timestamp), the CEL standard library and the custom functions item.count, item.lastRun, hash, semver.bump and glob, cel-go's two-variable comprehensions (all, exists, existsOne, transformList, transformMap and transformMapEntry with an index or key and a value: a rule builds a map from a list with list.transformMapEntry(i, v, {k: v})) and optional types (m[?k].hasValue() tests a key that isn't an identifier, at a constant estimated cost where `k in m` on a dyn value is estimated as a list scan). Numbers compare across int and double.

func (*Env) Compile

func (e *Env) Compile(src string, kind ExprKind) (*Program, error)

Compile parses and type-checks src as kind, or returns the cached Program. Errors are *CompileError (CodeParse or CodeCheck); a Where whose type is known not to be bool is a CodeCheck error (a dyn result is checked when evaluated).

func (*Env) CompileTree

func (e *Env) CompileTree(v any, idx ProgramIndex) error

CompileTree compiles every "=CEL" string leaf of v (maps, lists and scalars, as decoded from YAML) as a Value and adds it to idx. Every failing leaf is reported: the result joins one *CompileError per leaf, with its Path set (map keys sorted).

type EvalError

type EvalError struct {
	Code Code
	Expr string
	// Path is the leaf's path in the tree given to EvalTree; empty for EvalBool/EvalValue.
	Path string
	// Line and Column locate the failing sub-expression (1-based; 0 when unknown).
	Line, Column int
	Message      string
	Err          error
}

EvalError reports an evaluation that failed. Err is the cause: one of the sentinels above (ErrMissing, ErrType, ErrCostLimit, ErrTimeout, ErrNotCompiled), the caller's context error for CodeCanceled, or cel-go's error otherwise.

func (*EvalError) Error

func (e *EvalError) Error() string

func (*EvalError) Unwrap

func (e *EvalError) Unwrap() error

Unwrap returns the cause.

type ExprKind

type ExprKind int

ExprKind is what an expression must produce.

const (
	// Where is a rule's where: it must produce a bool. An empty where is always true.
	Where ExprKind = iota + 1
	// Value is a "=CEL" value (action values, TaskSpec fields): any YAML value.
	Value
)

func (ExprKind) String

func (k ExprKind) String() string

type FieldError

type FieldError struct {
	Expr string
	// Field is the selection that is not allowed, e.g. "event.release.tagg" or
	// "item.pr.approvedBy[].identty".
	Field        string
	Line, Column int
}

FieldError reports a field that the environment's allow-list doesn't document, e.g. a typo such as event.release.tagg.

func (*FieldError) Error

func (e *FieldError) Error() string

type Issue

type Issue struct {
	Line, Column int
	Message      string
}

Issue is one parse or check problem, at a 1-based line and column of the expression (0 when cel-go gives no position).

func (Issue) String

func (i Issue) String() string

type Option

type Option func(*options)

Option configures an Env.

func WithCostLimit

func WithCostLimit(n uint64) Option

WithCostLimit sets the runtime cost limit of one evaluation (default DefaultCostLimit).

func WithInterruptCheckFrequency

func WithInterruptCheckFrequency(n uint) Option

WithInterruptCheckFrequency sets how often comprehensions check the evaluation context (default DefaultInterruptCheckFrequency).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the wall-clock limit of one evaluation (default DefaultTimeout).

type ParamError

type ParamError struct {
	// Path is where in the tree the failure is ("actions[0].dispatch.queue"); empty for a
	// merge error.
	Path string
	// Param is the param name, when known.
	Param   string
	Message string
	Err     error
}

ParamError reports a failed "{{ params.x }}" substitution or params merge.

func (*ParamError) Error

func (e *ParamError) Error() string

func (*ParamError) Unwrap

func (e *ParamError) Unwrap() error

Unwrap returns the sentinel cause.

type Program

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

Program is a compiled expression. It is immutable and safe for concurrent use.

func (*Program) EstimateCost

func (p *Program) EstimateCost() (minCost, maxCost uint64, err error)

EstimateCost returns cel-go's static cost estimate (min, max) assuming every activation value has at most EstimateSizeHint elements or characters. The catalog compares max to the cost limit (CAT603); at runtime the actual cost is what the limit applies to.

func (*Program) EvalBool

func (p *Program) EvalBool(ctx context.Context, a Activation) (bool, error)

EvalBool evaluates a where. A result that is not a bool is an *EvalError with ErrType.

func (*Program) EvalValue

func (p *Program) EvalValue(ctx context.Context, a Activation) (any, error)

EvalValue evaluates the expression and converts the result to a YAML value (map[string]any, []any, string, bool, int64, uint64, float64, nil, []byte, time.Time, time.Duration).

func (*Program) Kind

func (p *Program) Kind() ExprKind

Kind returns what the expression was compiled as.

func (*Program) Source

func (p *Program) Source() string

Source returns the expression as compiled (without a "=" prefix).

func (*Program) UnknownFields

func (p *Program) UnknownFields() []*FieldError

UnknownFields returns the selections the field allow-list doesn't document, such as event.release.tagg or item.pr.approvedBy[].identty, in source order. Selections into open maps (item.state, run.inputs, params, …) are never reported; comprehension variables take the element shape of the list they range over.

func (*Program) Variables

func (p *Program) Variables() []string

Variables returns the environment variables the expression references, sorted (e.g. for "now in a where needs a schedule" and "TaskSpec fields only use inputs and task").

type ProgramIndex

type ProgramIndex map[string]*Program

ProgramIndex holds the compiled "=" leaves of a catalog, keyed by CEL source (without the "="). It is filled by CompileTree at catalog load and read-only afterwards, so it is safe to share between goroutines.

Jump to

Keyboard shortcuts

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