api

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package api implements the data types and messages exchanged by the ConfigHub function executor and its clients, in Go.

Index

Constants

View Source
const (
	// Basic scalar types
	DataTypeNone   = DataType("")
	DataTypeString = DataType("string")
	DataTypeInt    = DataType("int")
	DataTypeBool   = DataType("bool")
	DataTypeEnum   = DataType("enum")

	// Additional Storage types
	DataTypeUUID                    = DataType("uuid")
	DataTypeTime                    = DataType("time")
	DataTypeStringMap               = DataType("map[string]string")
	DataTypeStringBoolMap           = DataType("map[string]bool")
	DataTypeUUIDArray               = DataType("[]uuid")
	DataTypeUUIDStringMap           = DataType("map[uuid]string")
	DataTypeStringStringUUIDBoolMap = DataType("map[string]map[string]map[uuid]bool")

	// Structured data types
	DataTypeAttributeValueList   = DataType("AttributeValueList")
	DataTypePatchMap             = DataType("PatchMap")
	DataTypeResourceMutationList = DataType("ResourceMutationList")
	DataTypeResourceList         = DataType("ResourceList")
	DataTypeValueFilter          = DataType("ValueFilter")

	// Configuration format types
	DataTypeJSON       = DataType("JSON")
	DataTypeYAML       = DataType("YAML")
	DataTypeProperties = DataType("Properties")
	DataTypeTOML       = DataType("TOML")
	DataTypeINI        = DataType("INI")
	DataTypeEnv        = DataType("Env")
	DataTypeHCL        = DataType("HCL")
	DataTypeCEL        = DataType("CEL")
)
View Source
const (
	OutputTypeValidationResult     = OutputType("ValidationResult")
	OutputTypeValidationResultList = OutputType("ValidationResultList")
	OutputTypeAttributeValueList   = OutputType("AttributeValueList")
	OutputTypeResourceInfoList     = OutputType("ResourceInfoList")
	OutputTypeResourceList         = OutputType("ResourceList")
	OutputTypePatchMap             = OutputType("PatchMap")
	OutputTypeCustomJSON           = OutputType("JSON")
	OutputTypeYAML                 = OutputType("YAML")
	OutputTypeOpaque               = OutputType("Opaque")
	OutputTypeResourceMutationList = OutputType("ResourceMutationList")
)
View Source
const (
	ResourceCategoryInvalid     = ResourceCategory("Invalid")
	ResourceCategoryResource    = ResourceCategory("Resource")
	ResourceCategoryDyanmicData = ResourceCategory("DynamicData")
	ResourceCategoryAppConfig   = ResourceCategory("AppConfig")
)
View Source
const (
	AttributeNameNone                    = AttributeName("")
	AttributeNameGeneral                 = AttributeName("attribute-value")
	AttributeNameNeededValue             = AttributeName("needed-value")
	AttributeNameProvidedValue           = AttributeName("provided-value")
	AttributeNameResourceName            = AttributeName("resource-name")
	AttributeNameContainerName           = AttributeName("container-name")
	AttributeNameContainerImage          = AttributeName("container-image")
	AttributeNameContainerImages         = AttributeName("container-images")
	AttributeNameContainerRepositoryURI  = AttributeName("container-repository-uri")
	AttributeNameContainerImageReference = AttributeName("container-image-reference")
	AttributeNameHostname                = AttributeName("hostname")
	AttributeNameDomain                  = AttributeName("domain")
	AttributeNameSubdomain               = AttributeName("subdomain")
	AttributeNameDetail                  = AttributeName("detail")
	AttributeNameDefaultName             = AttributeName("default-name")
)
View Source
const (
	FunctionTypePathVisitor = FunctionType("PathVisitor")
	FunctionTypeCustom      = FunctionType("Custom")
)
View Source
const (
	EvaluatorTemplate = "template"
	EvaluatorCEL      = "cel"
)
View Source
const AttributeNamePrefixRegexpString = "^[A-Za-z0-9]([\\-_A-Za-z0-9]{0,127})?"

Valid attribute names. By convention we use kabob-case to match cub's convention.

View Source
const (
	EmbeddedAccessorRegexp = "Regexp"
)
View Source
const FunctionNamePrefixRegexpString = "^[A-Za-z0-9]([\\-_A-Za-z0-9]{0,127})?"

Valid function names. By convention we use kabob-case to match cub's convention.

View Source
const MaxAttributeNameLength = 128
View Source
const MaxConfigDataLength = 64 * 1024 * 1024 // 64MB
View Source
const MaxDataTypeLength = 32
View Source
const MaxFilterLength = 8192
View Source
const MaxFunctionDescriptionLength = 1024
View Source
const MaxFunctionErrorMessageLength = 1024
View Source
const MaxFunctionNameLength = 128

