env

package
v0.33.4 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0, BSD-3-Clause Imports: 13 Imported by: 6

Documentation

Overview

Package env provides a representation of a CEL environment.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigToJSON added in v0.33.0

func ConfigToJSON(c *Config) ([]byte, error)

ConfigToJSON returns the config serialized to JSON

Provided as a convenience wrapper around a tested JSON Marshaler.

func ConfigToYAML

func ConfigToYAML(c *Config) ([]byte, error)

ConfigToYAML returns the config serialized to YAML

Provided as a convenience wrapper around a tested YAML Marshaler.

func EditDistance added in v0.33.0

func EditDistance(a, b string) int

EditDistance calculates the Damerau-Levenshtein distance between two strings, taking into account insertions, deletions, substitutions, and adjacent transpositions.

When evaluating string similarity for suggestions, the following distance thresholds are recommended:

  • length <= 3: max distance 1
  • 4 <= length <= 8: max distance 2
  • length > 8: max distance length / 3

Types

type Catalog added in v0.33.0

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

Catalog holds an index of symbols from the active environment and available libraries.

func NewCatalog added in v0.33.0

func NewCatalog(symbols ...*CatalogSymbol) *Catalog

NewCatalog creates a new Catalog initialized with the given symbols.

func (*Catalog) Add added in v0.33.0

func (c *Catalog) Add(syms ...*CatalogSymbol)

Add adds one or more symbols to the catalog.

func (*Catalog) Find added in v0.33.0

func (c *Catalog) Find(name string) []*CatalogSymbol

Find searches for symbols in the catalog matching the given name.

If an exact match exists, a single-element slice containing that symbol is returned. Otherwise, candidate symbols matching the namespace structure (namespaced vs non-namespaced) are evaluated using Damerau-Levenshtein edit distance within the following thresholds:

  • length <= 3: max distance 1
  • 4 <= length <= 8: max distance 2
  • length > 8: max distance length / 3

If candidates meet the edit distance threshold, up to two entries with the lowest edit distance are returned, ordered from shortest to longest suggestion (and alphabetically on tie).

If no edit distance matches are found, prefix matching is performed as a fallback. When a prefix matches multiple symbols, up to two candidates are returned, ordered from shortest to longest.

type CatalogSymbol added in v0.33.0

type CatalogSymbol struct {
	Name       string     `yaml:"name" json:"name"`
	Kind       SymbolKind `yaml:"kind" json:"kind"`
	Library    string     `yaml:"library,omitempty" json:"library,omitempty"`
	Option     string     `yaml:"option,omitempty" json:"option,omitempty"`
	MinVersion uint32     `yaml:"min_version,omitempty" json:"minVersion,omitempty"`
}

CatalogSymbol represents a symbol in the environment catalog.

type Config

type Config struct {
	Name            string           `yaml:"name,omitempty" json:"name,omitempty"`
	Description     string           `yaml:"description,omitempty" json:"description,omitempty"`
	Container       string           `` /* 127-byte string literal not displayed */
	Imports         []*Import        `yaml:"imports,omitempty" json:"imports,omitempty" jsonschema_description:"Fully qualified type names imported by simple name"`
	StdLib          *LibrarySubset   `` /* 129-byte string literal not displayed */
	Extensions      []*Extension     `yaml:"extensions,omitempty" json:"extensions,omitempty"`
	ContextVariable *ContextVariable `` /* 161-byte string literal not displayed */
	Variables       []*Variable      `yaml:"variables,omitempty" json:"variables,omitempty"`
	Functions       []*Function      `yaml:"functions,omitempty" json:"functions,omitempty"`
	Validators      []*Validator     `yaml:"validators,omitempty" json:"validators,omitempty"`
	Features        []*Feature       `yaml:"features,omitempty" json:"features,omitempty"`
	Limits          []*Limit         `yaml:"limits,omitempty" json:"limits,omitempty"`
}

Config represents a serializable form of the CEL environment configuration.

Note: custom validations, feature flags, and performance tuning parameters are not (yet) considered part of the core CEL environment configuration and should be managed separately until a common convention for such settings is developed.

func ConfigFromJSON added in v0.33.0

func ConfigFromJSON(data []byte, opts ...DecodeOption) (*Config, error)

ConfigFromJSON returns a config from JSON source.

Adds custom parsing logic for normalizing shorthand for specifying some fields in a JSON document (mainly the type-specifier shorthand).

Using json.Unmarshal with any implementation should be sufficient for most cases.

func ConfigFromYAML

func ConfigFromYAML(data []byte, opts ...DecodeOption) (*Config, error)

