Documentation
¶
Overview ¶
Package api implements the data types and messages exchanged by the ConfigHub function executor and its clients, in Go.
Index ¶
- Constants
- Variables
- func CombineOutputs(functionName string, instance string, newOutputType OutputType, ...) (map[OutputType]any, []string)
- func ConfigDataHasChanged(functionContext *FunctionContext, data []byte) bool
- func DataTypeIsSerializedAsString(dataType DataType) bool
- func EvaluateExpression(expr *RelationalExpression, leftValue any, rightValue any, ...) (bool, error)
- func EvaluatePermissionsExpression(operator string, leftValue PermissionsData, rightValue interface{}, ...) (bool, error)
- func FindAncestorPath(m MutationMap, path ResolvedPath) (ResolvedPath, MutationInfo, bool)
- func GetLogicalOperator(decodedQueryString string) (string, string)
- func GetToolchainPath(toolchain workerapi.ToolchainType) string
- func HasAncestorPath(m MutationMap, path ResolvedPath) bool
- func InitTypeSchemas()
- func IsEmptyDataHash(hash DataHash) bool
- func IsSupportedToolchain(toolchain workerapi.ToolchainType) bool
- func IsUUID(s string) bool
- func NoMutations(mutations ResourceMutationList) bool
- func OffsetMutations(mutations ResourceMutationList, offset int64)
- func ParseInClause(decodedQueryString string) (string, string, error)
- func ParseInClauseValues(literal string) []string
- func ParseWhereFilterForImport(queryString string) ([]ImportFilter, ImportOptions, error)
- func SkipWhitespace(decodedQueryString string) string
- func SkipWhitespaceWithLimit(decodedQueryString string, limit int) string
- func SupportedToolchainsToString() string
- func UnmarshalOutput(outputBytes []byte, outputType OutputType) (any, error)
- func ValidateImportOperator(operator string) error
- func ValidatePath(path string) error
- type AttributeDescriptor
- type AttributeDetails
- type AttributeIdentifier
- type AttributeInfo
- type AttributeMetadata
- type AttributeName
- type AttributeNameToAttributeDescriptor
- type AttributeNameToResourceTypeToPathToVisitorInfoType
- type AttributeSelector
- type AttributeValue
- type AttributeValueList
- type Binding
- type BindingList
- type CustomStringComparator
- type DataHash
- type DataType
- type EmbeddedAccessorType
- type FunctionArgument
- type FunctionContext
- type FunctionIDs
- type FunctionInvocation
- type FunctionInvocationList
- type FunctionInvocationRequest
- type FunctionInvocationResponse
- type FunctionInvocationSuccessResponse
- type FunctionOptions
- type FunctionOutput
- type FunctionParameter
- type FunctionSignature
- type FunctionType
- type ImportFilter
- type ImportOptions
- type Issue
- type MutationInfo
- type MutationMap
- type MutationMapEntry
- type MutationType
- type OutputType
- type PatchMap
- type PathPrefixIndex
- type PathToVisitorInfoType
- type PathVisitorInfo
- type PermissionsData
- type RelationalExpression
- type ResolvedPath
- type Resource
- type ResourceCategory
- type ResourceCategoryType
- type ResourceInfo
- type ResourceInfoList
- type ResourceList
- type ResourceMutation
- type ResourceMutationIndex
- type ResourceMutationList
- type ResourceName
- type ResourcePatch
- type ResourceType
- type ResourceTypeAndName
- type ResourceTypeToPathToVisitorInfoType
- type RevisionHash
- type Scalar
- type Score
- type UnresolvedPath
- type ValidationResult
- type ValidationResultList
- type ValueConstraints
- type ValueFilter
- type VisitorRelationalExpression
- func ParseAndValidateBinaryExpression(decodedQueryString string) (string, *VisitorRelationalExpression, error)
- func ParseAndValidateWhereFilter(queryString string) ([]*VisitorRelationalExpression, error)
- func ParseAndValidateWhereFilterForImport(queryString string) ([]*VisitorRelationalExpression, error)
- type YAMLPayload
Constants ¶
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") DataTypeAttributeInfoList = DataType("AttributeInfoList") 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") )
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") )
const ( ResourceCategoryInvalid = ResourceCategory("Invalid") ResourceCategoryResource = ResourceCategory("Resource") ResourceCategoryDyanmicData = ResourceCategory("DynamicData") ResourceCategoryAppConfig = ResourceCategory("AppConfig") )
const ( // This is used to indicate that no path is registered in the path registry AttributeNameNone = AttributeName("none") // TODO: Convert these to attribute groups once they are registered under more specific attributes. AttributeNameDetail = AttributeName("detail") AttributeNameDefaultName = AttributeName("default-name") // Attributes with registered paths AttributeNameResourceName = AttributeName("resource-name") AttributeNameContainerName = AttributeName("container-name") AttributeNameContainerImage = AttributeName("container-image") AttributeNameContainerImages = AttributeName("container-images") // TODO: dedupe with container-image AttributeNameContainerRepositoryURI = AttributeName("container-repository-uri") AttributeNameContainerImageReference = AttributeName("container-image-reference") AttributeNameHostname = AttributeName("hostname") AttributeNameDomain = AttributeName("domain") AttributeNameSubdomain = AttributeName("subdomain") )
const ( FunctionTypePathVisitor = FunctionType("PathVisitor") FunctionTypeCustom = FunctionType("Custom") )
const ( EvaluatorTemplate = "template" EvaluatorCEL = "cel" )
const ( ScoreCritical = Score("Critical") ScoreHigh = Score("High") ScoreMedium = Score("Medium") ScoreLow = Score("Low") ScoreNone = Score("") )
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.
const (
EmbeddedAccessorRegexp = "Regexp"
)
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.
const MaxAttributeNameLength = 128
const MaxConfigDataLength = 64 * 1024 * 1024 // 64MB
const MaxDataTypeLength = 32
const MaxEmbeddedAccessorConfigLength = 1024
const MaxFilterLength = 8192
const MaxFunctionDescriptionLength = 1024
const MaxFunctionErrorMessageLength = 1024
const MaxFunctionNameLength = 128
TODO: Validate these
const MaxFunctionNumberOfErrors = 1024
const MaxFunctionOutputLength = 64 * 1024 * 1024 // 64MB
const MaxFunctionParameterNameLength = 128
const MaxNumFunctionArguments = 32
const MaxPathLength = 512
const MaxResourceTypeLength = 128
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
const (
ResourceTypeAny = ResourceType("*")
)
Variables ¶
var ( ValidationResultTrue = ValidationResult{Passed: true} ValidationResultFalse = ValidationResult{Passed: false} )
var ( LogicalOperatorRegexp = regexp.MustCompile(logicalOperatorRegexpString) // Exported Literal patterns BooleanLiteralRegexp = regexp.MustCompile(booleanLiteralRegexpString) IntegerLiteralRegexp = regexp.MustCompile(integerLiteralRegexpString) SafeStringCharsOnlyRegexp = regexp.MustCompile("^" + safeStringCharsRegexpString + "$") StringLiteralRegexp = regexp.MustCompile(stringLiteralRegexpString) )
var ( ResourceListSchema jsonschema.Schema ResourceInfoListSchema jsonschema.Schema AttributeValueListSchema jsonschema.Schema ValidationResultListSchema jsonschema.Schema YAMLPayloadSchema jsonschema.Schema ResourceMutationListSchema jsonschema.Schema )
Pre-generated JSON schemas for common function output types. There is just one set of pre-generated schemas for all executors and all handlers. Call InitTypeSchemas() to ensure they are initialized before use.
var EmptyDataHash = HashConfigDataSHA256(nil)
EmptyDataHash is the SHA256 hash of an empty byte slice.
var ImportSupportedOperators = []string{"=", "!=", "IN", "NOT IN"}
Import-specific operator support
var NumberToScore = map[int]Score{ 4: ScoreCritical, 3: ScoreHigh, 2: ScoreMedium, 1: ScoreLow, 0: ScoreNone, }
var ScoreToNumber = map[Score]int{ ScoreCritical: 4, ScoreHigh: 3, ScoreMedium: 2, ScoreLow: 1, ScoreNone: 0, }
var SupportedToolchains = map[workerapi.ToolchainType]string{ workerapi.ToolchainConfigHubYAML: "/confighub", workerapi.ToolchainKubernetesYAML: "/kubernetes", workerapi.ToolchainAppConfigProperties: "/properties", workerapi.ToolchainAppConfigYAML: "/yaml", workerapi.ToolchainAppConfigTOML: "/toml", workerapi.ToolchainAppConfigINI: "/ini", workerapi.ToolchainAppConfigJSON: "/json", workerapi.ToolchainAppConfigEnv: "/env", workerapi.ToolchainOpenTofuHCL: "/opentofu", }
var ValidWhereResourcePaths = map[string]bool{ "ConfigHub.ResourceName": true, "ConfigHub.ResourceNameWithoutScope": true, "ConfigHub.ResourceType": true, "ConfigHub.ResourceCategory": true, }
ValidWhereResourcePaths lists the supported ConfigHub metadata paths for WhereResource filtering.
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 ConfigDataHasChanged ¶
func ConfigDataHasChanged(functionContext *FunctionContext, data []byte) bool
ConfigDataHasChanged returns true if the given data differs from the previous data identified by the hashes in the FunctionContext. It prefers PreviousDataHash (SHA256) when available, falling back to PreviousContentHash (CRC32) for legacy units.
func DataTypeIsSerializedAsString ¶
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 FindAncestorPath ¶
func FindAncestorPath(m MutationMap, path ResolvedPath) (ResolvedPath, MutationInfo, bool)
FindAncestorPath walks up from path to find the most specific ancestor (or exact match) present in the map. It iteratively removes the last path segment and checks for a match. Since dots within segments are escaped as ~1, splitting on "." is safe. Returns the matching path, its MutationInfo, and whether a match was found.
func GetLogicalOperator ¶
func GetToolchainPath ¶
func GetToolchainPath(toolchain workerapi.ToolchainType) string
func HasAncestorPath ¶
func HasAncestorPath(m MutationMap, path ResolvedPath) bool
HasAncestorPath returns true if any ancestor of path (not including path itself) exists in the map. An ancestor is a path formed by removing one or more trailing segments.
func InitTypeSchemas ¶
func InitTypeSchemas()
InitTypeSchemas initializes the shared JSON schemas for common function types. It is safe to call multiple times; initialization only happens once.
func IsEmptyDataHash ¶ added in v0.1.13
IsEmptyDataHash returns true if the given hash represents empty configuration data.
func IsSupportedToolchain ¶
func IsSupportedToolchain(toolchain workerapi.ToolchainType) bool
func IsUUID ¶
IsUUID returns true if s looks like a valid UUID (8-4-4-4-12 hex format). Used to avoid matching on placeholder or other non-UUID ResourceID values.
func NoMutations ¶
func NoMutations(mutations ResourceMutationList) bool
func OffsetMutations ¶
func OffsetMutations(mutations ResourceMutationList, offset int64)
func ParseInClause ¶
ParseInClause parses an IN clause like "('value1', 'value2', 'value3')" Exported for use by internal packages
func ParseInClauseValues ¶
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 ¶
SkipWhitespace skips whitespace characters with optional limit
func SkipWhitespaceWithLimit ¶
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 ¶
ValidateImportOperator validates that an operator is supported for import queries
func ValidatePath ¶
ValidatePath validates a path string against the path name regex.
Types ¶
type AttributeDescriptor ¶
type AttributeDescriptor struct {
AttributeName AttributeName
AttributeGroup []AttributeName // List of attributes to expand to, if non-empty
AttributeDetails
}
AttributeDescriptor contains details about an attribute that is valid for all paths of the attribute. In the case of an attribute group, it contains the list of attributes the group expands to.
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."`
Details *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 AttributeNameToAttributeDescriptor ¶
type AttributeNameToAttributeDescriptor map[AttributeName]*AttributeDescriptor
type AttributeNameToResourceTypeToPathToVisitorInfoType ¶
type AttributeNameToResourceTypeToPathToVisitorInfoType map[AttributeName]ResourceTypeToPathToVisitorInfoType
AttributeNameToResourceTypeToPathToVisitorInfoType associates paths of resource types with an attribute attribute class for traversal/visitation by functions.
type AttributeSelector ¶ added in v0.1.13
type AttributeSelector struct {
WhereResource string `json:",omitempty"` // where expression to select resource(s)
Path UnresolvedPath `json:",omitempty" swaggertype:"string"` // path expression
}
AttributeSelector identifies a value to extract from configuration data.
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 */
FunctionName string `json:",omitempty" description:"Name of the function invocation corresponding to the output"`
Score Score `json:",omitempty" description:"Score of finding attributed to this Path"`
Issues []Issue `json:",omitempty" description:"Issues found with the attribute"`
}
AttributeValue provides the value of an attribute in addition to information about the attribute.
type AttributeValueList ¶
type AttributeValueList []AttributeValue
type Binding ¶
type Binding struct {
// AttributeName is the shared attribute name that matched the need to the provide.
AttributeName AttributeName `json:",omitempty" swaggertype:"string"`
// DataType of the bound value.
DataType DataType `json:",omitempty" swaggertype:"string"`
// ProvidedResource identifies the resource in the upstream unit that provides the value.
ProvidedResource ResourceInfo
// ProvidedPath is the resolved path within the provided resource.
ProvidedPath ResolvedPath `json:",omitempty" swaggertype:"string"`
// InLiveState indicates whether the provided value comes from the upstream unit's LiveState
// rather than its Data.
InLiveState bool `json:",omitempty"`
// NeededResource identifies the resource in the downstream unit that needs the value.
NeededResource ResourceInfo
// NeededPath is the resolved path within the needed resource.
NeededPath ResolvedPath `json:",omitempty" swaggertype:"string"`
// OriginalValue is the value at the needed path when the binding was first created.
OriginalValue any `json:",omitempty"`
// Expression is reserved for future use (e.g., CEL transformation expressions).
Expression string `json:",omitempty"`
// AutoUpdate indicates whether this binding should be automatically updated
// when the provided value changes. If false, the binding is manual and will
// not be modified by automatic resolution.
AutoUpdate bool
}
Binding represents a single needs/provides binding between two units. It records which provided attribute satisfies which needed attribute, and captures the original value at the time the binding was first created.
type BindingList ¶
type BindingList []Binding
BindingList is a list of Binding entries stored on a Link.
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 DataHash ¶
type DataHash string
DataHash represents a SHA256 hash of configuration data, encoded as a hexadecimal string. This is the same hash algorithm used by git and container images.
func HashConfigDataSHA256 ¶
HashConfigDataSHA256 computes the SHA256 hash of configuration data and returns it as a hex string.
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).
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 `` /* 178-byte string literal not displayed */
PreviousDataHash DataHash `` /* 147-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"`
SpaceSlug string `json:",omitempty" description:"Slug of the Unit's Space"`
UnitID uuid.UUID `description:"ID of the Unit the configuration data is associated with"`
UnitSlug string `json:",omitempty" description:"Slug of the Unit"`
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"`
WhereResource string `` /* 246-byte string literal not displayed */
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 FunctionOptions ¶
type FunctionOptions struct {
WhereResourceExpressions []*VisitorRelationalExpression
}
FunctionOptions contains options that affect how functions operate on resources.
func ParseAndValidateWhereResource ¶
func ParseAndValidateWhereResource(whereResource string) (*FunctionOptions, error)
ParseAndValidateWhereResource parses and validates a WhereResource filter string. It returns FunctionOptions with the parsed expressions, or nil if whereResource is empty. Paths with the "ConfigHub." prefix are validated against ValidWhereResourcePaths. Other paths are treated as resource field paths (e.g., "spec.replicas") and are resolved from the YAML document at evaluation time.
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 Issue ¶
type Issue struct {
Identifier string `` /* 188-byte string literal not displayed */
Message string `description:"A more detailed and specific explanation of the issue found"`
}
Issue describes an issue found with a configuration attribute/path, such as a validation failure, policy violation, recommendation, etc.
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
}
func SortedMutationMapEntries ¶
func SortedMutationMapEntries(m MutationMap) []MutationMapEntry
SortedMutationMapEntries returns the entries of a MutationMap sorted lexicographically by path. Since dots within path segments are escaped (as ~1), the dot separator always denotes segment boundaries, so lexicographic order naturally places parent paths before children (e.g., "spec" < "spec.template" < "spec.template.spec").
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 ¶
type PatchMap map[ResourceTypeAndName]ResourcePatch
PatchList is a list of patches applied to specified resources.
type PathPrefixIndex ¶
type PathPrefixIndex struct {
SortedPaths []ResolvedPath
}
PathPrefixIndex provides efficient lookup of child paths (paths that start with a given prefix + ".") using binary search on a sorted slice of paths. It is built from a MutationMap and used by AddMutations and SubtractMutations to avoid iterating over all paths when checking for prefix relationships.
func NewPathPrefixIndex ¶
func NewPathPrefixIndex(m MutationMap) *PathPrefixIndex
NewPathPrefixIndex builds a PathPrefixIndex from a MutationMap.
func (*PathPrefixIndex) ChildPaths ¶
func (idx *PathPrefixIndex) ChildPaths(prefix ResolvedPath) []ResolvedPath
ChildPaths returns all paths in the index that start with prefix + ".". Uses binary search to find the range, returning O(log n + k) where k is the result count.
func (*PathPrefixIndex) HasChildPath ¶
func (idx *PathPrefixIndex) HasChildPath(prefix ResolvedPath) bool
HasChildPath returns true if any path in the index starts with prefix + ".". Uses binary search for O(log n) performance.
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"`
Details *AttributeDetails `json:",omitempty" description:"Additional attribute details"`
IsNeeded bool `json:",omitempty" description:"Whether this path is a needed value"`
IsProvided bool `json:",omitempty" description:"Whether this path is a provided value"`
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 ¶
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 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 */
ResourceID string `` /* 312-byte string literal not displayed */
}
ResourceInfo contains the ResourceName, ResourceNameWithoutScope, ResourceType, ResourceCategory, and ResourceID 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 ResourceMutationIndex ¶
type ResourceMutationIndex struct {
NameMap map[ResourceTypeAndName]int
AliasNameMap map[ResourceTypeAndName]int // from AliasesWithoutScopes of indexed mutations
ResourceIDMap map[string]int
}
ResourceMutationIndex provides efficient lookup of resources in a ResourceMutationList by ResourceID, ResourceTypeAndName, and AliasesWithoutScopes. It is used by AddMutations, SubtractMutations, PatchMutations, and FindMutationIndex to match resources consistently.
func NewResourceMutationIndex ¶
func NewResourceMutationIndex(mutations ResourceMutationList) *ResourceMutationIndex
NewResourceMutationIndex builds an index from a ResourceMutationList. For duplicate keys, the last entry wins.
func (*ResourceMutationIndex) Find ¶
func (idx *ResourceMutationIndex) Find(resource ResourceInfo, callerAliases map[ResourceName]struct{}) (int, bool)
Find looks up a resource in the index using multiple strategies:
- ResourceID match
- ResourceTypeAndName match
- callerAliases against indexed mutation names
- Indexed mutation aliases against the caller's name
type ResourceMutationList ¶
type ResourceMutationList []ResourceMutation
func AttributeValueListToResourceMutationList ¶
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.
type ResourceName ¶
type ResourceName string
ResourceName represents a fully qualified resource name of a resource for a specific resource provider.
type ResourcePatch ¶
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. Deprecated: Use DataHash (SHA256) instead for new code. 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 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 */
FunctionName string `json:",omitempty" description:"Name of the function invocation corresponding to the result"`
MaxScore Score `json:",omitempty" description:"Maximum score of all findings"`
Details []string `` /* 168-byte string literal not displayed */
Issues []Issue `` /* 165-byte string literal not displayed */
FailedAttributes AttributeValueList `` /* 134-byte string literal not displayed */
}
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 `` /* 145-byte string literal not displayed */
DenyStrings map[string]bool `` /* 130-byte string literal not displayed */
AllowRegexp string `` /* 165-byte string literal not displayed */
DenyRegexp string `` /* 150-byte string literal not displayed */
AllowBool *bool `json:",omitempty" description:"Required boolean value; if set, only this boolean value is permitted"`
Min *int `json:",omitempty" description:"Minimum allowed integer value (inclusive)"`
Max *int `json:",omitempty" description:"Maximum allowed integer value (inclusive)"`
}
ValueFilter specifies allow and deny rules for value validation. For strings: AllowStrings/DenyStrings use exact match sets; AllowRegexp/DenyRegexp use regular expressions. AllowStrings and AllowRegexp are mutually exclusive. DenyStrings and DenyRegexp are mutually exclusive. For bools: AllowBool specifies the required boolean value (pointer; nil means any bool is allowed). For ints: Min and Max specify an inclusive range (pointer; nil means unbounded). 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
}