TODO: Validate these

View Source
const MaxFunctionNumberOfErrors = 1024
View Source
const MaxFunctionOutputLength = 64 * 1024 * 1024 // 64MB
View Source
const MaxFunctionParameterNameLength = 128
View Source
const MaxNumFunctionArguments = 32
View Source
const MaxResourceTypeLength = 128
View Source
const (
	PathRegexpString = "^" + pathSegmentRegexpString + "(?:\\." + pathSegmentRegexpString + ")*(?:\\.\\|" + pathSegmentWithoutPatternsRegexpString + "(?:\\." + pathSegmentWithoutPatternsRegexpString + ")*)?(?:#" + pathMapSegmentRegexpString + ")?"
)

Path expressions support embedded accessors and escaped dots. They also support wildcards and associative matches. Kubernetes annotations and labels permit slashes

View Source
const (
	ResourceTypeAny = ResourceType("*")
)

Variables

View Source
var (
	ValidationResultTrue  = ValidationResult{Passed: true}
	ValidationResultFalse = ValidationResult{Passed: false}
)
View Source
var (
	LogicalOperatorRegexp = regexp.MustCompile(logicalOperatorRegexpString)

	// Exported Literal patterns
	BooleanLiteralRegexp      = regexp.MustCompile(booleanLiteralRegexpString)
	IntegerLiteralRegexp      = regexp.MustCompile(integerLiteralRegexpString)
	SafeStringCharsOnlyRegexp = regexp.MustCompile("^" + safeStringCharsRegexpString + "$")
	StringLiteralRegexp       = regexp.MustCompile(stringLiteralRegexpString)
)
View Source
var ImportSupportedOperators = []string{"=", "!=", "IN", "NOT IN"}

Import-specific operator support

Functions

func CombineOutputs

func CombineOutputs(
	functionName string,
	instance string,
	newOutputType OutputType,
	outputs map[OutputType]any,
	newOutput any,
	functionInvocationIndex int,
	messages []string,
) (map[OutputType]any, []string)

Merge outputs from multiple function calls as a map by output type, combining lists of the same well known type.

func DataTypeIsSerializedAsString

func DataTypeIsSerializedAsString(dataType DataType) bool

All types except int and bool are always serialized as strings.

func EvaluateExpression

func EvaluateExpression(expr *RelationalExpression, leftValue any, rightValue any, customComparators []CustomStringComparator) (bool, error)

EvaluateExpression evaluates a relational expression against a value of any type Returns (matched, error) where error indicates type conversion failure

func EvaluatePermissionsExpression

func EvaluatePermissionsExpression(operator string, leftValue PermissionsData, rightValue interface{}, isLengthExpression bool, actionKey string, fieldKey string) (bool, error)

EvaluatePermissionsExpression evaluates Permissions expressions Supports:

  • LEN(Permissions) - returns total number of action categories with subjects
  • LEN(Permissions.<action>.UserIDs) - returns number of users for a specific action
  • Permissions.<action>.UserIDs ? <uuid> - checks if a user has a specific permission

func GetLogicalOperator

func GetLogicalOperator(decodedQueryString string) (string, string)

func IsSupportedToolchain

func IsSupportedToolchain(toolchain workerapi.ToolchainType) bool

func NoMutations

func NoMutations(mutations ResourceMutationList) bool

func OffsetMutations

func OffsetMutations(mutations ResourceMutationList, offset int64)

func ParseInClause

func ParseInClause(decodedQueryString string) (string, string, error)

ParseInClause parses an IN clause like "('value1', 'value2', 'value3')" Exported for use by internal packages

func ParseInClauseValues

func ParseInClauseValues(literal string) []string

ParseInClauseValues parses values from IN/NOT IN clauses like "('value1', 'value2')" Exported for use by internal packages

func ParseWhereFilterForImport

func ParseWhereFilterForImport(queryString string) ([]ImportFilter, ImportOptions, error)

ParseWhereFilterForImport parses a where-filter query string into ImportFilters and ImportOptions This is the public API version that can be used in tests and other public packages

func SkipWhitespace

func SkipWhitespace(decodedQueryString string) string

SkipWhitespace skips whitespace characters with optional limit

func SkipWhitespaceWithLimit

func SkipWhitespaceWithLimit(decodedQueryString string, limit int) string

SkipWhitespaceWithLimit skips whitespace characters with a character limit limit of -1 means no limit, 0 means no whitespace allowed, positive values set max chars

func SupportedToolchainsToString

func SupportedToolchainsToString() string