ConfigFromYAML returns a config from YAML source.

Adds custom parsing logic for normalizing shorthand for specifiying some fields in a YAML document (mainly the type-specifier shorthand).

Using yaml.Unmarshal with any implementation should be sufficient for most cases.

func NewConfig

func NewConfig(name string) *Config

NewConfig creates an instance of a YAML/JSON serializable CEL environment configuration.

func (*Config) AddExtensions

func (c *Config) AddExtensions(exts ...*Extension) *Config

AddExtensions appends a set of extensions to the config.

func (*Config) AddFeatures

func (c *Config) AddFeatures(feats ...*Feature) *Config

AddFeatures appends one or more features to the config.

func (*Config) AddFunctionDecls

func (c *Config) AddFunctionDecls(funcs ...*decls.FunctionDecl) *Config

AddFunctionDecls adds one or more functions to the config, converting them to serializable values first.

FunctionDecl inputs are expected to be well-formed.

func (*Config) AddFunctions

func (c *Config) AddFunctions(funcs ...*Function) *Config

AddFunctions adds one or more functions to the config.

func (*Config) AddImports

func (c *Config) AddImports(imps ...*Import) *Config

AddImports appends a set of imports to the config.

func (*Config) AddLimits

func (c *Config) AddLimits(limits ...*Limit) *Config

AddLimits appends one or more limits to the config.

func (*Config) AddValidators

func (c *Config) AddValidators(vals ...*Validator) *Config

AddValidators appends one or more validators to the config.

func (*Config) AddVariableDecls

func (c *Config) AddVariableDecls(vars ...*decls.VariableDecl) *Config

AddVariableDecls adds one or more variables to the config, converting them to serializable values first.

VariableDecl inputs are expected to be well-formed.

func (*Config) AddVariables

func (c *Config) AddVariables(vars ...*Variable) *Config

AddVariables adds one or more variables to the config.

func (*Config) SetContainer

func (c *Config) SetContainer(container string) *Config

SetContainer configures the container name for this configuration.

func (*Config) SetContextVariable

func (c *Config) SetContextVariable(ctx *ContextVariable) *Config

SetContextVariable configures the ContextVariable for this configuration.

func (*Config) SetStdLib

func (c *Config) SetStdLib(subset *LibrarySubset) *Config

SetStdLib configures the LibrarySubset for the standard library.

func (*Config) ToCatalog added in v0.33.0

func (c *Config) ToCatalog() *Catalog

ToCatalog converts the Config to a Catalog containing its functions, variables, container, and imports.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the whole configuration is well-formed.

type ContextVariable

type ContextVariable struct {
	// TypeName represents the fully qualified typename of the context variable.
	// Currently, only protobuf types are supported.
	TypeName string `yaml:"type_name" json:"typeName" jsonschema_description:"Fully qualified protobuf message type name"`
}

ContextVariable represents a structured message whose fields are to be treated as the top-level variable identifiers within CEL expressions.

func NewContextVariable

func NewContextVariable(typeName string) *ContextVariable

NewContextVariable returns a serializable context variable with a specific type name.

func (*ContextVariable) UnmarshalJSON added in v0.33.0

func (ctx *ContextVariable) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*ContextVariable) UnmarshalYAML added in v0.33.0

func (ctx *ContextVariable) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements yaml.Unmarshaler.

func (*ContextVariable) Validate

func (ctx *ContextVariable) Validate() error

Validate validates the context-variable configuration is well-formed.

type DecodeOption added in v0.33.0

type DecodeOption func(*decodeOptions)

DecodeOption configures how an environment Config is decoded from YAML or JSON.

func StrictDecoding added in v0.33.0

func StrictDecoding(strict bool) DecodeOption

StrictDecoding configures whether unknown fields in the YAML or JSON input cause a decoding error. By default, unknown fields are ignored.

type Extension

type Extension struct {
	// Name is either the LibraryName() or some short-hand simple identifier which is understood by the config-handler.
	Name string `yaml:"name" json:"name"`

	// Version may either be an unsigned long value or the string 'latest'. If empty, the value is treated as '0'.
	Version string `yaml:"version,omitempty" json:"version,omitempty" jsonschema_description:"Extension version number or 'latest'"`
}

Extension represents a named and optionally versioned extension library configured in the environment.

func NewExtension

func NewExtension(name string, version uint32) *Extension

NewExtension creates a serializable Extension from a name and version string.

func (*Extension) Validate

func (e *Extension) Validate() error

Validate validates the extension configuration is well-formed.

func (*Extension) VersionNumber

