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
- Variables
- func CELSource(s string) (src string, ok bool)
- func EvalTree(ctx context.Context, v any, a Activation, progs ProgramIndex) (any, error)
- func MergeParams(declared, defaults, overrides map[string]any) (map[string]any, error)
- func Substitute(v any, params map[string]any) (any, error)
- func SubstituteRule(r *v1alpha1.Rule, params map[string]any) (*v1alpha1.Rule, error)
- func Unescape(s string) string
- type Activation
- type Code
- type CompileError
- type Env
- type EvalError
- type ExprKind
- type FieldError
- type Issue
- type Option
- type ParamError
- type Program
- func (p *Program) EstimateCost() (minCost, maxCost uint64, err error)
- func (p *Program) EvalBool(ctx context.Context, a Activation) (bool, error)
- func (p *Program) EvalValue(ctx context.Context, a Activation) (any, error)
- func (p *Program) Kind() ExprKind
- func (p *Program) Source() string
- func (p *Program) UnknownFields() []*FieldError
- func (p *Program) Variables() []string
- type ProgramIndex
Constants ¶
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).
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.
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).
const ExprPrefix = "="
ExprPrefix starts a runtime CEL value: "=event.object.ref".
Variables ¶
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.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
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.
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 ¶
Issue is one parse or check problem, at a 1-based line and column of the expression (0 when cel-go gives no position).
type Option ¶
type Option func(*options)
Option configures an Env.
func WithCostLimit ¶
WithCostLimit sets the runtime cost limit of one evaluation (default DefaultCostLimit).
func WithInterruptCheckFrequency ¶
WithInterruptCheckFrequency sets how often comprehensions check the evaluation context (default DefaultInterruptCheckFrequency).
func WithTimeout ¶
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
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 ¶
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 ¶
EvalBool evaluates a where. A result that is not a bool is an *EvalError with ErrType.
func (*Program) EvalValue ¶
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) 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.
type ProgramIndex ¶
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.