func UnmarshalOutput

func UnmarshalOutput(outputBytes []byte, outputType OutputType) (any, error)

Unmarshal well known output types.

func ValidateImportOperator

func ValidateImportOperator(operator string) error

ValidateImportOperator validates that an operator is supported for import queries

Types

type AttributeDetails

type AttributeDetails struct {
	GetterInvocation  *FunctionInvocation  `json:",omitempty" description:"Function invocation used to get the attribute, if any"`                        // used for matching
	SetterInvocations []FunctionInvocation `json:",omitempty" description:"Function invocation used to set the attribute (except for the value), if any"` // used for matching
	Description       string               `json:",omitempty" description:"Description of the attribute"`
}

AttributeDetails provides the getter and (potentially multiple) setter functions for the resource attribute, and other information.

type AttributeIdentifier

type AttributeIdentifier struct {
	ResourceInfo
	Path        ResolvedPath `swaggertype:"string" description:"Path of the attribute"`
	InLiveState bool         `json:",omitempty" description:"True if a path in the live state, false if a path in the configuration data"`
}

An AttributeIdentifier identifies the resource type and name and resolved path of the resource attribute.

type AttributeInfo

type AttributeInfo struct {
	AttributeIdentifier
	AttributeMetadata
}

AttributeInfo conveys both the identifying information about a resource attribute and its metadata.

type AttributeMetadata

type AttributeMetadata struct {
	AttributeName AttributeName     `json:",omitempty" swaggertype:"string" description:"Name of the registered attribute"`
	DataType      DataType          `swaggertype:"string" description:"Data type if the attribute value."`
	Info          *AttributeDetails `json:",omitempty" description:"Additional attribute details"`
}

AttributeMetadata specifies the AttributeName, DataType, and other details, such as corresponding getter and setter functions for the attribute.

type AttributeName

type AttributeName string

AttributeName represents the category name of an attribute used for getter and setter functions, and for matching Provided values to Needed values. There are some well known attribute names that are used across resource/configuration providers, and some that are specific to each provider. The well known ones are specified here. For functions that use the path registry, they identify sets of related resource paths.

func AttributeNameForResourceType

func AttributeNameForResourceType(resourceType ResourceType) AttributeName

type AttributeNameToResourceTypeToPathToVisitorInfoType

type AttributeNameToResourceTypeToPathToVisitorInfoType map[AttributeName]ResourceTypeToPathToVisitorInfoType

AttributeNameToResourceTypeToPathToVisitorInfoType associates paths of resource types with an attribute attribute class for traversal/visitation by functions.

type AttributeValue

type AttributeValue struct {
	AttributeInfo
	Value   any    `description:"Value of the attribute at the specified Path"`
	Comment string `json:",omitempty" description:"Line comment on the attribute at the specified Path"`
	Index   int    `` /* 189-byte string literal not displayed */
}

AttributeValue provides the value of an attribute in addition to information about the attribute.

type AttributeValueList

type AttributeValueList []AttributeValue

type CustomStringComparator

type CustomStringComparator interface {
	// MatchesPath returns true if this comparator should handle the given path
	MatchesPath(path string) bool
	// Evaluate performs the comparison of a value and literal and returns the result
	Evaluate(expr *RelationalExpression, value string) (bool, error)
}

CustomStringComparator allows injecting custom string comparison logic for specific path patterns

type DataType

type DataType string

DataType represents the data type of a function parameter or configuration attribute. The data type can be a scalar type (string, int, bool), a structured format (JSON, YAML), or a well known structured data type (e.g., AttributeValueList).

func ParseLiteral

func ParseLiteral(decodedQueryString string) (string, string, DataType, error)

type EmbeddedAccessorType

type EmbeddedAccessorType string

EmbeddedAccessorType specifies the type of format the embedded accessor can marshal and unmarshal in order to access embedded attributes.

type FunctionArgument

type FunctionArgument struct {
	ParameterName string `` /* 133-byte string literal not displayed */
	Value         any    `description:"Argument value; must be a Scalar type, currently string, int, or bool"`
	// DataType is not needed here because it's in the function signature
	Evaluator string `json:",omitempty" description:"Evaluate the provided Value with the specified Evaluator; supported values: template, cel"`
}

FunctionArgument specifies the value of an argument in a function invocation and, optionally, its corresponding parameter name. If the parameter name is not specified for any argument, all of the arguments are expected to be passed in the same order as in the parameter list.

type FunctionContext