func (e *Extension) VersionNumber() (uint32, error)

VersionNumber returns the parsed version string, or an error if the version cannot be parsed.

type Feature

type Feature struct {
	Name    string `yaml:"name" json:"name"`
	Enabled bool   `yaml:"enabled" json:"enabled"`
}

Feature represents a named boolean feature flag supported by CEL.

func NewFeature

func NewFeature(name string, enabled bool) *Feature

NewFeature creates a new feature flag with a boolean enablement flag.

func (*Feature) Validate

func (feat *Feature) Validate() error

Validate validates whether the feature is well-configured.

type Function

type Function struct {
	Name        string      `yaml:"name" json:"name" jsonschema_description:"camelCase function name, either standalone or namespace.functionName"`
	Description string      `yaml:"description,omitempty" json:"description,omitempty"`
	Overloads   []*Overload `yaml:"overloads,omitempty" json:"overloads,omitempty"`
}

Function represents the serializable format of a function and its overloads.

func NewFunction

func NewFunction(name string, overloads ...*Overload) *Function

NewFunction creates a serializable function and overload set.

func NewFunctionWithDoc

func NewFunctionWithDoc(name, doc string, overloads ...*Overload) *Function

NewFunctionWithDoc creates a serializable function and overload set.

func (*Function) AsCELFunction

func (fn *Function) AsCELFunction(tp types.Provider) (*decls.FunctionDecl, error)

AsCELFunction converts the serializable form of the Function into CEL environment declaration.

func (*Function) Validate

func (fn *Function) Validate() error

Validate validates the function configuration is well-formed.

type Import

type Import struct {
	Name string `yaml:"name" json:"name" jsonschema_description:"Fully qualified protobuf message or enum name"`
}

Import represents a type name that will be appreviated by its simple name using the cel.Abbrevs() option.

func NewImport

func NewImport(name string) *Import

NewImport returns a serializable import value from the qualified type name.

func (*Import) Validate

func (imp *Import) Validate() error

Validate validates the import configuration is well-formed.

type LibrarySubset

type LibrarySubset struct {
	// Disabled indicates whether the library has been disabled, typically only used for
	// default-enabled libraries like stdlib.
	Disabled bool `yaml:"disabled,omitempty" json:"disabled,omitempty"`

	// DisableMacros disables macros for the given library.
	DisableMacros bool `yaml:"disable_macros,omitempty" json:"disableMacros,omitempty"`

	// IncludeMacros specifies a set of macro function names to include in the subset.
	IncludeMacros []string `yaml:"include_macros,omitempty" json:"includeMacros,omitempty"`

	// ExcludeMacros specifies a set of macro function names to exclude from the subset.
	// Note: if IncludeMacros is non-empty, then ExcludeFunctions is ignored.
	ExcludeMacros []string `yaml:"exclude_macros,omitempty" json:"excludeMacros,omitempty"`

	// IncludeFunctions specifies a set of functions to include in the subset.
	//
	// Note: the overloads specified in the subset need only specify their ID.
	// Note: if IncludeFunctions is non-empty, then ExcludeFunctions is ignored.
	IncludeFunctions []*Function `` /* 140-byte string literal not displayed */

	// ExcludeFunctions specifies the set of functions to exclude from the subset.
	//
	// Note: the overloads specified in the subset need only specify their ID.
	ExcludeFunctions []*Function `` /* 140-byte string literal not displayed */
}

LibrarySubset indicates a subset of the macros and function supported by a subsettable library.

func NewLibrarySubset

func NewLibrarySubset() *LibrarySubset

NewLibrarySubset returns an empty library subsetting config which permits all library features.

func (*LibrarySubset) AddExcludedFunctions

func (lib *LibrarySubset) AddExcludedFunctions(funcs ...*Function) *LibrarySubset

AddExcludedFunctions deny-lists one or more functions from the subset.

func (*LibrarySubset) AddExcludedMacros

func (lib *LibrarySubset) AddExcludedMacros(macros ...string) *LibrarySubset

AddExcludedMacros deny-lists one or more macros by function name.

func (*LibrarySubset) AddIncludedFunctions

func (lib *LibrarySubset) AddIncludedFunctions(funcs ...*Function) *LibrarySubset

AddIncludedFunctions allow-lists one or more functions from the subset.

Note, this option will override any excluded functions.

func (*LibrarySubset) AddIncludedMacros

func (lib *LibrarySubset) AddIncludedMacros(macros ...string) *LibrarySubset

AddIncludedMacros allow-lists one or more macros by function name.

Note, this option will override any excluded macros.