type FunctionContext struct {
	ToolchainType       workerapi.ToolchainType `description:"ToolchainType of the configuration data and function handlers"`
	UnitSlug            string                  `description:"Slug of the configuration Unit"`
	UnitID              uuid.UUID               `description:"Unique ID of the configuration Unit"`
	UnitLabels          map[string]string       `description:"Labels of the configuration Unit"`
	UnitAnnotations     map[string]string       `description:"Annotations of the configuration Unit"`
	SpaceID             uuid.UUID               `description:"ID of the Space of the configuration Unit"`
	SpaceSlug           string                  `description:"Slug of the Space of the configuration Unit"`
	SpaceLabels         map[string]string       `description:"Labels of the Space of the configuration Unit"`
	SpaceAnnotations    map[string]string       `description:"Annotations of the Space of the configuration Unit"`
	OrganizationID      uuid.UUID               `description:"ID of the Organization of the configuration Unit"`
	TargetID            uuid.UUID               `json:",omitempty" description:"ID of the Target where the function is executed; optional"`
	BridgeWorkerID      uuid.UUID               `` /* 167-byte string literal not displayed */
	RevisionID          uuid.UUID               `description:"Unique ID of the configuration Revision"`
	RevisionNum         int64                   `description:"Current/previous HeadRevisionNum of the configuration Unit"`
	QueuedOperationID   uuid.UUID               `description:"Unique ID of the operation generating the LiveState for the Unit"`
	NotLive             bool                    `` /* 131-byte string literal not displayed */
	IsLiveState         bool                    `description:"True if the ConfigData is the LiveState of the Unit"`
	PreviousContentHash RevisionHash            `` /* 136-byte string literal not displayed */
	ApprovedBy          []string                `description:"Usernames of users that have approved this revision of the configuration data"`
}

The FunctionContext contains metadata about the configuration Unit provided as input to a function invocation sequence.

func (*FunctionContext) InstanceString

func (fc *FunctionContext) InstanceString() string

InstanceString returns a string that uniquely identifies the configuration Unit and, if present, the RevisionID.

type FunctionIDs

type FunctionIDs struct {
	OrganizationID uuid.UUID `description:"ID of the Unit's Organization"`
	SpaceID        uuid.UUID `description:"ID of the Unit's Space"`
	UnitID         uuid.UUID `description:"ID of the Unit the configuration data is associated with"`
	RevisionID     uuid.UUID `description:"ID of the Revision the configuration data is associated with"`
}

FunctionIDs contains the IDs related to a function invocation.

type FunctionInvocation

type FunctionInvocation struct {
	FunctionName string             `description:"Function name"`
	Arguments    []FunctionArgument `description:"Function arguments"`
}

FunctionInvocation specifies the name of the function to invoke and the arguments to pass to the function. The function name must uniquely identify the function within its resource/configuration provider on its executor instance.

type FunctionInvocationList

type FunctionInvocationList []FunctionInvocation

type FunctionInvocationRequest

type FunctionInvocationRequest struct {
	FunctionContext
	ConfigData          []byte                 `swaggertype:"string" format:"byte" description:"Configuration data of the Unit to operate on"`
	NumFilters          int                    `description:"Number of validating functions to treat as filters: stop, but don't report errors"`
	StopOnError         bool                   `description:"If true, stop executing functions on the first error"`
	FunctionInvocations FunctionInvocationList `description:"List of functions to invoke and their arguments"`
}

A FunctionInvocationRequest contains the configuration data of a configuration Unit, the function context for that configuration Unit, a sequence of functions to invoke and their arguments, and various options for the invocation.

type FunctionInvocationResponse

type FunctionInvocationResponse struct {
	FunctionIDs
	FunctionInvocationSuccessResponse
	Success       bool     `description:"True if all functions executed successfully"`
	ErrorMessages []string `description:"Error messages from function execution; will be empty if Success is true"`
}

A FunctionInvocationResponse is returned by the function executor in response to a FunctionInvocationRequest. It contains the potentially modified configuration data, any output produced by read-only and/or validation functions, whether the function sequence executed successfully, and any error messages returned. Output of compatible OutputTypes is combined, and otherwise the first output is returned. For instance, multiple AttributeValueLists will be appended together, and multiple ResourceInfoLists will be appended together.

type FunctionInvocationSuccessResponse

type FunctionInvocationSuccessResponse struct {
	ConfigData []byte                `swaggertype:"string" format:"byte" description:"The resulting configuration data, potentially mutated"`
	Outputs    map[OutputType][]byte `description:"Map of output types to their corresponding output data as embedded JSON"`
	Mutations  ResourceMutationList  `description:"List of mutations in the same order as the resources in ConfigData"`
	Mutators   []int                 `description:"List of function invocation indices that resulted in mutations"`
}

FunctionInvocationSuccessResponse contains the data returned from a successful function invocation.

type FunctionOutput

type FunctionOutput struct {
	ResultName  string             `description:"Name of the result in kabob-case"`
	Description string             `description:"Description of the result"`
	OutputType  OutputType         `swaggertype:"string" description:"Data type of the JSON embedded in the output"`
	Schema      *jsonschema.Schema `json:",omitempty" description:"JSON schema of the output type"`
}

FunctionOutput specifies the name and description of the result and its OutputType.

type FunctionParameter

type FunctionParameter struct {
	ParameterName string   `description:"Name of the parameter in kabob-case"`
	Description   string   `description:"Description of the parameter"`
	Required      bool     `description:"Whether the parameter is required"`
	DataType      DataType `swaggertype:"string" description:"Data type of the parameter"`
	Example       string   `json:",omitempty" description:"Example value"`
	ValueConstraints
}

FunctionParameter specifies the parameter name, description, required vs optional, data type, and example.

type FunctionSignature

type FunctionSignature struct {
	FunctionName          string              `description:"Name of the function in kabob-case"`
	Parameters            []FunctionParameter `description:"Function parameters, in order"`
	RequiredParameters    int                 `description:"Number of required parameters"`
	VarArgs               bool                `description:"Last parameter may be repeated"`
	OutputInfo            *FunctionOutput     `description:"Output description"`
	Mutating              bool                `description:"May change the configuration data"`
	Validating            bool                `description:"Returns ValidationResult"`
	Hermetic              bool                `description:"Does not call other systems"`
	Idempotent            bool                `description:"Will return the same result if invoked again"`
	Description           string              `description:"Description of the function"`
	FunctionType          FunctionType        `swaggertype:"string" description:"Implementation pattern of the function: PathVisitor or Custom"`
	AttributeName         AttributeName       `json:",omitempty" swaggertype:"string" description:"Attribute corresponding to registered paths, if a path visitor; optional"`
	AffectedResourceTypes []ResourceType      `json:",omitempty" description:"Resource types the function applies to; * if all"`
}

FunctionSignature specifies the parameter names and values, required and optional parameters, OutputType, kind of function (mutating/readonly or validating), and description of the function.

type FunctionType

type FunctionType string

FunctionType represents the function's implementation pattern, if a common pattern. The type is Custom if it doesn't fit a common pattern.

type ImportFilter

type ImportFilter struct {
	// Type specifies the filter type (namespace, label, resource_type, etc.)
	Type string `json:",omitempty" description:"Type specifies the filter type (namespace, label, resource_type, etc.)"`

	// Operator specifies how to apply the filter (include, exclude, equals, contains, matches)
	Operator string `json:",omitempty" description:"Operator specifies how to apply the filter (include, exclude, equals, contains, matches)"`

	// Values specifies the filter values
	Values []string `json:",omitempty" description:"Values specifies the filter values"`
}

ImportFilter

type ImportOptions

type ImportOptions map[string]interface{}

ImportOptions represents extensible import configuration

type MutationInfo

type MutationInfo struct {
	MutationType MutationType `` /* 133-byte string literal not displayed */
	Index        int64        `description:"Function index or sequence number corresponding to the change"`
	Predicate    bool         `description:"Used to decide how to use the mututation"`
	Value        string       `description:"Removed configuration data if MutationType is Delete and otherwise the new data"`
}

type MutationMap

type MutationMap map[ResolvedPath]MutationInfo

type MutationMapEntry

type MutationMapEntry struct {
	Path         ResolvedPath
	MutationInfo *MutationInfo
}

type MutationType

type MutationType string

Mutation Type is the type of mutation performed on the associated configuration element.

const (
	// No mutations at the level.
	MutationTypeNone MutationType = "None"
	// Add new configuration at the level.
	MutationTypeAdd MutationType = "Add"
	// Update part of the configuration at the level.
	MutationTypeUpdate MutationType = "Update"
	// Replace all of the configuration at the level (equivalent of Delete + Add).
	MutationTypeReplace MutationType = "Replace"
	// Delete the configuration at the level.
	MutationTypeDelete MutationType = "Delete"
)

type OutputType

type OutputType string

OutputType represents the type of output produced by a function. It is either a well known structured type (e.g., AttributeValueList), a structured format (JSON), or Opaque (unparsed).

type PatchMap

PatchList is a list of patches applied to specified resources.

type PathToVisitorInfoType

type PathToVisitorInfoType map[UnresolvedPath]*PathVisitorInfo

PathToVisitorInfoType associates attribute metadata with a resource path.

type PathVisitorInfo