func (*LibrarySubset) SetDisableMacros

func (lib *LibrarySubset) SetDisableMacros(value bool) *LibrarySubset

SetDisableMacros disables the macros for the library.

func (*LibrarySubset) SetDisabled

func (lib *LibrarySubset) SetDisabled(value bool) *LibrarySubset

SetDisabled disables or enables the library.

func (*LibrarySubset) SubsetFunction

func (lib *LibrarySubset) SubsetFunction(fn *decls.FunctionDecl) (*decls.FunctionDecl, bool)

SubsetFunction produces a function declaration which matches the supported subset, or nil if the function is not supported by the LibrarySubset.

For IncludeFunctions, if the function does not specify a set of overloads to include, the whole function definition is included. If overloads are set, then a new function which includes only the specified overloads is produced.

For ExcludeFunctions, if the function does not specify a set of overloads to exclude, the whole function definition is excluded. If overloads are set, then a new function which includes only the permitted overloads is produced.

func (*LibrarySubset) SubsetMacro

func (lib *LibrarySubset) SubsetMacro(macroFunction string) bool

SubsetMacro indicates whether the macro function should be included in the library subset.

func (*LibrarySubset) Validate

func (lib *LibrarySubset) Validate() error

Validate validates the library configuration is well-formed.

For example, setting both the IncludeMacros and ExcludeMacros together could be confusing and create a broken expectation, likewise for IncludeFunctions and ExcludeFunctions.

type Limit

type Limit struct {
	Name  string `yaml:"name" json:"name"`
	Value int    `yaml:"value" json:"value"`
}

Limit represents a named limit in the CEL environment. This is used to control the complexity tolerated before failing parsing, type checking, or planning.

func NewLimit

func NewLimit(name string, value int) *Limit

NewLimit creates a new limit.

func (*Limit) Validate

func (l *Limit) Validate() error

Validate validates a limit.

type Overload

type Overload struct {
	ID       string      `` /* 144-byte string literal not displayed */
	Examples []string    `yaml:"examples,omitempty" json:"examples,omitempty"`
	Target   *TypeDesc   `yaml:"target,omitempty" json:"target,omitempty" jsonschema_description:"Receiver type specifier for member functions"`
	Args     []*TypeDesc `yaml:"args,omitempty" json:"args,omitempty"`
	Return   *TypeDesc   `yaml:"return,omitempty" json:"return,omitempty"`
}

Overload represents the serializable format of a function overload.

func NewMemberOverload

func NewMemberOverload(id string, target *TypeDesc, args []*TypeDesc, ret *TypeDesc, examples ...string) *Overload

NewMemberOverload returns a new serializable representation of a member (receiver) overload.

func NewOverload

func NewOverload(id string, args []*TypeDesc, ret *TypeDesc, examples ...string) *Overload

NewOverload returns a new serializable representation of a global overload.

func (*Overload) AsFunctionOption

func (od *Overload) AsFunctionOption(tp types.Provider) (decls.FunctionOpt, error)

AsFunctionOption converts the serializable form of the Overload into a function declaration option.

func (*Overload) UnmarshalJSON added in v0.33.0

func (od *Overload) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Overload) UnmarshalYAML added in v0.33.0

func (od *Overload) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements yaml.Unmarshaler.

func (*Overload) Validate

func (od *Overload) Validate() error

Validate validates the overload configuration is well-formed.

type SymbolKind added in v0.33.0

type SymbolKind string

SymbolKind indicates the kind of declaration provided in an environment.

const (
	// FunctionKind represents a function declaration.
	FunctionKind SymbolKind = "function"

	// MacroKind represents a macro declaration.
	MacroKind SymbolKind = "macro"

	// TypeKind represents a type declaration.
	TypeKind SymbolKind = "type"

	// NamespaceKind represents a namespace declaration.
	NamespaceKind SymbolKind = "namespace"

	// VariableKind represents a variable declaration.
	VariableKind SymbolKind = "variable"
)

type TypeDesc

type TypeDesc struct {
	TypeName    string      `yaml:"type_name" json:"typeName"`
	Params      []*TypeDesc `yaml:"params,omitempty" json:"params,omitempty"`
	IsTypeParam bool        `yaml:"is_type_param,omitempty" json:"isTypeParam,omitempty"`
}

TypeDesc represents the serializable format of a CEL *types.Type value.

func NewTypeDesc

func NewTypeDesc(typeName string, params ...*TypeDesc) *TypeDesc

NewTypeDesc describes a simple or complex type with parameters.

func NewTypeParam

func NewTypeParam(paramName string) *TypeDesc