type PathVisitorInfo struct {
	Path                   UnresolvedPath            `swaggertype:"string" description:"Unresolved path pattern"`
	ResolvedPath           ResolvedPath              `json:",omitempty" swaggertype:"string" description:"Specific resolved path"`
	AttributeName          AttributeName             `swaggertype:"string" description:"AttributeName for the path"`
	DataType               DataType                  `swaggertype:"string" description:"DataType of the attribute at the path"`
	Info                   *AttributeDetails         `json:",omitempty" description:"Additional attribute details"`
	TypeExceptions         map[ResourceType]struct{} `json:",omitempty" description:"Resource types to skip"`
	EmbeddedAccessorType   EmbeddedAccessorType      `json:",omitempty" swaggertype:"string" description:"Embedded accessor to use, if any"`
	EmbeddedAccessorConfig string                    `json:",omitempty" description:"Configuration of the embedded accessor, if any"`
}

PathVisitorInfo specifies the information needed by a visitor function to traverse the specified attributes within the registered resource types. The type is serializable as JSON for dynamic configuration and discovery.

type PermissionsData

type PermissionsData map[string]map[string]map[uuid.UUID]bool

PermissionsData represents the Permissions type for query evaluation. This is map[string]map[string]map[uuid.UUID]bool which corresponds to map[ActionCategory]Subjects where Subjects contains UserIDs map[uuid.UUID]bool. The structure is: Permissions[action]["UserIDs"][userUUID] = true

type RelationalExpression

type RelationalExpression struct {
	Path               string // The path of the left operand, which must be an attribute. During evaluation this is used to trigger custom evaluators.
	Operator           string
	Literal            string
	DataType           DataType
	IsLengthExpression bool // True if this is a LEN(attribute) expression
}

type ResolvedPath

type ResolvedPath string

ResolvedPath represents a concrete specific dot-separated path within a structured document (JSON, YAML document, etc.). Array indices are represented as integers within the path. A Kubernetes example is: "spec.template.spec.containers.0.image".

type Resource

type Resource struct {
	ResourceInfo
	ResourceBody string `json:",omitempty" description:"Full configuration data of the resource"`
}

Resource contains the ResourceName, ResourceType, ResourceCategory, and Body for a configuration Element within a configuration Unit.

type ResourceCategory

type ResourceCategory string

ResourceCategory represents the category of syntactic construct represented. Each configuration toolchain defines its own set of valid resource categories, but there are some common categories, such as Resource and AppConfig.

type ResourceCategoryType

type ResourceCategoryType struct {
	ResourceCategory ResourceCategory
	ResourceType     ResourceType
}

ResourceCategoryType is a tuple containing the ResourceCategory and ResourceType.

type ResourceInfo

type ResourceInfo struct {
	ResourceName             ResourceName     `` /* 324-byte string literal not displayed */
	ResourceNameWithoutScope ResourceName     `` /* 270-byte string literal not displayed */
	ResourceType             ResourceType     `` /* 217-byte string literal not displayed */
	ResourceCategory         ResourceCategory `` /* 247-byte string literal not displayed */
}

ResourceInfo contains the ResourceName, ResourceNameWithoutScope, ResourceType, and ResourceCategory for a configuration Element within a configuration Unit.

type ResourceInfoList

type ResourceInfoList []ResourceInfo

type ResourceList

type ResourceList []Resource

type ResourceMutation

type ResourceMutation struct {
	Resource             ResourceInfo              `description:"Identifiers of the resource to which the mutations correspond"`
	ResourceMutationInfo MutationInfo              `description:"Resource-level mutation information, such as for Add, Delete, or Replace"`
	PathMutationMap      MutationMap               `description:"Path-level mutation information; more deeply nested paths override values represented at higher levels"`
	Aliases              map[ResourceName]struct{} `json:",omitempty" description:"Names (with scopes, if any) used in current and prior revisions of this resource"`
	AliasesWithoutScopes map[ResourceName]struct{} `json:",omitempty" description:"Names without scopes used in current and prior revisions of this resource"`
}

type ResourceMutationList

type ResourceMutationList []ResourceMutation

func AddMutations

func AddMutations(mutations, newMutations ResourceMutationList) ResourceMutationList

AddMutations merges newMutations into (existing) mutations and returns the result. It's used to accumulate changes over sequential edits, creating a compiled history of all modifications.

Algorithm:

1. Process Each New Mutation

For each mutation in newMutations:

Resource Matching:

  • First tries to match by current ResourceTypeAndName
  • If not found, checks AliasesWithoutScopes to handle renamed resources
  • If still not found, appends as a new resource mutation

Resource-Level Merge Rules:

| Existing Type    | New Type              | Result              |
|------------------|-----------------------|---------------------|
| Any              | None                  | Keep existing       |
| Any              | Delete or Replace     | Replace with new    |
| None             | Any (non-None)        | Replace with new    |
| Delete           | Any (non-Delete)      | Change to Replace   |
| Add/Update       | Add/Update            | Merge path mutations|

2. Path-Level Merge

When merging Add/Update mutations, the path mutations are combined:

  • Exact path match: Update the value, preserving the original mutation type (except Delete → non-Delete becomes Replace)
  • New path is prefix of existing: Remove existing child paths (the new value supersedes them)
  • New path not found: Add it to the map.

One implication of this approach is that a path and value might appear at the resource level or in the path map at a higher level (path prefix), or even at multiple levels, and can be then overridden by a value of a more specific path. The values need to be patched from least specific to most specific in order to produce the resulting configuration data.

3. Alias Tracking

Merges aliases from both mutations to track all names the resource has had.

Key Behaviors:

  • Accumulative: Designed to be called repeatedly as changes occur
  • Last-write-wins for values: New values replace old values at the same path
  • Type preservation: Original mutation type is preserved (Add stays Add, Update stays Update)
  • Alias awareness: Handles resources that have been renamed between mutations

func AttributeValueListToResourceMutationList added in v0.1.1

func AttributeValueListToResourceMutationList(avl AttributeValueList) ResourceMutationList

AttributeValueListToResourceMutationList converts an AttributeValueList to an equivalent ResourceMutationList by grouping attribute values by resource and creating Update mutations for each attribute path.

func SubtractMutations

func SubtractMutations(mutations, subtractMutations ResourceMutationList) ResourceMutationList

SubtractMutations removes mutations that overlap with subtractMutations from mutations. It's used in three-way merging to ensure that changes made in a target unit take precedence over changes from a source unit.

Use Case:

When merging source unit changes into a target unit:

  • Source: base → sourceEnd (upstream changes)
  • Target: base → target (local customizations)
  • Result: SubtractMutations(sourceMutations, targetMutations) gives changes that won't overwrite local customizations

Both operands are expected to be mutation diffs produced by ComputeMutations. ComputeMutations generates Add, Delete, Update, and None mutations (not Replace). None means the resource was present but not changed. AddMutations is what converts Delete followed by Add to Replace. Replace is handled here just in case, but not expected. Update at the resource level has an empty Value - all values are in the PathMutationMap.

Algorithm:

1. Resource Matching

For each mutation, find corresponding subtraction mutation by:

  • Current ResourceTypeAndName
  • AliasesWithoutScopes from either mutation (handles renamed resources)

2. Resource-Level Subtraction