NewTypeParam describe a type-param type.

func ParseTypeDesc

func ParseTypeDesc(text string) (*TypeDesc, error)

ParseTypeDesc parses a TypeDesc from the type specifier format: "map<string, int>"

func SerializeTypeDesc

func SerializeTypeDesc(t *types.Type) *TypeDesc

SerializeTypeDesc converts a CEL native *types.Type to a serializable TypeDesc.

func (*TypeDesc) AsCELType

func (td *TypeDesc) AsCELType(tp types.Provider) (*types.Type, error)

AsCELType converts the serializable object to a *types.Type value.

func (*TypeDesc) MarshalJSON added in v0.33.0

func (td *TypeDesc) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*TypeDesc) MarshalYAML added in v0.33.0

func (td *TypeDesc) MarshalYAML() (any, error)

MarshalYAML implements yaml.Marshaler.

func (*TypeDesc) SpecifierFormat

func (td *TypeDesc) SpecifierFormat() string

SpecifierFormat returns the short text representation of the type. e.g. "map<string, int>"

func (*TypeDesc) String

func (td *TypeDesc) String() string

String implements the strings.Stringer interface method.

func (*TypeDesc) UnmarshalJSON added in v0.33.0

func (td *TypeDesc) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*TypeDesc) UnmarshalYAML

func (td *TypeDesc) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements yaml.Unmarshaler.

func (*TypeDesc) Validate

func (td *TypeDesc) Validate() error

Validate validates the type configuration is well-formed.

type Validator

type Validator struct {
	Name   string         `yaml:"name" json:"name"`
	Config map[string]any `yaml:"config,omitempty" json:"config,omitempty"`
}

Validator represents a named validator with an optional map-based configuration object.

Note: the map-keys must directly correspond to the internal representation of the original validator, and should only use primitive scalar types as values at this time.

func NewValidator

func NewValidator(name string) *Validator

NewValidator returns a named Validator instance.

func (*Validator) ConfigValue

func (v *Validator) ConfigValue(name string) (any, bool)

ConfigValue retrieves the value associated with the config key name, if one exists.

func (*Validator) SetConfig

func (v *Validator) SetConfig(config map[string]any) *Validator

SetConfig sets the set of map key-value pairs associated with this validator's configuration.

func (*Validator) UnmarshalJSON added in v0.33.0

func (v *Validator) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Validator) UnmarshalYAML added in v0.33.0

func (v *Validator) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements yaml.Unmarshaler.

func (*Validator) Validate

func (v *Validator) Validate() error

Validate validates the configuration of the validator object.

type Variable

type Variable struct {
	Name        string `yaml:"name" json:"name"`
	Description string `yaml:"description,omitempty" json:"description,omitempty"`

	// Type represents the type declaration for the variable.
	//
	// When serialized, 'type' is used for shorthand specifier string.
	//
	// Use GetType() for getting the effective type.
	Type *TypeDesc `` /* 178-byte string literal not displayed */

	// TypeDesc is an embedded set of fields allowing for the specification of the Variable type.
	*TypeDesc `yaml:",inline"`
}

Variable represents a typed variable declaration which will be published via the cel.VariableDecls() option.

func NewVariable

func NewVariable(name string, t *TypeDesc) *Variable

NewVariable returns a serializable variable from a name and type definition

func NewVariableWithDoc

func NewVariableWithDoc(name string, t *TypeDesc, doc string) *Variable

NewVariableWithDoc returns a serializable variable from a name, type definition, and doc string.

func (*Variable) AsCELVariable

func (v *Variable) AsCELVariable(tp types.Provider) (*decls.VariableDecl, error)

AsCELVariable converts the serializable form of the Variable into a CEL environment declaration.

func (*Variable) GetType

func (v *Variable) GetType() *TypeDesc

GetType returns the variable type description.

Note, if both the embedded TypeDesc and the field Type are non-nil, the embedded TypeDesc will take precedence.

func (*Variable) MarshalJSON added in v0.33.0

func (v *Variable) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Variable) MarshalYAML

func (v *Variable) MarshalYAML() (any, error)

MarshalYAML implements yaml.Marshaler.

func (*Variable) UnmarshalJSON added in v0.33.0

func (v *Variable) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Variable) UnmarshalYAML

func (v *Variable) UnmarshalYAML(unmarshal func(any) error) error

UnmarshalYAML implements yaml.Unmarshaler.

func (*Variable) Validate

func (v *Variable) Validate() error

Validate validates the variable configuration is well-formed.

Jump to

Keyboard shortcuts

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