| Subtract Type | Mutation Type | Result                                     |
|---------------|---------------|--------------------------------------------|
| Delete        | Any           | Remove entirely (target deleted)           |
| Replace       | Any           | Remove entirely (target redefined)         |
| None          | Any           | Keep mutation (target didn't change it)    |
| Any           | None          | Keep mutation (source didn't change it)    |
| Update/Add    | Delete        | Remove (don't delete what target modified) |
| Update/Add    | Update/Add    | Process path-level subtraction             |

3. Path-Level Subtraction

For each path in the mutation's PathMutationMap:

  • Case 1 - Exact match: Path exists in subtractMutations → remove it
  • Case 2 - Subtract path is prefix: e.g., subtract has spec.containers.0, mutation has spec.containers.0.image → remove it (parent was changed)
  • Case 3 - Mutation path is prefix: e.g., mutation has spec.containers.0 (whole block), subtract has spec.containers.0.image → if the mutation is a Delete, skip it entirely (can't partially un-delete). Otherwise, keep the mutation and add the subtractMutation paths. PatchMutations processes paths from least specific to most specific, so the subtractMutation's more specific paths will override the mutation's value.

Key Behaviors:

  • Target precedence: Changes in subtractMutations take priority
  • Alias awareness: Matches resources across renames
  • Partial expansion: Only expands paths as needed, keeping unaffected branches whole
  • Type conversion: If all paths are subtracted from an Update, it becomes None

type ResourceName

type ResourceName string

ResourceName represents a fully qualified resource name of a resource for a specific resource provider.

type ResourcePatch

type ResourcePatch struct {
	Patches yamlpatch.Patch `description:"Isomorphic to a JSON patch, but to be applied to YAML"`
}

type ResourceType

type ResourceType string

ResourceType represents a fully qualified resource type of a resource provider. Each resource provider defines its own set of valid resource types.

type ResourceTypeAndName

type ResourceTypeAndName string

func ResourceTypeAndFullNameFromResourceInfo

func ResourceTypeAndFullNameFromResourceInfo(resourceInfo ResourceInfo) ResourceTypeAndName

ResourceTypeAndFullNameFromResourceInfo returns ResourceType#ResourceName (including namespace/scope) Use this for tracking individual resource instances across scopes (e.g., ResourceStatusMap) For Kubernetes: returns "apiVersion/kind#namespace/name" (e.g., "apps/v1/Deployment#default/my-app")

func ResourceTypeAndNameFromResourceInfo

func ResourceTypeAndNameFromResourceInfo(resourceInfo ResourceInfo) ResourceTypeAndName

type ResourceTypeToPathToVisitorInfoType

type ResourceTypeToPathToVisitorInfoType map[ResourceType]PathToVisitorInfoType

ResourceTypeToPathToVisitorInfoType associates attribute path information with applicable resource types.

type RevisionHash

type RevisionHash int32

RevisionHash represents a crc32.ChecksumIEEE of configuration data. In Go, conversion of uint32 to int32 doesn't lose information. The 32 bits are retained. We use int32 because a number of languages and systems don't handle unsigned integers.

func HashConfigData

func HashConfigData(data []byte) RevisionHash

type Scalar

type Scalar interface {
	~string | ~int | ~bool
}

type UnresolvedPath

type UnresolvedPath string

UnresolvedPath represents a dot-separated path pattern within a structured document (JSON, YAML document, etc.). In addition to literal map keys and array indices, the following segment patterns are supported:

  • .?mapKey:parameterName=value. represents an associative match within an array based on the value of the `mapKey` attribute of a child of the array. This is common, for instance, in Kubernetes. It is replaced with the matched array index. The `parameterName` is the name of the getter or setter parameter that corresponds to the segment.

  • .*?mapKey:parameterName. represents a wildcard match within an array or map where the value of the `mapKey` attribute of a child is recorded for the named parameter of the getter or setter for the attribute.

  • .*@:parameterName. represents a wildcard match within a map where the value of the map key for that segment is recorded for the named parameter of the getter or setter for the attribute.

  • .*. represents a wildcard for an array or map without recording any values for getter or setter parameters.

type ValidationResult

type ValidationResult struct {
	Passed           bool               `description:"True if valid, false otherwise"`
	Index            int                `` /* 191-byte string literal not displayed */
	Details          []string           `json:",omitempty" description:"Optional list of failure details"`
	FailedAttributes AttributeValueList `json:",omitempty" description:"optional list of failed attributes; preferred over Details"`
}

ValidationResult specifies whether a single validation function or sequence of validation functions passed for the given configuration Unit.

type ValidationResultList

type ValidationResultList []ValidationResult

type ValueConstraints

type ValueConstraints struct {
	Regexp     string             `json:",omitempty" description:"Regular expression matching valid values; applies to string parameters"`
	Min        *int               `json:",omitempty" description:"Minimum allowed value; applies to int parameters"`
	Max        *int               `json:",omitempty" description:"Maximum allowed value; applies to int parameters"`
	EnumValues []string           `json:",omitempty" description:"List of valid enum values; applies to enum parameters"`
	Schema     *jsonschema.Schema `json:",omitempty" description:"JSON schema (for embedded JSON values)"`
}

ValueConstraints specifies constraints on a parameter's value.

type ValueFilter

type ValueFilter struct {
	AllowStrings map[string]bool `description:"Set of allowed values; if non-empty, only these values are permitted"`
	DenyStrings  map[string]bool `description:"Set of denied values; these values are always rejected"`
}

ValueFilter specifies allow and deny sets for value validation. If AllowStrings is non-empty, only values in the map are allowed. Values in DenyStrings are always rejected.

type VisitorRelationalExpression

type VisitorRelationalExpression struct {
	RelationalExpression
	// Fields for split path feature used by function visitors
	VisitorPath string // Left side of .| for visitor
	SubPath     string // Right side of .| for property check
	IsSplitPath bool   // Whether this uses the .|syntax
}

VisitorRelationalExpression extends RelationalExpression with visitor-specific fields

func ParseAndValidateBinaryExpression

func ParseAndValidateBinaryExpression(decodedQueryString string) (string, *VisitorRelationalExpression, error)

func ParseAndValidateWhereFilter

func ParseAndValidateWhereFilter(queryString string) ([]*VisitorRelationalExpression, error)

func ParseAndValidateWhereFilterForImport

func ParseAndValidateWhereFilterForImport(queryString string) ([]*VisitorRelationalExpression, error)

ParseAndValidateWhereFilterForImport parses a where filter specifically for import context

type YAMLPayload

type YAMLPayload struct {
	Payload string
}

Jump to

Keyboard shortcuts

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