Documentation
¶
Overview ¶
Copyright 2026 Philipp Hossner
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Package templating provides template rendering capabilities using the Scriggo template engine.
This package offers a unified interface for compiling and rendering templates using Go template syntax via the Scriggo engine.
Templates are pre-compiled at initialization for optimal runtime performance and early detection of syntax errors.
Index ¶
- Constants
- Variables
- func BindAllIncrementalResources(resources any, lease IncrementalResourceInvocationLease) (any, error)
- func BindImmutableResourceInputs(templateContext map[string]any, ctx context.Context) error
- func BindIncrementalImmutableInputs(templateContext map[string]any, ctx context.Context) error
- func CanonicalIncrementalHTTPArgs(args ...any) ([]any, error)
- func CanonicalIncrementalResourceKey(index int, key any) (string, error)
- func CanonicalIncrementalResourceKeys(keys ...any) ([]string, error)
- func CanonicalIncrementalResourceValue(index int, key reflect.Value) (string, error)
- func ConsumeIncrementalDetachedValue(value *IncrementalDetachedValue) (any, error)
- func DeriveResourceJSONPath(item any, path string, value any) (any, error)
- func ExactCycleReplayExecutionActive(ctx context.Context) bool
- func FormatCompilationError(err error, templateName, templateContent string) string
- func IncrementalResourceStoreType(storeType reflect.Type) reflect.Type
- func IncrementalScope(ctx context.Context) (string, bool)
- func MergeStatusLists(payload, current map[string]any, ownership string) (map[string]any, error)
- func RegisterExactCyclePreviousOutputDeclaration(declaration any)
- func RegisterIncrementalImmutableCertificate(ctx context.Context, certificate *IncrementalImmutableCertificate) error
- func RegisterIncrementalImmutableInputs(ctx context.Context, values ...any) error
- func RegisterIncrementalResourceDeclaration(declaration any)
- func RegisterIncrementalResourceFunctionBindings(owner *IncrementalResourceFunctionBindingOwner, resources any, ...) error
- func RegisterIncrementalResourceFunctionTrampolines(owner *IncrementalResourceFunctionBindingOwner, resources any, ...) error
- func RenderErrorMessage(err error) string
- func WithBoundImmutableResourceInputs(ctx context.Context, templateContext map[string]any) (context.Context, error)
- func WithCycleTime(ctx context.Context, now time.Time) context.Context
- func WithExactCycleRootInvocation(ctx context.Context, invocation ExactCycleRootInvocation) context.Context
- func WithImmutableResourceInputs(ctx context.Context) context.Context
- func WithIncrementalEventRecorder(ctx context.Context, recorder IncrementalEventRecorder) context.Context
- func WithIncrementalExecutionLease(ctx context.Context, lease IncrementalExecutionLease) context.Context
- func WithIncrementalImmutableCapabilityInputs(ctx context.Context, values ...any) context.Context
- func WithIncrementalImmutableCertificates(ctx context.Context, certificates ...*IncrementalImmutableCertificate) context.Context
- func WithIncrementalImmutableInputs(ctx context.Context, values ...any) context.Context
- func WithIncrementalRenderer(ctx context.Context, renderer IncrementalRenderer) context.Context
- func WithIncrementalResourceDeriver(ctx context.Context, deriver IncrementalResourceDeriver) context.Context
- func WithIncrementalScope(ctx context.Context, scope string) context.Context
- func WithIncrementalStatusPatchRecorder(ctx context.Context, recorder IncrementalStatusPatchRecorder) context.Context
- func WithIncrementalTransitionTime(ctx context.Context, value string) context.Context
- func WithWorkerGate(ctx context.Context, gate WorkerGate) context.Context
- type CompilationError
- type ConcreteJSONPath
- type Engine
- type EventCollector
- func (c *EventCollector) Events() []RenderedEvent
- func (c *EventCollector) ExactCycleProtocolState() (ExactCycleProtocolState, error)
- func (c *EventCollector) Register(namespace, name, apiVersion, kind, eventType, reason, message string) error
- func (c *EventCollector) Snapshot(previous ...*RenderedEventSnapshot) (*RenderedEventSnapshot, error)
- type ExactCycleProtocolState
- type ExactCycleProtocolStateProvider
- type ExactCycleReplayInputs
- type ExactCycleReplayProgram
- func (p *ExactCycleReplayProgram) Begin(ctx context.Context, generation uint64, templateContext map[string]any) (context.Context, *ExactCycleReplayInputs, error)
- func (p *ExactCycleReplayProgram) BeginWithInvocations(ctx context.Context, generation uint64, templateContext map[string]any, ...) (context.Context, *ExactCycleReplayInputs, error)
- func (p *ExactCycleReplayProgram) Capture(templateContext map[string]any) (*ExactCycleReplayInputs, error)
- func (p *ExactCycleReplayProgram) ExecutionContext(ctx context.Context) (context.Context, error)
- func (p *ExactCycleReplayProgram) Matches(previous *ExactCycleReplayInputs, templateContext map[string]any) (bool, error)
- func (p *ExactCycleReplayProgram) OutputOnlyRoot(name string) (bool, error)
- func (p *ExactCycleReplayProgram) RequiresUnchangedInputRoots() (bool, error)
- func (p *ExactCycleReplayProgram) UsesPreviousOutput(name string) (bool, error)
- type ExactCycleRootInvocation
- type ExistenceJSONPath
- type FailError
- type FileRegistrar
- type FilterFunc
- type GlobalFunc
- type GlobalUsageIntrospector
- type HTTPFetcher
- type IncludeStats
- type IncrementalBackendPlanRegistrar
- type IncrementalBindingInputSnapshot
- type IncrementalBindingPlannerExecutor
- type IncrementalBindingSnapshotPlanner
- type IncrementalCertifiedValueReader
- type IncrementalCertifiedValues
- type IncrementalComponentBatchError
- type IncrementalComponentBatchExecutor
- type IncrementalComponentBatchItem
- type IncrementalComponentContextOptions
- type IncrementalComponentContextTable
- func (t *IncrementalComponentContextTable) Prepare(index int, parent context.Context, options IncrementalComponentContextOptions, ...) (context.Context, error)
- func (t *IncrementalComponentContextTable) Seal(index int, templateContext map[string]any, capabilities ...any) error
- func (t *IncrementalComponentContextTable) SealValues(index int, values IncrementalComponentContextValues) error
- type IncrementalComponentContextValues
- type IncrementalComponentExecutor
- type IncrementalComponentSourceTransaction
- type IncrementalComponentSourceTransactionBatch
- type IncrementalComponentSourceTransactionChild
- type IncrementalComponentSourceTransactionLifecycle
- type IncrementalComponentSourceTransactionWave
- type IncrementalComponentSourceTransactionsInput
- type IncrementalComponentSourceTransactionsRenderer
- type IncrementalComponentVectorCarrierEligibility
- type IncrementalComponentVectorCarrierLane
- type IncrementalComponentVectorCarrierWave
- type IncrementalComponentVectorCarrierWaveLane
- type IncrementalComponentVectorCarrierWaveLifecycle
- type IncrementalComponentVectorCarrierWavesInput
- type IncrementalComponentVectorCarrierWavesRenderer
- type IncrementalComponentVectorEligibility
- type IncrementalComponentVectorInput
- type IncrementalComponentVectorLifecycle
- type IncrementalComponentVectorRenderer
- type IncrementalDetachedValue
- type IncrementalEventRecorder
- type IncrementalExecutionLease
- type IncrementalImmutableCertificate
- type IncrementalRankedFragmentBytesReader
- type IncrementalRankedFragmentJoinReader
- type IncrementalRankedFragmentReader
- type IncrementalRankedTextFragmentJoinReader
- type IncrementalRankedTextFragmentReader
- type IncrementalRenderer
- type IncrementalResourceBinder
- type IncrementalResourceBoundFrameFactory
- type IncrementalResourceDeriver
- type IncrementalResourceFunctionBinding
- type IncrementalResourceFunctionBindingOwner
- type IncrementalResourceInvocationLease
- type IncrementalSourceTransactionChildSelector
- type IncrementalSourceTransactionResourceBinder
- type IncrementalSourceTransactionSelectorAuthenticator
- type IncrementalStatusPatchRecorder
- type IncrementalTextFragmentRenderer
- type IncrementalValueCounter
- type IncrementalValueReader
- type Options
- type PathResolver
- type PlanRegistrar
- type PostProcessBatchError
- type PostProcessBatcher
- type PostProcessPublication
- type PostProcessReuseProof
- type PostProcessReuseProver
- type PostProcessTransaction
- type PostProcessor
- type PostProcessorConfig
- type PostProcessorType
- type RawTextRenderer
- type RegexReplaceProcessor
- type RenderError
- type RenderTimeoutError
- type RenderedEvent
- type RenderedEventSnapshot
- func (s *RenderedEventSnapshot) AddedSince(previous *RenderedEventSnapshot) ([]RenderedEvent, error)
- func (s *RenderedEventSnapshot) Events() ([]RenderedEvent, error)
- func (s *RenderedEventSnapshot) ExactEqual(other *RenderedEventSnapshot) (bool, error)
- func (s *RenderedEventSnapshot) Len() (int, error)
- func (s *RenderedEventSnapshot) SameRoot(other *RenderedEventSnapshot) (bool, error)
- func (s *RenderedEventSnapshot) ValidateAuthentication() error
- type RenderedResource
- type RenderedResourceCollector
- func (c *RenderedResourceCollector) Register(apiVersion, kind, namespace, name string, object map[string]any) error
- func (c *RenderedResourceCollector) RegisterWithCreateOnlyFields(apiVersion, kind, namespace, name string, object map[string]any, ...) error
- func (c *RenderedResourceCollector) Resources() []RenderedResource
- func (c *RenderedResourceCollector) Snapshot(previous ...*RenderedResourceSnapshot) (*RenderedResourceSnapshot, error)
- func (c *RenderedResourceCollector) Validate() error
- type RenderedResourceSnapshot
- func (s *RenderedResourceSnapshot) ExactEqual(other *RenderedResourceSnapshot) (bool, error)
- func (s *RenderedResourceSnapshot) Len() (int, error)
- func (s *RenderedResourceSnapshot) Resources() ([]RenderedResource, error)
- func (s *RenderedResourceSnapshot) SameRoot(other *RenderedResourceSnapshot) (bool, error)
- func (s *RenderedResourceSnapshot) ValidateAuthentication() error
- type ResourceDeriver
- type ResourceStore
- type RuntimeEnvironment
- type ScriggoEngine
- func (e *ScriggoEngine) AppendTraces(other Engine)
- func (e *ScriggoEngine) BeginPostProcessTransaction(ctx context.Context) (context.Context, PostProcessTransaction)
- func (e *ScriggoEngine) BindIncrementalResources(templateName string, resources any, lease IncrementalResourceInvocationLease) (any, error)
- func (e *ScriggoEngine) BindIncrementalSourceTransactionResources(templateNames []string, resources any, ...) (any, error)
- func (e *ScriggoEngine) ClearVMPool()
- func (e *ScriggoEngine) DisableFilterDebug()
- func (e *ScriggoEngine) DisableTracing()
- func (e *ScriggoEngine) EnableFilterDebug()
- func (e *ScriggoEngine) EnableTracing()
- func (e *ScriggoEngine) EntryPointUsedGlobals(name string) []string
- func (e *ScriggoEngine) EntryPointUsedNativeValueAccesses(name string) []scriggo.UsedNativeValueAccess
- func (e *ScriggoEngine) GetRawTemplate(templateName string) (string, error)
- func (e *ScriggoEngine) GetTraceOutput() string
- func (e *ScriggoEngine) GlobalUsage(name string) (used, known bool)
- func (e *ScriggoEngine) HasTemplate(templateName string) bool
- func (e *ScriggoEngine) IncrementalComponentSourceTransactionsEligibility() bool
- func (e *ScriggoEngine) IncrementalComponentVectorCarrierDiagnostic() error
- func (e *ScriggoEngine) IncrementalComponentVectorCarrierEligibility() (IncrementalComponentVectorCarrierEligibility, bool)
- func (e *ScriggoEngine) IncrementalComponentVectorEligibility(templateName string) (IncrementalComponentVectorEligibility, bool)
- func (e *ScriggoEngine) IsFilterDebugEnabled() bool
- func (e *ScriggoEngine) IsProfilingEnabled() bool
- func (e *ScriggoEngine) IsTracingEnabled() bool
- func (e *ScriggoEngine) MatchIncrementalBindingInputs(entryPoints []string, bindingContext map[string]any, ...) bool
- func (e *ScriggoEngine) PostProcess(ctx context.Context, templateName, text string) (string, error)
- func (e *ScriggoEngine) PostProcessBatch(ctx context.Context, templateName string, inputs []string) ([]string, error)
- func (e *ScriggoEngine) PostProcessReuseProof(templateName string) (*PostProcessReuseProof, error)
- func (e *ScriggoEngine) PrepareExactCycleReplay(entryPoints []string) (*ExactCycleReplayProgram, error)
- func (e *ScriggoEngine) RawTextRenderInstrumented() bool
- func (e *ScriggoEngine) Render(ctx context.Context, templateName string, templateContext map[string]any) (string, error)
- func (e *ScriggoEngine) RenderIncrementalBindings(ctx context.Context, templateName string, bindingContext map[string]any) ([]byte, error)
- func (e *ScriggoEngine) RenderIncrementalBindingsSnapshot(ctx context.Context, templateName string, ...) ([]byte, error)
- func (e *ScriggoEngine) RenderIncrementalComponent(ctx context.Context, templateName string, templateContext map[string]any) (string, error)
- func (e *ScriggoEngine) RenderIncrementalComponentSourceTransactions(ctx context.Context, input IncrementalComponentSourceTransactionsInput) (err error)
- func (e *ScriggoEngine) RenderIncrementalComponentVector(ctx context.Context, templateName string, ...) (err error)
- func (e *ScriggoEngine) RenderIncrementalComponentVectorCarrierWaves(ctx context.Context, input IncrementalComponentVectorCarrierWavesInput) (err error)
- func (e *ScriggoEngine) RenderIncrementalComponents(ctx context.Context, templateName string, ...) ([]string, error)
- func (e *ScriggoEngine) RenderRawTo(ctx context.Context, templateName string, templateContext map[string]any, ...) ([]IncludeStats, error)
- func (e *ScriggoEngine) RenderWithProfiling(ctx context.Context, templateName string, templateContext map[string]any) (string, []IncludeStats, error)
- func (e *ScriggoEngine) RenderWithSourceMap(ctx context.Context, templateName string, templateContext map[string]any) (raw string, spans []SourceSpan, err error)
- func (e *ScriggoEngine) ReuseExactCycleRoot(ctx context.Context, templateName string) error
- func (e *ScriggoEngine) SnapshotIncrementalBindingInputs(entryPoints []string, bindingContext map[string]any) (*IncrementalBindingInputSnapshot, error)
- func (e *ScriggoEngine) TemplateCount() int
- func (e *ScriggoEngine) TemplateNames() []string
- type SharedContext
- func (s *SharedContext) ComputeIfAbsent(key string, compute func() any) (any, bool)
- func (*SharedContext) Count(_, _ string) int
- func (s *SharedContext) ExactCycleProtocolState() (ExactCycleProtocolState, error)
- func (s *SharedContext) Get(key string) any
- func (*SharedContext) Publish(_, _ string, _ any) string
- func (*SharedContext) PublishRanked(_, _, _ string, _ any) string
- func (*SharedContext) Select(_, _, _ string) (any, bool)
- func (*SharedContext) SelectValues(_, _ string) []any
- func (*SharedContext) Unique(_, _, _ string) string
- type SharedContributionContext
- type SharedContributionRecorder
- type SharedValueSelector
- type SourceFrame
- type SourceSpan
- type StatusPatch
- type StatusPatchCollector
- func (c *StatusPatchCollector) ExactCycleProtocolState() (ExactCycleProtocolState, error)
- func (c *StatusPatchCollector) Patches() ([]StatusPatch, error)
- func (c *StatusPatchCollector) Register(namespace, name, apiVersion, kind string, variants map[string]map[string]any) error
- func (c *StatusPatchCollector) RegisterWithLineage(namespace, name, apiVersion, kind, uid, resourceVersion string, ...) error
- func (c *StatusPatchCollector) ReplayProjectionPlan(replay *StatusPatchProjectionPlanReplay) error
- func (c *StatusPatchCollector) ReplayProjections(replays []*StatusPatchProjectionReplay) error
- func (c *StatusPatchCollector) SetSource(namespace, name, apiVersion, kind, sourceTemplate string, sourceLine int)
- func (c *StatusPatchCollector) Snapshot(previous ...*StatusPatchSnapshot) (*StatusPatchSnapshot, error)
- type StatusPatchProjection
- type StatusPatchProjectionClaim
- type StatusPatchProjectionPlan
- func (p *StatusPatchProjectionPlan) PrepareReplay() (*StatusPatchProjectionPlanReplay, error)
- func (p *StatusPatchProjectionPlan) ReplaceEntry(group, entry string, statusProjection *StatusPatchProjection) (*StatusPatchProjectionPlan, error)
- func (p *StatusPatchProjectionPlan) ReplaceGroup(group string, statusProjection *StatusPatchProjection) (*StatusPatchProjectionPlan, error)
- func (p *StatusPatchProjectionPlan) ValidateAuthentication() error
- type StatusPatchProjectionPlanEntry
- type StatusPatchProjectionPlanReplay
- type StatusPatchProjectionReplay
- type StatusPatchSnapshot
- func (s *StatusPatchSnapshot) ChangedPatchesForPhase(previous *StatusPatchSnapshot, phase string) ([]StatusPatch, error)
- func (s *StatusPatchSnapshot) ExactEqual(other *StatusPatchSnapshot) (bool, error)
- func (s *StatusPatchSnapshot) Len() (int, error)
- func (s *StatusPatchSnapshot) Patches() ([]StatusPatch, error)
- func (s *StatusPatchSnapshot) PatchesForPhase(phase string) ([]StatusPatch, error)
- func (s *StatusPatchSnapshot) PatchesForPhaseTargets(phase string, targets []StatusPatchTarget) ([]StatusPatch, error)
- func (s *StatusPatchSnapshot) SameRoot(other *StatusPatchSnapshot) (bool, error)
- func (s *StatusPatchSnapshot) ValidateAuthentication() error
- type StatusPatchTarget
- type TemplateNotFoundError
- type TemplatePostProcessor
- type TextFragment
- type WorkerGate
Constants ¶
const ( // FilterSortBy sorts items by JSONPath criteria. FilterSortBy = "sort_by" // FilterGlobMatch filters items by glob pattern. FilterGlobMatch = "glob_match" // FilterStrip removes leading/trailing whitespace. FilterStrip = "strip" // FilterB64Decode decodes base64-encoded strings. FilterB64Decode = "b64decode" // FilterB64Encode encodes strings as standard base64. FilterB64Encode = "b64encode" // FilterDebug outputs debug information for items. FilterDebug = "debug" // FilterIndent indents each line of a string by a specified amount. FilterIndent = "indent" )
Filter name constants for template engines.
const ( // FuncFail stops template execution with an error message. FuncFail = "fail" // FuncMerge merges two maps, returning a new map. // Values from the second map override values from the first. FuncMerge = "merge" // FuncKeys returns sorted keys from a map. FuncKeys = "keys" // FuncSortStrings sorts a []any slice as strings. // Useful when append() returns []any but you need sorted strings. FuncSortStrings = "sort_strings" // FuncSortInts sorts a []any slice of integer values numerically. // Useful for sorting port numbers, IDs, or any other integer keys // where lexicographic sort_strings ordering would be wrong // (e.g. "10" before "2"). Non-integer entries are coerced via // toint() and sort to the front (toint of a non-numeric value // returns 0). FuncSortInts = "sort_ints" // FuncStringsContains checks if a string contains a substring. FuncStringsContains = "strings_contains" // FuncStringsSplit splits a string by a separator. FuncStringsSplit = "strings_split" // FuncStringsTrim trims whitespace from a string. FuncStringsTrim = "strings_trim" // FuncStringsLower converts a string to lowercase. FuncStringsLower = "strings_lower" // FuncStringsSplitN splits a string by a separator with a maximum number of parts. FuncStringsSplitN = "strings_splitn" // FuncToString converts a value to string. FuncToString = "tostring" // FuncToInt converts a value to int. FuncToInt = "toint" // FuncToFloat converts a value to float64. FuncToFloat = "tofloat" // FuncCeil returns the ceiling of a float. FuncCeil = "ceil" // FuncSeq generates a sequence of integers from 0 to n-1. // Syntax: seq(n) returns []int{0, 1, 2, ..., n-1}. FuncSeq = "seq" // FuncRegexSearch checks if a string matches a regex pattern. FuncRegexSearch = "regex_search" // FuncIsDigit checks if a string contains only digits. FuncIsDigit = "isdigit" // FuncSanitizeRegex escapes regex special characters. FuncSanitizeRegex = "sanitize_regex" // FuncTitle converts a string to title case. FuncTitle = "title" // FuncOnOwnLines starts each snippet a render_glob matches on a new line. // distributeOnOwnLines rewrites it into the two declared functions below. FuncOnOwnLines = "on_own_lines" // FuncIsNil checks if a value is nil, including typed nil pointers. // In Go, a typed nil pointer stored in an any is not equal to nil. // This function uses reflection to properly check for nil pointers. // Syntax: isNil(value) returns bool. FuncIsNil = "isNil" // FuncDig navigates nested maps/structures using a sequence of keys. // Returns nil if any key along the path is missing. // Ruby-style dig: obj | dig("metadata", "namespace") | fallback("") // Available in: Scriggo only. FuncDig = "dig" // FuncDigString fuses the very common dig + fallback + tostring chain // used at the chart's polymorphic-value boundaries (annotation lookups, // metadata extraction from any-typed values, etc.) into one filter. // Syntax: obj | dig_string(defaultStr, keys...) returns string. // Equivalent to: obj | dig(keys...) | fallback(defaultStr) | tostring(). // Available in: Scriggo only. FuncDigString = "dig_string" // FuncToStringSlice converts []any to []string. // Available in: Scriggo only. FuncToStringSlice = "toStringSlice" // FuncCidrPartition splits a CIDR set into the disjoint blocks each prefix is a union of. FuncCidrPartition = "cidr_partition" // FuncJoin joins a string slice with a separator. // Available in: Scriggo only. FuncJoin = "join" // FuncReplace replaces all occurrences of old with new. FuncReplace = "replace" // FuncCoalesce returns the first non-nil value, or the default if nil. // Workaround for Scriggo's default operator limitation with field access. FuncCoalesce = "coalesce" // FuncFallback returns the first non-nil value, or the fallback if nil. // Jinja2-style alias for coalesce, works well with pipe syntax (e.g., {{ value | fallback("default") }}). FuncFallback = "fallback" // FuncNamespace creates a mutable map for storing state in loops. FuncNamespace = "namespace" // FuncToSlice converts any value to []any for safe ranging. // Returns empty slice if input is nil, otherwise converts to []any. // Syntax: toSlice(value) - returns []any. FuncToSlice = "toSlice" // FuncToStrMap normalises any string-keyed map (map[string]string // from typegen-produced fields like metadata.labels / matchLabels, // or map[string]any from the untyped store path) into a uniform // map[string]string for template iteration. Returns nil for nil // input. Non-string values from a map[string]any input are // coerced via tostring(). // // Motivation: chart code that did `value.(map[string]any)` on a // label / matchLabels field panicked once the typed-watched- // resources path landed, because typegen builds those fields as // `map[string]string` (matching the K8s OpenAPI schema). A // shape-agnostic conversion at the call site keeps chart code // from having to branch per shape. // // Syntax: to_str_map(value) - returns map[string]string. FuncToStrMap = "to_str_map" // FuncFirstSeen checks if a composite key is being seen for the first time. // Returns true on first occurrence, false on subsequent calls with same key. // Thread-safe for parallel template rendering. // Syntax: first_seen("prefix", key1, key2, ...) returns bool. FuncFirstSeen = "first_seen" // FuncSelectAttr filters items by attribute existence or value. // Jinja2-compatible filter for selecting items from a sequence. // Syntax: // selectattr(items, "attr") - items where attr is defined/truthy // selectattr(items, "attr", "eq", v) - items where attr equals v // selectattr(items, "attr", "ne", v) - items where attr not equals v // selectattr(items, "attr", "in", list) - items where attr is in list FuncSelectAttr = "selectattr" // FuncJoinKey joins multiple values into a composite key string with a separator. // Automatically converts all values to strings. // Syntax: join_key("_", val1, val2, ...) returns string. FuncJoinKey = "join_key" // FuncShardSlice divides a slice into N shards and returns the portion for a given shard index. // Used for parallel template rendering where work is split across goroutines. // Syntax: shard_slice(items, shardIndex, totalShards) returns []any. FuncShardSlice = "shard_slice" // FuncBasename extracts the filename from a path (like Unix basename command). // Useful for extracting sanitized filenames from paths returned by fileRegistry.Register(). // Syntax: basename(path) returns string. FuncBasename = "basename" // FuncStatusPatch registers a status patch for a Kubernetes resource during rendering. // Syntax: statusPatch(resource, variants). FuncStatusPatch = "statusPatch" // FuncRecordEvent registers a Kubernetes Warning Event to emit against a // resource during rendering (resource-agnostic — namespace/name/apiVersion/ // kind are read off the passed resource object via dig, so it works for any // watched resource or CRD). // Syntax: recordEvent(resource, reason, message). FuncRecordEvent = "recordEvent" // FuncCondition builds a metav1.Condition-compatible map. // Syntax: condition(type, status, reason, message, observedGeneration, lastTransitionTime). FuncCondition = "condition" // FuncTransitionTime determines the correct lastTransitionTime for a // metav1.Condition-shaped entry. Given the *existing* list of conditions // for the target field (e.g. .status.conditions, or // .status.listeners[i].conditions, or .status.parents[i].conditions — // the helper is resource-agnostic, the caller navigates to the list), // the existing lastTransitionTime is preserved if a condition with the // same type AND status is already present; otherwise the current time // is returned. Pass nil when no prior conditions exist (e.g. the // resource was just created) — the helper will treat every condition // as new. // // Syntax: transitionTime(existingConditions, conditionType, newStatus). FuncTransitionTime = "transitionTime" // FuncCycleTimeBucket returns the current UTC time bucket in a caller-supplied layout. FuncCycleTimeBucket = "cycleTimeBucket" // FuncCycleRandomBytes returns random bytes owned by the current render attempt. FuncCycleRandomBytes = "cycleRandomBytes" // FilterToJSON serializes any value to a JSON string. // Syntax: toJSON(value) or value | toJSON(). FilterToJSON = "toJSON" // FuncSemverGte checks if a semver version is >= a minimum version. // Compares major.minor (patch ignored). Returns false for unparseable versions. // Syntax: semver_gte(version, minVersion) returns bool. FuncSemverGte = "semver_gte" // FuncMakeGUID builds a HAProxy GUID from parts joined by ":". // Auto-truncates with a hash suffix if the result exceeds 127 characters. // Syntax: make_guid(parts...) returns string. FuncMakeGUID = "make_guid" // FuncResource returns the per-render items of a watched resource named // dynamically, sharing the same objects as resources.<name>.List(), so a // jsonpathSet write is observed downstream. Syntax: resource(name) []any. FuncResource = "resource" // FuncJSONPathGet reads a concrete JSONPath out of a resource item. // Syntax: jsonpathGet(item, path) any. FuncJSONPathGet = "jsonpathGet" // FuncJSONPathSet writes a concrete JSONPath into a resource item in place. // Syntax: jsonpathSet(item, path, value) bool. FuncJSONPathSet = "jsonpathSet" // FuncDeriveResource publishes an immutable transformed resource value. // Syntax: deriveResource(resource, item, path, value) any. FuncDeriveResource = "deriveResource" // FuncIncrementalRender renders a keyed component snippet. FuncIncrementalRender = "incremental_render" // FuncIncrementalValues returns winning immutable values for a component group cell. FuncIncrementalValues = "incremental_values" // FuncIncrementalRankedFragments joins ranked string publications in rank order. FuncIncrementalRankedFragments = "incremental_ranked_fragments" // FuncIncrementalRankedFragmentsJoin joins ranked string publications with a delimiter. FuncIncrementalRankedFragmentsJoin = "incremental_ranked_fragments_join" // FuncIncrementalRankedTextFragment retains ranked publications in direct output. FuncIncrementalRankedTextFragment = "incremental_ranked_text_fragment" // FuncIncrementalRankedTextFragmentJoin retains delimiter-joined publications in direct output. FuncIncrementalRankedTextFragmentJoin = "incremental_ranked_text_fragment_join" // FuncIncrementalRankedFragmentBytes reports a ranked cell's joined length // without materialising it, so a template can test emptiness cheaply. FuncIncrementalRankedFragmentBytes = "incremental_ranked_fragment_bytes" // FuncIncrementalValueCount reports how many winning values a cell holds // without decoding them, so a presence test costs nothing per value. FuncIncrementalValueCount = "incremental_value_count" // Collection pipeline helpers (ADR-0018). Each preserves its input's // element type, so a chain over a typed watched resource keeps typed // field access at every stage. Predicates are closures rather than // JSONPath strings so field names are checked at engine compile time. // // FuncMap applies a function to every element, preserving length. // Syntax: items | map(func(e T) U { ... }) returns []U. // The name is available because the fork's parser resolves `map` as an // identifier when it is not followed by `[`. FuncMap = "map" // FuncFilter keeps the elements a predicate accepts. // Syntax: items | filter(func(e T) bool { ... }) returns []T. FuncFilter = "filter" // FuncReject drops the elements a predicate accepts, so a call site // reads as a positive statement instead of a negated one. // Syntax: items | reject(func(e T) bool { ... }) returns []T. FuncReject = "reject" // FuncFlatMap maps each element to a slice and concatenates the // results, flattening exactly one level (not recursively). // Syntax: items | flat_map(func(e T) []U { ... }) returns []U. FuncFlatMap = "flat_map" // FuncUnique keeps the first occurrence of each distinct element, // preserving input order. // Syntax: items | unique() returns []T. FuncUnique = "unique" // FuncUniqueBy keeps the first element per key, preserving input order. // Replaces the hand-rolled map[string]bool{} dedup sets. // Syntax: items | unique_by(func(e T) K { ... }) returns []T. FuncUniqueBy = "unique_by" // FuncGroupBy buckets elements by a string key, preserving input order // within each bucket. Iterate the result via keys() — Go map order is // not stable, and a reordered render reads as a change to the // controller. // Syntax: items | group_by(func(e T) string { ... }) returns map[string][]T. FuncGroupBy = "group_by" // FuncUntarGz expands a gzip-compressed tar archive into entry path → // entry content. Syntax: untar_gz(archive) (map[string]string, error). // Reports failure through the error return rather than panicking, so a // bad archive costs the caller a fallback and not the whole render. FuncUntarGz = "untar_gz" )
Function name constants for template engines.
const ( EventTypeWarning = "Warning" EventTypeNormal = "Normal" )
EventTypeWarning / EventTypeNormal mirror corev1.EventType values without importing k8s.io/api into the pure templating package.
const EngineNameScriggo = "scriggo"
EngineNameScriggo is the canonical name of the (only) supported template engine. Used to validate the configured engine string in callers.
const ResourceDeriverContextName = "resourceDeriver"
ResourceDeriverContextName is the render-context key for ResourceDeriver.
Variables ¶
var ErrHTTPFetchDelayOption = errors.New(
`option "delay" was removed, so this call fails. Rename it to "interval"`)
ErrHTTPFetchDelayOption rejects the pre-v0.3.0 spelling of the "interval" option.
var RenderContextContextKey = renderContextKey{}
RenderContextContextKey is exported for use in engine_scriggo.go.
Functions ¶
func BindAllIncrementalResources ¶
func BindAllIncrementalResources( resources any, lease IncrementalResourceInvocationLease, ) (any, error)
BindAllIncrementalResources binds every resource callable to one component lease.
func BindImmutableResourceInputs ¶
BindImmutableResourceInputs makes a prepared guard available to template execution.
func BindIncrementalImmutableInputs ¶
BindIncrementalImmutableInputs authenticates a prepared component's immutable guard.
func CanonicalIncrementalHTTPArgs ¶
CanonicalIncrementalHTTPArgs validates and detaches arguments before a tracked HTTP fetch.
func CanonicalIncrementalResourceKey ¶
CanonicalIncrementalResourceKey validates one indexed resource lookup key.
func CanonicalIncrementalResourceKeys ¶
CanonicalIncrementalResourceKeys validates resource lookup keys without native coercion methods.
func CanonicalIncrementalResourceValue ¶
CanonicalIncrementalResourceValue validates one indexed resource lookup key held in a reflection value.
func ConsumeIncrementalDetachedValue ¶
func ConsumeIncrementalDetachedValue( value *IncrementalDetachedValue, ) (any, error)
ConsumeIncrementalDetachedValue transfers ownership exactly once.
func DeriveResourceJSONPath ¶
DeriveResourceJSONPath returns a detached resource value with one concrete path changed.
func ExactCycleReplayExecutionActive ¶
ExactCycleReplayExecutionActive reports whether root scheduling must be deterministic.
func FormatCompilationError ¶
func IncrementalResourceStoreType ¶
IncrementalResourceStoreType adds the execution environment used to bind resource reads to one component lease while preserving template call syntax.
func IncrementalScope ¶
IncrementalScope returns the root template attached to ctx.
func MergeStatusLists ¶
MergeStatusLists replaces selected entries while retaining other writers' current entries.
func RegisterExactCyclePreviousOutputDeclaration ¶
func RegisterExactCyclePreviousOutputDeclaration(declaration any)
RegisterExactCyclePreviousOutputDeclaration marks one controller-owned previous-output type (currentConfig) as replay-safe. The engine must not name the controller's packages, so the owner registers the type instead.
func RegisterIncrementalImmutableCertificate ¶
func RegisterIncrementalImmutableCertificate( ctx context.Context, certificate *IncrementalImmutableCertificate, ) error
RegisterIncrementalImmutableCertificate attaches a reusable guard to one render context.
func RegisterIncrementalImmutableInputs ¶
RegisterIncrementalImmutableInputs guards values returned after component entry.
func RegisterIncrementalResourceDeclaration ¶
func RegisterIncrementalResourceDeclaration(declaration any)
RegisterIncrementalResourceDeclaration marks one controller-built resources type for lease-bound batch execution.
func RegisterIncrementalResourceFunctionBindings ¶
func RegisterIncrementalResourceFunctionBindings( owner *IncrementalResourceFunctionBindingOwner, resources any, bindings ...IncrementalResourceFunctionBinding, ) error
RegisterIncrementalResourceFunctionBindings associates exact native callables with one owned resources facade.
func RegisterIncrementalResourceFunctionTrampolines ¶
func RegisterIncrementalResourceFunctionTrampolines( owner *IncrementalResourceFunctionBindingOwner, resources any, trampolines ...*native.FunctionTrampoline, ) error
RegisterIncrementalResourceFunctionTrampolines associates exact native function implementations with one owned resources facade.
func RenderErrorMessage ¶ added in v0.7.0
RenderErrorMessage returns the message a template passed to fail(), or err's full text when the render failed for another reason.
func WithBoundImmutableResourceInputs ¶
func WithBoundImmutableResourceInputs( ctx context.Context, templateContext map[string]any, ) (context.Context, error)
WithBoundImmutableResourceInputs attaches a render context's prepared guard.
func WithCycleTime ¶
WithCycleTime gives cycleTimeBucket one immutable time input across renders.
func WithExactCycleRootInvocation ¶
func WithExactCycleRootInvocation( ctx context.Context, invocation ExactCycleRootInvocation, ) context.Context
WithExactCycleRootInvocation binds the artifact occurrence rendered by one root call.
func WithImmutableResourceInputs ¶
WithImmutableResourceInputs guards resource values returned during one render.
func WithIncrementalEventRecorder ¶
func WithIncrementalEventRecorder(ctx context.Context, recorder IncrementalEventRecorder) context.Context
WithIncrementalEventRecorder enables recordEvent for one component query.
func WithIncrementalExecutionLease ¶
func WithIncrementalExecutionLease( ctx context.Context, lease IncrementalExecutionLease, ) context.Context
WithIncrementalExecutionLease binds native capability work to one component.
func WithIncrementalImmutableCapabilityInputs ¶
WithIncrementalImmutableCapabilityInputs guards a reflected capability surface without traversing function closures or adapter internals. Values returned through the capability must be registered separately.
func WithIncrementalImmutableCertificates ¶
func WithIncrementalImmutableCertificates( ctx context.Context, certificates ...*IncrementalImmutableCertificate, ) context.Context
WithIncrementalImmutableCertificates attaches reusable guards without walking their values again.
func WithIncrementalImmutableInputs ¶
WithIncrementalImmutableInputs guards graph values from template mutation.
func WithIncrementalRenderer ¶
func WithIncrementalRenderer(ctx context.Context, renderer IncrementalRenderer) context.Context
WithIncrementalRenderer attaches one render transaction to Scriggo execution.
func WithIncrementalResourceDeriver ¶
func WithIncrementalResourceDeriver(ctx context.Context, deriver IncrementalResourceDeriver) context.Context
WithIncrementalResourceDeriver enables deriveResource for one component query.
func WithIncrementalScope ¶
WithIncrementalScope identifies the root template that owns component calls.
func WithIncrementalStatusPatchRecorder ¶
func WithIncrementalStatusPatchRecorder( ctx context.Context, recorder IncrementalStatusPatchRecorder, ) context.Context
WithIncrementalStatusPatchRecorder enables statusPatch for one component query.
func WithIncrementalTransitionTime ¶
WithIncrementalTransitionTime provides one immutable timestamp to a status-patch component execution.
func WithWorkerGate ¶
func WithWorkerGate(ctx context.Context, gate WorkerGate) context.Context
WithWorkerGate makes parallel batches rendered under ctx admit their extra workers through gate.
Types ¶
type CompilationError ¶
type CompilationError struct {
// TemplateName is the name of the template that failed to compile
TemplateName string
// TemplateSnippet contains the first 200 characters of the template
TemplateSnippet string
// Cause is the underlying compilation error from the template engine
Cause error
}
CompilationError represents a template compilation failure. This error occurs during template initialization when the template syntax is invalid or contains unsupported constructs.
func NewCompilationError ¶
func NewCompilationError(templateName, templateContent string, cause error) *CompilationError
NewCompilationError creates a CompilationError for a template compilation failure.
func (*CompilationError) Error ¶
func (e *CompilationError) Error() string
Error implements the error interface.
func (*CompilationError) Unwrap ¶
func (e *CompilationError) Unwrap() error
Unwrap returns the underlying cause for error unwrapping.
type ConcreteJSONPath ¶
type ConcreteJSONPath struct {
// contains filtered or unexported fields
}
ConcreteJSONPath is a parsed path that can test object-field presence.
func CompileConcreteJSONPath ¶
func CompileConcreteJSONPath(path string) (ConcreteJSONPath, error)
CompileConcreteJSONPath validates and parses one concrete JSONPath.
func (ConcreteJSONPath) Equal ¶
func (p ConcreteJSONPath) Equal(other ConcreteJSONPath) bool
Equal reports whether both paths have the same compiled representation.
type Engine ¶
type Engine interface {
// Render executes a template with the given context and returns the output.
// The ctx parameter is used for cancellation and timeout control.
// Returns RenderError if template execution fails, RenderTimeoutError if
// the context deadline is exceeded, or TemplateNotFoundError if the
// template doesn't exist.
Render(ctx context.Context, templateName string, templateContext map[string]any) (string, error)
// RenderWithProfiling renders a template and returns profiling statistics
// for included templates. Useful for performance debugging.
//
// Enable profiling via Options.Profiling at construction time.
// Returns nil stats when profiling is disabled.
//
// Stats are aggregated by template name — multiple renders of the same
// template are combined into a single IncludeStats entry with count > 1.
RenderWithProfiling(ctx context.Context, templateName string, templateContext map[string]any) (string, []IncludeStats, error)
// PostProcess applies a template's configured post-processor chain to
// text that did not come from that render pass, so a caller assembling
// output from several pieces can normalise each piece the same way.
PostProcess(ctx context.Context, templateName string, text string) (string, error)
BeginPostProcessTransaction(context.Context) (context.Context, PostProcessTransaction)
// TemplateNames returns the names of all available templates, sorted alphabetically.
TemplateNames() []string
// HasTemplate checks if a template with the given name exists.
HasTemplate(templateName string) bool
// GetRawTemplate returns the original template string for the given name.
// Returns TemplateNotFoundError if the template doesn't exist.
GetRawTemplate(templateName string) (string, error)
// TemplateCount returns the number of templates in the engine.
TemplateCount() int
// EnableTracing enables template execution tracing for debugging.
EnableTracing()
// DisableTracing disables template execution tracing.
DisableTracing()
// IsTracingEnabled returns whether tracing is currently enabled.
IsTracingEnabled() bool
// GetTraceOutput returns accumulated trace output and clears the buffer.
GetTraceOutput() string
// AppendTraces appends traces from another engine to this engine's trace buffer.
// This is useful for aggregating traces from multiple worker engines.
AppendTraces(other Engine)
// EnableFilterDebug enables detailed filter operation logging.
EnableFilterDebug()
// DisableFilterDebug disables detailed filter operation logging.
DisableFilterDebug()
// IsFilterDebugEnabled returns whether filter debug logging is enabled.
IsFilterDebugEnabled() bool
// ClearVMPool releases pooled VMs to allow garbage collection.
// Call after rendering completes to reduce memory from parallel rendering spikes.
// No-op for engines that don't use VM pooling.
ClearVMPool()
}
Engine is the contract every template engine implementation satisfies. The methods are grouped visually by concern — rendering, introspection, tracing, filter debug, and resource management — but they all live on a single interface because no current caller needs a narrower view and every implementation ends up providing the full surface anyway.
type EventCollector ¶
type EventCollector struct {
// contains filtered or unexported fields
}
EventCollector collects Events registered by templates during rendering. It is thread-safe for concurrent writes from parallel template goroutines and created per render cycle (same lifecycle as StatusPatchCollector).
func NewEventCollector ¶
func NewEventCollector() *EventCollector
NewEventCollector creates a new thread-safe collector.
func (*EventCollector) Events ¶
func (c *EventCollector) Events() []RenderedEvent
Events returns all collected events as a snapshot, sorted by key so the output is deterministic regardless of the (parallel, nondeterministic) registration order. Further Register calls do not affect the returned slice.
func (*EventCollector) ExactCycleProtocolState ¶
func (c *EventCollector) ExactCycleProtocolState() (ExactCycleProtocolState, error)
ExactCycleProtocolState proves that this collector starts empty and mutable.
func (*EventCollector) Register ¶
func (c *EventCollector) Register(namespace, name, apiVersion, kind, eventType, reason, message string) error
Register records an Event to emit. Duplicate (resource, type, reason, message) tuples collapse to one. name/apiVersion/kind/type/reason/message are required; namespace is optional (cluster-scoped resources).
func (*EventCollector) Snapshot ¶
func (c *EventCollector) Snapshot(previous ...*RenderedEventSnapshot) (*RenderedEventSnapshot, error)
Snapshot freezes the collector and reuses previous when every event is exact.
type ExactCycleProtocolState ¶
type ExactCycleProtocolState interface {
ValidateExactCycleProtocolState() error
SameExactCycleProtocolState(ExactCycleProtocolState) (bool, error)
}
ExactCycleProtocolState is an authenticated immutable root for hidden attempt-local state consumed through an engine protocol global.
type ExactCycleProtocolStateProvider ¶
type ExactCycleProtocolStateProvider interface {
ExactCycleProtocolState() (ExactCycleProtocolState, error)
}
ExactCycleProtocolStateProvider exposes the initial semantic root of one attempt-local protocol object.
type ExactCycleReplayInputs ¶
type ExactCycleReplayInputs struct {
// contains filtered or unexported fields
}
ExactCycleReplayInputs is an isolated snapshot of only compiled-used ambient globals.
func (*ExactCycleReplayInputs) Finalize ¶
func (s *ExactCycleReplayInputs) Finalize() error
Finalize seals every effect after all root entry points have returned.
func (*ExactCycleReplayInputs) Generation ¶
func (s *ExactCycleReplayInputs) Generation() (uint64, error)
Generation returns the attempt generation authenticated by this input snapshot.
type ExactCycleReplayProgram ¶
type ExactCycleReplayProgram struct {
// contains filtered or unexported fields
}
ExactCycleReplayProgram certifies the statically used root-template surface.
func (*ExactCycleReplayProgram) Begin ¶
func (p *ExactCycleReplayProgram) Begin( ctx context.Context, generation uint64, templateContext map[string]any, ) (context.Context, *ExactCycleReplayInputs, error)
Begin starts an attempt-owned observation stream for one candidate generation.
func (*ExactCycleReplayProgram) BeginWithInvocations ¶
func (p *ExactCycleReplayProgram) BeginWithInvocations( ctx context.Context, generation uint64, templateContext map[string]any, invocations []ExactCycleRootInvocation, ) (context.Context, *ExactCycleReplayInputs, error)
BeginWithInvocations starts a candidate against the exact ordered artifact plan.
func (*ExactCycleReplayProgram) Capture ¶
func (p *ExactCycleReplayProgram) Capture( templateContext map[string]any, ) (*ExactCycleReplayInputs, error)
Capture is unavailable because publication requires an owned execution attempt.
func (*ExactCycleReplayProgram) ExecutionContext ¶
ExecutionContext binds the program's deterministic and immutable root semantics.
func (*ExactCycleReplayProgram) Matches ¶
func (p *ExactCycleReplayProgram) Matches( previous *ExactCycleReplayInputs, templateContext map[string]any, ) (bool, error)
Matches reports whether every compiled-used ambient input and temporal lease is unchanged.
func (*ExactCycleReplayProgram) OutputOnlyRoot ¶
func (p *ExactCycleReplayProgram) OutputOnlyRoot(name string) (bool, error)
OutputOnlyRoot reports whether the named root produces nothing but its text: it uses no protocol global, records no effect and is not post-processed, so its previous output can stand in for a render whose ambient inputs and observed incremental values are unchanged.
func (*ExactCycleReplayProgram) RequiresUnchangedInputRoots ¶
func (p *ExactCycleReplayProgram) RequiresUnchangedInputRoots() (bool, error)
RequiresUnchangedInputRoots reports whether legacy shared state hides dependencies behind root execution order and therefore requires every input root to stay fixed.
func (*ExactCycleReplayProgram) UsesPreviousOutput ¶
func (p *ExactCycleReplayProgram) UsesPreviousOutput(name string) (bool, error)
UsesPreviousOutput reports whether a compiled root reads the named prior output.
type ExactCycleRootInvocation ¶
ExactCycleRootInvocation identifies one rendered artifact occurrence.
type ExistenceJSONPath ¶
type ExistenceJSONPath struct {
// contains filtered or unexported fields
}
ExistenceJSONPath is a parsed path that may select any array element.
func CompileExistenceJSONPath ¶
func CompileExistenceJSONPath(path string) (ExistenceJSONPath, error)
CompileExistenceJSONPath validates a path used by a presence predicate.
func (ExistenceJSONPath) Equal ¶
func (p ExistenceJSONPath) Equal(other ExistenceJSONPath) bool
Equal reports whether both paths have the same compiled representation.
type FailError ¶ added in v0.7.0
type FailError struct {
Message string
}
FailError is the error fail() stops a render with. Message is the template's text for the operator.
type FileRegistrar ¶
FileRegistrar is an interface for dynamic file registration during template rendering. This interface is implemented by rendercontext.FileRegistry, allowing templates to register auxiliary files (certificates, maps, etc.) without creating import cycles.
The Register method signature matches the variadic calling convention used in templates:
file_registry.Register("cert", "filename.pem", "content...")
Arguments:
- args[0]: file type (string) - "cert", "map", "file", or "crt-list"
- args[1]: filename (string) - base filename
- args[2]: content (string) - file content
Returns:
- Predicted absolute path where the file will be located
- Error if validation fails or content conflict detected
type FilterFunc ¶
FilterFunc is a template filter function signature. Template filters transform values within template expressions:
{{ value | filter_name(arg1, arg2) }}
FilterFunc receives:
- in: The value being filtered (left side of | operator)
- args: Additional filter arguments from the template
Example:
func upperFilter(in any, args ...any) (any, error) {
str, ok := in.(string)
if !ok {
return nil, errors.New("upper filter requires string input")
}
return strings.ToUpper(str), nil
}
type GlobalFunc ¶
GlobalFunc is a template global function signature. Global functions are called directly in templates:
{{ function_name(arg1, arg2) }}
GlobalFunc receives variadic arguments from the template call.
Example:
func mergeFunc(args ...any) (any, error) {
if len(args) != 2 {
return nil, errors.New("merge requires exactly 2 arguments")
}
// ... merge logic
}
type GlobalUsageIntrospector ¶
GlobalUsageIntrospector reports usage across every compiled entry point. A negative result is actionable only when known is true.
type HTTPFetcher ¶
type HTTPFetcher interface {
// Fetch fetches content from a URL with optional options and authentication.
// Arguments:
// - args[0]: URL (string, required)
// - args[1]: options (map, optional) - {"interval": "60s", "timeout": "30s", "retries": 3, "critical": true}
// - args[2]: auth (map, optional) - {"type": "bearer"|"basic", "token": "...", ...}
Fetch(args ...any) (any, error)
// Pending reports whether this render left the URL out because its new
// content waits for a render that can accept it: Fetch returned empty
// content without fetching, and a later render serves the content.
Pending(url string) bool
}
HTTPFetcher defines the interface for HTTP resource fetching accessible from templates. This interface enables the http.Fetch() method in Scriggo templates:
{% var content = http.Fetch("https://example.com/blocklist.txt") %}
{% var content = http.Fetch(url, map[string]any{"interval": "60s", "critical": true}) %}
Implementations are provided by pkg/controller/httpstore.HTTPStoreWrapper.
type IncludeStats ¶
type IncludeStats struct {
// Name is the name of the included/rendered template.
Name string
// Count is the number of times this template was rendered.
// Templates rendered multiple times (e.g., in loops) have count > 1.
Count int
// TotalMs is the cumulative time spent rendering this template in milliseconds.
// For templates rendered multiple times, this is the sum of all renders.
TotalMs float64
// AvgMs is the average time per render in milliseconds (TotalMs / Count).
AvgMs float64
// MaxMs is the maximum time for a single render in milliseconds.
MaxMs float64
}
IncludeStats represents timing statistics for template includes/renders. Used for performance profiling to identify slow templates.
type IncrementalBackendPlanRegistrar ¶
type IncrementalBackendPlanRegistrar interface {
Profile(record map[string]any) (string, error)
Backend(record map[string]any, text string) (string, error)
BackendWhenAny(record map[string]any, text, cell string, keys []string) (string, error)
}
IncrementalBackendPlanRegistrar records deterministic backend declarations.
type IncrementalBindingInputSnapshot ¶
type IncrementalBindingInputSnapshot struct {
// contains filtered or unexported fields
}
IncrementalBindingInputSnapshot is a detached planner-input snapshot owned by one engine.
func (*IncrementalBindingInputSnapshot) Equal ¶
func (s *IncrementalBindingInputSnapshot) Equal(other *IncrementalBindingInputSnapshot) bool
Equal reports exact planner-visible equality, including Go value types.
type IncrementalBindingPlannerExecutor ¶
type IncrementalBindingPlannerExecutor interface {
RenderIncrementalBindings(context.Context, string, map[string]any) ([]byte, error)
}
IncrementalBindingPlannerExecutor evaluates a configured dynamic binding planner.
type IncrementalBindingSnapshotPlanner ¶
type IncrementalBindingSnapshotPlanner interface {
SnapshotIncrementalBindingInputs([]string, map[string]any) (*IncrementalBindingInputSnapshot, error)
MatchIncrementalBindingInputs([]string, map[string]any, *IncrementalBindingInputSnapshot) bool
RenderIncrementalBindingsSnapshot(context.Context, string, *IncrementalBindingInputSnapshot) ([]byte, error)
}
IncrementalBindingSnapshotPlanner executes planners against an authenticated input snapshot.
type IncrementalCertifiedValueReader ¶
type IncrementalCertifiedValueReader interface {
IncrementalValuesCertified(
context.Context,
string,
string,
) (*IncrementalCertifiedValues, error)
}
IncrementalCertifiedValueReader resolves reusable values with their immutable guard.
type IncrementalCertifiedValues ¶
type IncrementalCertifiedValues struct {
// contains filtered or unexported fields
}
IncrementalCertifiedValues carries reusable immutable values to the template runtime.
func NewIncrementalCertifiedValues ¶
func NewIncrementalCertifiedValues( values []any, certificate *IncrementalImmutableCertificate, ) *IncrementalCertifiedValues
NewIncrementalCertifiedValues seals values for the template runtime.
func (*IncrementalCertifiedValues) SameRoot ¶
func (v *IncrementalCertifiedValues) SameRoot(other *IncrementalCertifiedValues) (bool, error)
SameRoot reports whether two certified views reference the same immutable values.
func (*IncrementalCertifiedValues) ValidateAuthentication ¶
func (v *IncrementalCertifiedValues) ValidateAuthentication() error
ValidateAuthentication verifies the immutable value view without walking it.
type IncrementalComponentBatchError ¶
IncrementalComponentBatchError identifies the first failed batch item.
func (*IncrementalComponentBatchError) Error ¶
func (e *IncrementalComponentBatchError) Error() string
func (*IncrementalComponentBatchError) Unwrap ¶
func (e *IncrementalComponentBatchError) Unwrap() error
type IncrementalComponentBatchExecutor ¶
type IncrementalComponentBatchExecutor interface {
RenderIncrementalComponents(
context.Context,
string,
[]IncrementalComponentBatchItem,
) ([]string, error)
}
IncrementalComponentBatchExecutor reuses execution infrastructure without merging component contexts or outputs.
type IncrementalComponentBatchItem ¶
type IncrementalComponentBatchItem struct {
Context context.Context
TemplateContext map[string]any
Activate func() error
Deactivate func()
}
IncrementalComponentBatchItem is one isolated component execution.
type IncrementalComponentContextOptions ¶
type IncrementalComponentContextOptions struct {
ExecutionLease IncrementalExecutionLease
ResourceDeriver IncrementalResourceDeriver
EventRecorder IncrementalEventRecorder
StatusRecorder IncrementalStatusPatchRecorder
TransitionTime string
ContextValueKey any
ContextValue any
}
IncrementalComponentContextOptions supplies one component's native capabilities.
type IncrementalComponentContextTable ¶
type IncrementalComponentContextTable struct {
// contains filtered or unexported fields
}
IncrementalComponentContextTable owns compact contexts for one immutable vector lane.
func NewIncrementalComponentContextTable ¶
func NewIncrementalComponentContextTable(count int) (*IncrementalComponentContextTable, error)
NewIncrementalComponentContextTable allocates one contiguous context table.
func (*IncrementalComponentContextTable) Prepare ¶
func (t *IncrementalComponentContextTable) Prepare( index int, parent context.Context, options IncrementalComponentContextOptions, certificates ...*IncrementalImmutableCertificate, ) (context.Context, error)
Prepare binds construction-only inputs and returns the context for one item.
func (*IncrementalComponentContextTable) Seal ¶
func (t *IncrementalComponentContextTable) Seal( index int, templateContext map[string]any, capabilities ...any, ) error
Seal authenticates the render bindings and publishes one context atomically.
func (*IncrementalComponentContextTable) SealValues ¶
func (t *IncrementalComponentContextTable) SealValues( index int, values IncrementalComponentContextValues, ) error
SealValues authenticates vector bindings without materializing a context map.
type IncrementalComponentContextValues ¶
type IncrementalComponentContextValues struct {
Source string
Item map[string]any
Props map[string]any
RenderSubject map[string]any
RenderMode string
Resources any
Controller map[string]ResourceStore
HTTP HTTPFetcher
PlanRegistry IncrementalBackendPlanRegistrar
}
IncrementalComponentContextValues supplies one component's vector bindings.
type IncrementalComponentExecutor ¶
type IncrementalComponentExecutor interface {
RenderIncrementalComponent(context.Context, string, map[string]any) (string, error)
}
IncrementalComponentExecutor runs a component entry point without post-processing.
type IncrementalComponentSourceTransaction ¶
type IncrementalComponentSourceTransaction struct {
Children []IncrementalComponentSourceTransactionChild
}
IncrementalComponentSourceTransaction groups callable children behind one source load.
type IncrementalComponentSourceTransactionBatch ¶
type IncrementalComponentSourceTransactionBatch struct {
Bindings map[string]any
Contexts []context.Context
ChildContexts []context.Context
}
IncrementalComponentSourceTransactionBatch transfers owned source columns without flattening.
type IncrementalComponentSourceTransactionChild ¶
IncrementalComponentSourceTransactionChild identifies one exact child result.
type IncrementalComponentSourceTransactionLifecycle ¶
type IncrementalComponentSourceTransactionLifecycle interface {
IncrementalComponentVectorLifecycle
LoadSourceTransactionWave(context.Context, int) (IncrementalComponentSourceTransactionBatch, error)
SealWave(int) error
}
IncrementalComponentSourceTransactionLifecycle loads and seals exact source waves.
type IncrementalComponentSourceTransactionWave ¶
type IncrementalComponentSourceTransactionWave struct {
Transactions []IncrementalComponentSourceTransaction
}
IncrementalComponentSourceTransactionWave fixes one wave's source transactions.
type IncrementalComponentSourceTransactionsInput ¶
type IncrementalComponentSourceTransactionsInput struct {
Waves []IncrementalComponentSourceTransactionWave
Lifecycle IncrementalComponentSourceTransactionLifecycle
}
IncrementalComponentSourceTransactionsInput supplies immutable source/child topology.
type IncrementalComponentSourceTransactionsRenderer ¶
type IncrementalComponentSourceTransactionsRenderer interface {
IncrementalComponentSourceTransactionsEligibility() bool
RenderIncrementalComponentSourceTransactions(
context.Context,
IncrementalComponentSourceTransactionsInput,
) error
}
IncrementalComponentSourceTransactionsRenderer executes children under shared source loads.
type IncrementalComponentVectorCarrierEligibility ¶
type IncrementalComponentVectorCarrierEligibility struct {
TemplateNames []string
BindingNames []string
}
IncrementalComponentVectorCarrierEligibility is the carrier's exact static surface.
type IncrementalComponentVectorCarrierLane ¶
type IncrementalComponentVectorCarrierLane struct {
TemplateName string
Count int
Bindings map[string]any
Contexts []context.Context
}
IncrementalComponentVectorCarrierLane supplies one entry point's ordered items.
type IncrementalComponentVectorCarrierWave ¶
type IncrementalComponentVectorCarrierWave struct {
Lanes []IncrementalComponentVectorCarrierWaveLane
// EntryPoints optionally fixes per-child dispatch; nil preserves lane order.
EntryPoints []string
}
IncrementalComponentVectorCarrierWave fixes one publication wave's child order.
type IncrementalComponentVectorCarrierWaveLane ¶
IncrementalComponentVectorCarrierWaveLane fixes one lane's item count before execution.
type IncrementalComponentVectorCarrierWaveLifecycle ¶
type IncrementalComponentVectorCarrierWaveLifecycle interface {
IncrementalComponentVectorLifecycle
LoadWave(context.Context, int) ([]IncrementalComponentVectorCarrierLane, error)
SealWave(int) error
}
IncrementalComponentVectorCarrierWaveLifecycle loads and seals one wave at a time.
type IncrementalComponentVectorCarrierWavesInput ¶
type IncrementalComponentVectorCarrierWavesInput struct {
Waves []IncrementalComponentVectorCarrierWave
Lifecycle IncrementalComponentVectorCarrierWaveLifecycle
}
IncrementalComponentVectorCarrierWavesInput supplies an immutable multi-wave shape.
type IncrementalComponentVectorCarrierWavesRenderer ¶
type IncrementalComponentVectorCarrierWavesRenderer interface {
IncrementalComponentVectorCarrierEligibility() (
IncrementalComponentVectorCarrierEligibility,
bool,
)
RenderIncrementalComponentVectorCarrierWaves(
context.Context,
IncrementalComponentVectorCarrierWavesInput,
) error
}
IncrementalComponentVectorCarrierWavesRenderer executes every wave in one VM.
type IncrementalComponentVectorEligibility ¶
type IncrementalComponentVectorEligibility struct {
BindingNames []string
}
IncrementalComponentVectorEligibility is the exact per-item binding universe.
type IncrementalComponentVectorInput ¶
type IncrementalComponentVectorInput struct {
Count int
Bindings map[string]any
Contexts []context.Context
Lifecycle IncrementalComponentVectorLifecycle
}
IncrementalComponentVectorInput supplies fixed globals and concrete columns.
type IncrementalComponentVectorLifecycle ¶
type IncrementalComponentVectorLifecycle interface {
Begin(index int) error
End(index int, output string) error
Abort(activeIndex int, cause error)
}
IncrementalComponentVectorLifecycle owns one logical lifecycle per vector item.
type IncrementalComponentVectorRenderer ¶
type IncrementalComponentVectorRenderer interface {
IncrementalComponentVectorEligibility(
templateName string,
) (IncrementalComponentVectorEligibility, bool)
RenderIncrementalComponentVector(
context.Context,
string,
IncrementalComponentVectorInput,
) error
}
IncrementalComponentVectorRenderer executes a certified component once over a vector.
type IncrementalDetachedValue ¶
type IncrementalDetachedValue struct {
// contains filtered or unexported fields
}
IncrementalDetachedValue carries an isolated value across the recorder boundary.
func NewIncrementalDetachedValue ¶
func NewIncrementalDetachedValue(value any) (*IncrementalDetachedValue, error)
NewIncrementalDetachedValue creates a single-owner immutable value transfer.
type IncrementalEventRecorder ¶
type IncrementalEventRecorder interface {
RecordEvent(namespace, name, apiVersion, kind, eventType, reason, message string) error
}
IncrementalEventRecorder records one query-local Kubernetes Event effect.
type IncrementalExecutionLease ¶
type IncrementalExecutionLease interface {
BeginIncrementalExecution(context.Context, string) (func(), error)
BeforeIncrementalNativeCall(context.Context) error
}
IncrementalExecutionLease rejects native capability work outside its component execution.
type IncrementalImmutableCertificate ¶
type IncrementalImmutableCertificate struct {
// contains filtered or unexported fields
}
IncrementalImmutableCertificate is a reusable immutable-value guard.
func CertifyIncrementalImmutableInputs ¶
func CertifyIncrementalImmutableInputs(values ...any) *IncrementalImmutableCertificate
CertifyIncrementalImmutableInputs prepares a reusable guard for immutable values.
func (*IncrementalImmutableCertificate) Guards ¶
func (c *IncrementalImmutableCertificate) Guards(value any) bool
Guards reports whether the certificate protects the exact referenced value.
type IncrementalRankedFragmentBytesReader ¶
type IncrementalRankedFragmentBytesReader interface {
IncrementalRankedFragmentBytes(ctx context.Context, group, cell string) (int, error)
}
IncrementalRankedFragmentBytesReader reports a ranked cell's joined length.
type IncrementalRankedFragmentJoinReader ¶
type IncrementalRankedFragmentJoinReader interface {
IncrementalRankedFragmentsJoin(context.Context, string, string, string) (string, error)
}
IncrementalRankedFragmentJoinReader resolves ranked strings with a delimiter.
type IncrementalRankedFragmentReader ¶
type IncrementalRankedFragmentReader interface {
IncrementalRankedFragments(context.Context, string, string) (string, error)
}
IncrementalRankedFragmentReader resolves ranked immutable string publications.
type IncrementalRankedTextFragmentJoinReader ¶
type IncrementalRankedTextFragmentJoinReader interface {
IncrementalRankedTextFragmentJoin(context.Context, string, string, string) (TextFragment, error)
}
IncrementalRankedTextFragmentJoinReader retains ranked strings with a delimiter.
type IncrementalRankedTextFragmentReader ¶
type IncrementalRankedTextFragmentReader interface {
IncrementalRankedTextFragment(context.Context, string, string) (TextFragment, error)
}
IncrementalRankedTextFragmentReader retains ranked immutable string publications.
type IncrementalRenderer ¶
IncrementalRenderer evaluates a configured keyed component group.
type IncrementalResourceBinder ¶
type IncrementalResourceBinder interface {
BindIncrementalResources(string, any, IncrementalResourceInvocationLease) (any, error)
}
IncrementalResourceBinder binds the resource surface used by one component entry point.
type IncrementalResourceBoundFrameFactory ¶
type IncrementalResourceBoundFrameFactory func( IncrementalResourceInvocationLease, ) (*native.FunctionTrampoline, error)
IncrementalResourceBoundFrameFactory binds one native resource frame to an exact execution lease.
type IncrementalResourceDeriver ¶
type IncrementalResourceDeriver interface {
DeriveResource(resource string, item any, path string, value any) (any, error)
}
IncrementalResourceDeriver records one query-local derived resource effect.
type IncrementalResourceFunctionBinding ¶
type IncrementalResourceFunctionBinding struct {
Trampoline *native.FunctionTrampoline
BoundFrameFactory IncrementalResourceBoundFrameFactory
}
IncrementalResourceFunctionBinding associates one exact callable with an optional bound frame factory.
type IncrementalResourceFunctionBindingOwner ¶
type IncrementalResourceFunctionBindingOwner struct {
// contains filtered or unexported fields
}
IncrementalResourceFunctionBindingOwner retains bindings as long as its facade is reachable.
func NewIncrementalResourceFunctionBindingOwner ¶
func NewIncrementalResourceFunctionBindingOwner() *IncrementalResourceFunctionBindingOwner
NewIncrementalResourceFunctionBindingOwner creates a facade binding owner.
type IncrementalResourceInvocationLease ¶
type IncrementalResourceInvocationLease interface {
ValidateIncrementalResourceInvocation(context.Context) error
}
IncrementalResourceInvocationLease authenticates a component-bound resource facade.
type IncrementalSourceTransactionChildSelector ¶
type IncrementalSourceTransactionChildSelector interface {
ActiveIncrementalSourceTransactionChild() (int, error)
}
IncrementalSourceTransactionChildSelector authenticates the active child.
type IncrementalSourceTransactionResourceBinder ¶
type IncrementalSourceTransactionResourceBinder interface {
BindIncrementalSourceTransactionResources(
[]string,
any,
IncrementalResourceInvocationLease,
IncrementalSourceTransactionChildSelector,
) (any, error)
}
IncrementalSourceTransactionResourceBinder binds callables to their exact child owners.
type IncrementalSourceTransactionSelectorAuthenticator ¶
type IncrementalSourceTransactionSelectorAuthenticator interface {
ValidateIncrementalSourceTransactionSelector(IncrementalSourceTransactionChildSelector) error
}
IncrementalSourceTransactionSelectorAuthenticator binds a selector to its execution lease.
type IncrementalStatusPatchRecorder ¶
type IncrementalStatusPatchRecorder interface {
RecordStatusPatch(
namespace, name, apiVersion, kind, uid, resourceVersion string,
variants map[string]map[string]any,
sourceTemplate string,
sourceLine int,
listOwnership ...string,
) error
}
IncrementalStatusPatchRecorder records one raw query-local statusPatch call.
type IncrementalTextFragmentRenderer ¶
type IncrementalTextFragmentRenderer interface {
RenderIncrementalTextFragment(context.Context, string) (TextFragment, error)
}
IncrementalTextFragmentRenderer retains immutable component output until the final text consumer needs its bytes.
type IncrementalValueCounter ¶
type IncrementalValueCounter interface {
IncrementalValueCount(ctx context.Context, group, cell string) (int, error)
}
IncrementalValueCounter answers how many winning values a cell holds.
type IncrementalValueReader ¶
type IncrementalValueReader interface {
IncrementalValues(context.Context, string, string) ([]any, error)
}
IncrementalValueReader resolves immutable keyed publications for a group cell.
type Options ¶
type Options struct {
// EntryPoints lists template names to compile explicitly; the remaining
// templates are snippets, discovered and compiled automatically when
// referenced via render/render_glob statements with inherit_context.
// nil means every template is an entry point.
EntryPoints []string
// IncrementalEntryPoints is the subset of EntryPoints compiled against
// the deterministic incremental declaration set.
IncrementalEntryPoints []string
// IncrementalBindingEntryPoints is the subset compiled as deterministic
// dynamic binding planners.
IncrementalBindingEntryPoints []string
// Filters are custom filters merged over the built-in set (can be nil).
Filters map[string]FilterFunc
// Functions are custom global functions merged over the built-in set
// (can be nil).
Functions map[string]GlobalFunc
// PostProcessors configures per-template post-processing (can be nil).
PostProcessors map[string][]PostProcessorConfig
// Declarations registers domain-specific types with Scriggo (e.g.
// currentConfig for slot-aware server assignment). Use this when
// templates need access to types from other packages (can be nil).
Declarations map[string]any
// Profiling enables Scriggo's built-in profiler, which collects timing
// data for function calls, macros, and includes during execution
// (see RenderWithProfiling). Profiling adds minimal runtime overhead.
Profiling bool
}
Options configures a template engine. The zero value (or a nil *Options) compiles every template as an entry point, with no custom filters, functions, post-processors, type declarations, or profiling.
type PathResolver ¶
type PathResolver struct {
// BaseDir is the absolute base path for HAProxy auxiliary files.
// This is used with "default-path origin" in HAProxy's global section
// to resolve relative paths regardless of where the config file is located.
// Example: "/etc/haproxy"
BaseDir string
// MapsDir is the relative path to the HAProxy maps directory.
// Example: "maps"
MapsDir string
// SSLDir is the relative path to the HAProxy SSL certificates directory.
// Example: "ssl"
SSLDir string
// CRTListDir is the relative path to the HAProxy crt-list files directory.
// Example: "ssl"
CRTListDir string
// GeneralDir is the relative path to the HAProxy general files directory.
// Example: "files"
GeneralDir string
}
PathResolver resolves auxiliary file names to paths based on file type. This is used via the GetPath method in templates to construct paths for HAProxy auxiliary files (maps, SSL certificates, crt-list files, general files).
The paths are relative (maps/, ssl/, files/) and rely on HAProxy's "default-path origin <BaseDir>" directive to resolve to absolute locations. This enables the same rendered config to work for both local validation and deployment onto the pod.
func (*PathResolver) GetBaseDir ¶
func (pr *PathResolver) GetBaseDir() string
GetBaseDir returns the BaseDir field for use in templates. This method exists because Scriggo runtime variables (declared with nil pointers) support method calls but may not support direct field access.
func (*PathResolver) GetPath ¶
func (pr *PathResolver) GetPath(args ...any) (any, error)
GetPath resolves a filename to a full path based on the file type.
This method is called from templates via the pathResolver context variable:
{{ pathResolver.GetPath("host.map", "map") }} → maps/host.map (relative) or /etc/haproxy/maps/host.map (absolute)
{{ pathResolver.GetPath("504.http", "file") }} → files/504.http (relative) or /etc/haproxy/general/504.http (absolute)
{{ pathResolver.GetPath("cert.pem", "cert") }} → ssl/cert.pem (relative) or /etc/haproxy/ssl/cert.pem (absolute)
{{ pathResolver.GetPath("certificate-list.txt", "crt-list") }} → ssl/certificate-list.txt (relative)
{{ pathResolver.GetPath("", "cert") }} → ssl (directory only)
Parameters:
- args[0]: filename (string) - The base filename (without directory path), or empty string for directory only
- args[1]: fileType (string) - File type: "map", "file", "cert", or "crt-list"
Returns:
- Path to the file (relative or absolute depending on PathResolver configuration)
- Error if argument count is wrong, arguments are not strings, file type is invalid, or path construction fails
Note: The pathResolver must be added to the rendering context for templates to access this method. Relative paths work with HAProxy's working directory resolution during validation.
type PlanRegistrar ¶
type PlanRegistrar interface {
// Section registers section text under a kind ("profile" or "backend")
// and a name, and returns its placeholder line. Registering the same
// (kind, name) twice is fine while the text is identical.
Section(kind, name, text string) (string, error)
// Fragment registers text to splice in at the placeholder it returns,
// without the text passing through the template writer. Unlike Section it
// does not partition the config — the fragment lands inside the
// surrounding core section, so the rendered bytes are identical to
// emitting the text inline.
Fragment(name string, fragment TextFragment) (string, error)
// Profile content-addresses a named `defaults` section from the shape
// values a backend shares with every backend of the same shape (mode,
// balance, hash-type, default-server keywords and the profile directive
// lines), registers it, and returns its name (`haptic-be-<hash>`). Two
// backends with the same shape get the same name and one section, which is
// what makes them dynamic-eligible. The name is what Backend() writes after
// `from` and records as the backend's `profile`.
Profile(record map[string]any) (string, error)
// Backend records a backend as data and registers its section text.
// Unknown keys and a missing name are errors — a typo must not silently
// under-describe the emitted section.
Backend(record map[string]any, text string) (string, error)
// ProfileGroup returns the placeholder line where every registered
// profile section is spliced, sorted by name. Emit it exactly once.
ProfileGroup() string
// MapMeta declares whether entry order matters for a map file. Maps are
// ordered unless declared otherwise.
MapMeta(path string, ordered bool) error
}
PlanRegistrar lets templates declare the structure of the configuration they emit: which text is one section, which backend record a section was built from, where the shared profiles go, and how a map file is ordered. It is implemented by rendercontext.PlanRegistry (which also assembles the final config from the returned tokens), keeping the plan types out of this package.
Templates use it through the `planRegistry` global:
{%- var name, err = planRegistry.Profile(record) -%}
{%- var token, err = planRegistry.Section("profile", name, body) -%}
{%- var token, err = planRegistry.Backend(record, text) -%}
{{ planRegistry.ProfileGroup() }}
{%- var err = planRegistry.MapMeta("host.map", false) -%}
Section, Backend and ProfileGroup return a placeholder line that the assembler replaces with the registered text; nothing else may emit one.
type PostProcessBatchError ¶
PostProcessBatchError identifies the first input that failed.
func (*PostProcessBatchError) BatchIndex ¶
func (e *PostProcessBatchError) BatchIndex() int
func (*PostProcessBatchError) Error ¶
func (e *PostProcessBatchError) Error() string
func (*PostProcessBatchError) Unwrap ¶
func (e *PostProcessBatchError) Unwrap() error
type PostProcessBatcher ¶
type PostProcessBatcher interface {
PostProcessBatch(ctx context.Context, templateName string, inputs []string) ([]string, error)
}
PostProcessBatcher returns one post-processed output per input in the same order.
type PostProcessPublication ¶
type PostProcessPublication interface {
Publish()
Abort()
}
type PostProcessReuseProof ¶
type PostProcessReuseProof struct {
// contains filtered or unexported fields
}
PostProcessReuseProof is an opaque identity for one compiler-certified chain.
func (*PostProcessReuseProof) CertifiesIdentity ¶
func (p *PostProcessReuseProof) CertifiesIdentity(engine Engine, templateName string) (bool, error)
CertifiesIdentity reports whether this proof belongs to the exact engine and template and authenticates an empty post-processor chain.
func (*PostProcessReuseProof) ValidateAuthentication ¶
func (p *PostProcessReuseProof) ValidateAuthentication() error
ValidateAuthentication rejects copied, substituted, and stale proofs.
type PostProcessReuseProver ¶
type PostProcessReuseProver interface {
PostProcessReuseProof(templateName string) (*PostProcessReuseProof, error)
}
PostProcessReuseProver returns an exact proof only for deterministic chains.
type PostProcessTransaction ¶
type PostProcessTransaction interface {
Stage(context.Context) (PostProcessPublication, error)
Abort()
}
type PostProcessor ¶
type PostProcessor interface {
// Process applies transformation to the input string.
// Returns the transformed output or an error if processing fails.
Process(input string) (string, error)
}
PostProcessor processes rendered template output before it is returned. Post-processors enable generic transformations like normalization, formatting, or cleanup that apply to the final rendered content.
Post-processors are applied in sequence after template rendering completes. Each processor receives the output of the previous processor (or the initial rendered template for the first processor).
func NewPostProcessor ¶
func NewPostProcessor(config PostProcessorConfig) (PostProcessor, error)
NewPostProcessor creates a post-processor instance from configuration.
Returns an error if:
- The processor type is unknown
- Required parameters are missing
- Parameters are invalid (e.g., invalid regex pattern)
type PostProcessorConfig ¶
type PostProcessorConfig struct {
// Type specifies which post-processor to use.
Type PostProcessorType `yaml:"type" json:"type"`
// Params contains type-specific configuration as key-value pairs.
// For regex_replace:
// - pattern: Regular expression pattern to match (required)
// - replace: Replacement string (required)
Params map[string]string `yaml:"params" json:"params"`
}
PostProcessorConfig defines configuration for a post-processor. The Type field determines which processor implementation to use, and Params contains type-specific configuration.
type PostProcessorType ¶
type PostProcessorType string
PostProcessorType identifies the type of post-processor.
const ( // PostProcessorTypeRegexReplace applies regex-based find/replace. PostProcessorTypeRegexReplace PostProcessorType = "regex_replace" // PostProcessorTypeTemplate applies a Scriggo template transformation. // The template receives the rendered output as the `input` variable (string) // and has access to all standard Scriggo builtins. PostProcessorTypeTemplate PostProcessorType = "template" )
type RawTextRenderer ¶
type RawTextRenderer interface {
RenderRawTo(context.Context, string, map[string]any, io.Writer) ([]IncludeStats, error)
RawTextRenderInstrumented() bool
}
RawTextRenderer streams template output before newline normalization and post-processing.
type RegexReplaceProcessor ¶
type RegexReplaceProcessor struct {
// contains filtered or unexported fields
}
RegexReplaceProcessor applies regex-based find/replace to template output.
The processor operates line-by-line, applying the regex pattern to each line independently. This enables efficient processing of large outputs and supports line-anchored patterns like ^[ ]+ for indentation normalization.
Example usage for indentation normalization:
processor, err := NewRegexReplaceProcessor("^[ ]+", " ")
normalized, err := processor.Process(haproxyConfig)
This replaces any leading spaces with exactly 2 spaces per line.
func NewRegexReplaceProcessor ¶
func NewRegexReplaceProcessor(pattern, replace string) (*RegexReplaceProcessor, error)
NewRegexReplaceProcessor creates a new regex replace processor.
Parameters:
- pattern: Regular expression pattern to match (e.g., "^[ ]+" for leading spaces)
- replace: Replacement string (e.g., " " for 2-space indentation)
Returns an error if the regex pattern is invalid.
type RenderError ¶
type RenderError struct {
// TemplateName is the name of the template that failed to render
TemplateName string
// Cause is the underlying rendering error from the template engine
Cause error
}
RenderError represents a template rendering failure. This error occurs when a valid template fails during execution, typically due to missing context variables or runtime evaluation errors.
func NewRenderError ¶
func NewRenderError(templateName string, cause error) *RenderError
NewRenderError creates a RenderError for a template rendering failure.
func (*RenderError) Error ¶
func (e *RenderError) Error() string
Error implements the error interface.
func (*RenderError) Unwrap ¶
func (e *RenderError) Unwrap() error
Unwrap returns the underlying cause for error unwrapping.
type RenderTimeoutError ¶
type RenderTimeoutError struct {
// TemplateName is the name of the template that timed out
TemplateName string
// Cause is the underlying context error
Cause error
}
RenderTimeoutError represents a template rendering that exceeded the context deadline.
func (*RenderTimeoutError) Error ¶
func (e *RenderTimeoutError) Error() string
Error implements the error interface.
func (*RenderTimeoutError) Unwrap ¶
func (e *RenderTimeoutError) Unwrap() error
Unwrap returns the underlying cause for error unwrapping.
type RenderedEvent ¶
type RenderedEvent struct {
// Namespace of the involved (regarding) resource. Empty for cluster-scoped.
Namespace string
// Name of the involved resource.
Name string
// APIVersion of the involved resource (e.g. "networking.k8s.io/v1").
APIVersion string
// Kind of the involved resource (e.g. "Ingress").
Kind string
// Type is the Event type: "Warning" or "Normal".
Type string
// Reason is a short, machine-readable, PascalCase reason (e.g. "RouteConflict").
Reason string
// Message is the human-readable description.
Message string
}
RenderedEvent is a Kubernetes Event a template asked to emit during rendering, via the recordEvent() function. It is resource-agnostic: the involved object is identified purely by APIVersion/Kind/Namespace/Name supplied by the template, so the controller can emit it against any watched resource or CRD without a typed client (RULE #1).
type RenderedEventSnapshot ¶
type RenderedEventSnapshot struct {
// contains filtered or unexported fields
}
RenderedEventSnapshot is an authenticated immutable event set.
func (*RenderedEventSnapshot) AddedSince ¶
func (s *RenderedEventSnapshot) AddedSince(previous *RenderedEventSnapshot) ([]RenderedEvent, error)
AddedSince returns events absent from the previous authenticated set.
func (*RenderedEventSnapshot) Events ¶
func (s *RenderedEventSnapshot) Events() ([]RenderedEvent, error)
Events returns a detached compatibility view.
func (*RenderedEventSnapshot) ExactEqual ¶
func (s *RenderedEventSnapshot) ExactEqual(other *RenderedEventSnapshot) (bool, error)
ExactEqual compares every event without trusting a digest.
func (*RenderedEventSnapshot) Len ¶
func (s *RenderedEventSnapshot) Len() (int, error)
Len returns the number of events.
func (*RenderedEventSnapshot) SameRoot ¶
func (s *RenderedEventSnapshot) SameRoot(other *RenderedEventSnapshot) (bool, error)
SameRoot reports authenticated storage identity.
func (*RenderedEventSnapshot) ValidateAuthentication ¶
func (s *RenderedEventSnapshot) ValidateAuthentication() error
ValidateAuthentication verifies the exact private ownership chain.
type RenderedResource ¶
type RenderedResource struct {
// APIVersion of the target resource (e.g., "v1", "gateway.networking.k8s.io/v1").
APIVersion string
// Kind of the target resource (e.g., "Service", "Secret", "ConfigMap").
Kind string
// Namespace of the target resource. Empty for cluster-scoped resources;
// the applier passes Namespace("") to the dynamic client which handles
// cluster-scoped types automatically.
Namespace string
// Name of the target resource.
Name string
// Object is the desired resource shape that will be sent verbatim to the
// API server via SSA. It must include `apiVersion`, `kind`, and
// `metadata.name` — the collector validates and injects those at
// Register time, so callers can omit them and pass only the deltas.
Object map[string]any
// CreateOnlyFields are dotted field paths the applier sends when it creates
// this object and omits from every apply after that, leaving them to
// whoever runs it.
CreateOnlyFields []string
}
RenderedResource represents a full Kubernetes resource that templates declare during rendering as "I want this to exist on the cluster, owned by the controller". The applier consumes these and reconciles them via SSA (Server-Side Apply); resources owned by the controller but no longer declared in a render are pruned.
This mirrors the StatusPatch / StatusPatchCollector pattern in status_patch.go but for whole-resource lifecycle instead of status-only updates. The same resource-agnostic principle applies: the controller never names a specific resource kind in code — it just applies whatever the template emits. Templates decide *what* to emit; the controller is the generic vehicle.
Object holds the desired API resource as a map[string]any matching the shape of the corresponding Kubernetes resource (apiVersion / kind / metadata / spec / data / …). The applier marshals the map to JSON and sends it to the API server with PatchType=Apply and a fixed field manager.
type RenderedResourceCollector ¶
type RenderedResourceCollector struct {
// contains filtered or unexported fields
}
RenderedResourceCollector collects desired Kubernetes resources for the applier to reconcile. Filled by the renderer after rendering each entry in `spec.k8sResources`: every YAML document in the rendered output becomes one Register call. Thread-safe so the renderer can populate it from parallel template goroutines if needed (same lifecycle / same shape as StatusPatchCollector).
Created per render cycle. Multiple Register calls for the same key are last-write-wins on Object (the prior Object is replaced wholesale; the applier checksums the final object and skips unchanged SSA patches).
func NewRenderedResourceCollector ¶
func NewRenderedResourceCollector() *RenderedResourceCollector
NewRenderedResourceCollector creates an empty thread-safe collector.
func (*RenderedResourceCollector) Register ¶
func (c *RenderedResourceCollector) Register(apiVersion, kind, namespace, name string, object map[string]any) error
Register declares that a resource should exist on the cluster after this render lands. apiVersion / kind / namespace / name identify the target; `object` is the desired shape (without apiVersion / kind / metadata.name — those are injected so the SSA payload is well-formed regardless of which keys the template author included).
Repeated calls with the same (namespace, name, apiVersion, kind) replace the prior Object — last write wins. This keeps the semantics simple for templates that conditionally re-emit resources during a render. The applier's SHA-256 checksum cache prevents the resulting last-version from triggering a redundant API call when nothing actually changed across renders, so this last-write-wins doesn't risk hammering the API.
func (*RenderedResourceCollector) RegisterWithCreateOnlyFields ¶
func (c *RenderedResourceCollector) RegisterWithCreateOnlyFields( apiVersion, kind, namespace, name string, object map[string]any, createOnlyFields []string, ) error
RegisterWithCreateOnlyFields is Register for a resource whose configuration names fields the applier must send only when it creates the object.
func (*RenderedResourceCollector) Resources ¶
func (c *RenderedResourceCollector) Resources() []RenderedResource
Resources returns a detached, deterministically ordered view. Further Register calls do not affect it.
func (*RenderedResourceCollector) Snapshot ¶
func (c *RenderedResourceCollector) Snapshot( previous ...*RenderedResourceSnapshot, ) (*RenderedResourceSnapshot, error)
Snapshot freezes the collector and reuses previous when every resource is exact.
func (*RenderedResourceCollector) Validate ¶
func (c *RenderedResourceCollector) Validate() error
Validate runs lightweight sanity checks every collected resource must pass before the applier is allowed to send it. Returned errors include the offending key so template authors can locate the bad call site.
The check set is deliberately minimal — the API server will reject malformed payloads itself; we just want to catch obvious template mistakes (missing kind, missing metadata) before they reach the wire.
type RenderedResourceSnapshot ¶
type RenderedResourceSnapshot struct {
// contains filtered or unexported fields
}
RenderedResourceSnapshot is an authenticated immutable desired-resource set.
func (*RenderedResourceSnapshot) ExactEqual ¶
func (s *RenderedResourceSnapshot) ExactEqual(other *RenderedResourceSnapshot) (bool, error)
ExactEqual compares complete resource identity without trusting a digest.
func (*RenderedResourceSnapshot) Len ¶
func (s *RenderedResourceSnapshot) Len() (int, error)
Len returns the number of desired resources.
func (*RenderedResourceSnapshot) Resources ¶
func (s *RenderedResourceSnapshot) Resources() ([]RenderedResource, error)
Resources returns a fully detached compatibility view.
func (*RenderedResourceSnapshot) SameRoot ¶
func (s *RenderedResourceSnapshot) SameRoot(other *RenderedResourceSnapshot) (bool, error)
SameRoot reports authenticated storage identity.
func (*RenderedResourceSnapshot) ValidateAuthentication ¶
func (s *RenderedResourceSnapshot) ValidateAuthentication() error
ValidateAuthentication verifies the exact private ownership chain.
type ResourceDeriver ¶
type ResourceDeriver interface {
DeriveResource(resource string, item any, path string, value any) (any, error)
}
ResourceDeriver publishes a transformed resource into the current render's view.
type ResourceStore ¶
type ResourceStore interface {
// List returns all resources from the store.
List() []any
// Fetch returns resources matching the given keys (typically namespace, name).
Fetch(keys ...any) []any
// GetSingle returns a single resource matching the keys, or nil if not found.
GetSingle(keys ...any) any
}
ResourceStore defines the interface for resource stores accessible from templates. This interface enables direct method calls in Scriggo templates:
{% for _, ing := range resources.ingresses.List() %}
{% var secret = resources.secrets.GetSingle(namespace, name) %}
{% for _, ep := range resources.endpoints.Fetch(serviceName) %}
Scriggo supports dot notation for map access, so `resources.ingresses` is equivalent to `resources["ingresses"]`.
Implementations are provided by pkg/controller/rendercontext.StoreWrapper.
type RuntimeEnvironment ¶
type RuntimeEnvironment struct {
// GOMAXPROCS is the maximum number of OS threads for parallel execution.
// Used by sharding logic to calculate optimal shard count.
GOMAXPROCS int
}
RuntimeEnvironment holds runtime information available to templates. This enables templates to adapt behavior based on the execution environment.
Templates access this via the runtimeEnvironment variable:
{%- var maxShards = runtimeEnvironment.GOMAXPROCS * 2 %}
Fields use exported names for direct template access.
type ScriggoEngine ¶
type ScriggoEngine struct {
// contains filtered or unexported fields
}
ScriggoEngine provides template compilation and rendering capabilities using Scriggo. It pre-compiles all templates at initialization for optimal runtime performance and early detection of syntax errors.
Scriggo uses Go template syntax, which is different from Jinja2:
- Loops: {% for x := range items %}...{% end %}
- Conditionals: {% if cond %}...{% else if other %}...{% end %}
- Variables: {{ .name }} or {{ name }} when in globals
This engine offers excellent performance and low memory usage with Go-style template syntax.
func New ¶
func New(templates map[string]string, opts *Options) (*ScriggoEngine, error)
New creates a Scriggo (Go template syntax) template engine.
Only opts.EntryPoints are compiled explicitly — or every template, when opts is nil or opts.EntryPoints is nil — so syntax errors are caught early. Templates not listed as entry points are snippets, compiled automatically when referenced via render/render_glob statements with inherit_context.
func (*ScriggoEngine) AppendTraces ¶
func (e *ScriggoEngine) AppendTraces(other Engine)
AppendTraces appends traces from another engine to this engine's trace buffer. This is useful for aggregating traces from multiple worker engines.
func (*ScriggoEngine) BeginPostProcessTransaction ¶
func (e *ScriggoEngine) BeginPostProcessTransaction( ctx context.Context, ) (context.Context, PostProcessTransaction)
func (*ScriggoEngine) BindIncrementalResources ¶
func (e *ScriggoEngine) BindIncrementalResources( templateName string, resources any, lease IncrementalResourceInvocationLease, ) (any, error)
BindIncrementalResources binds the resource callables reachable by one entry point.
func (*ScriggoEngine) BindIncrementalSourceTransactionResources ¶
func (e *ScriggoEngine) BindIncrementalSourceTransactionResources( templateNames []string, resources any, lease IncrementalResourceInvocationLease, selector IncrementalSourceTransactionChildSelector, ) (any, error)
func (*ScriggoEngine) ClearVMPool ¶
func (e *ScriggoEngine) ClearVMPool()
ClearVMPool releases pooled Scriggo VMs to allow garbage collection. Call after rendering completes to reduce memory from parallel rendering spikes.
This is safe to call at any time - VMs currently in use are not affected (they're held by goroutines, not in the pool). Only pooled VMs waiting for reuse are released.
func (*ScriggoEngine) DisableFilterDebug ¶
func (e *ScriggoEngine) DisableFilterDebug()
DisableFilterDebug disables detailed filter operation logging.
func (*ScriggoEngine) DisableTracing ¶
func (e *ScriggoEngine) DisableTracing()
DisableTracing disables template execution tracing.
func (*ScriggoEngine) EnableFilterDebug ¶
func (e *ScriggoEngine) EnableFilterDebug()
EnableFilterDebug enables detailed filter operation logging.
func (*ScriggoEngine) EnableTracing ¶
func (e *ScriggoEngine) EnableTracing()
EnableTracing enables template execution tracing.
func (*ScriggoEngine) EntryPointUsedGlobals ¶
func (e *ScriggoEngine) EntryPointUsedGlobals(name string) []string
func (*ScriggoEngine) EntryPointUsedNativeValueAccesses ¶
func (e *ScriggoEngine) EntryPointUsedNativeValueAccesses(name string) []scriggo.UsedNativeValueAccess
func (*ScriggoEngine) GetRawTemplate ¶
func (e *ScriggoEngine) GetRawTemplate(templateName string) (string, error)
GetRawTemplate returns the original template string for the given name.
func (*ScriggoEngine) GetTraceOutput ¶
func (e *ScriggoEngine) GetTraceOutput() string
GetTraceOutput returns accumulated trace output and clears the buffer.
func (*ScriggoEngine) GlobalUsage ¶
func (e *ScriggoEngine) GlobalUsage(name string) (used, known bool)
GlobalUsage reports whether any compiled entry point reads name.
func (*ScriggoEngine) HasTemplate ¶
func (e *ScriggoEngine) HasTemplate(templateName string) bool
HasTemplate checks if a template with the given name exists.
func (*ScriggoEngine) IncrementalComponentSourceTransactionsEligibility ¶
func (e *ScriggoEngine) IncrementalComponentSourceTransactionsEligibility() bool
func (*ScriggoEngine) IncrementalComponentVectorCarrierDiagnostic ¶
func (e *ScriggoEngine) IncrementalComponentVectorCarrierDiagnostic() error
IncrementalComponentVectorCarrierDiagnostic returns the fail-closed build rejection.
func (*ScriggoEngine) IncrementalComponentVectorCarrierEligibility ¶
func (e *ScriggoEngine) IncrementalComponentVectorCarrierEligibility() ( IncrementalComponentVectorCarrierEligibility, bool, )
func (*ScriggoEngine) IncrementalComponentVectorEligibility ¶
func (e *ScriggoEngine) IncrementalComponentVectorEligibility( templateName string, ) (IncrementalComponentVectorEligibility, bool)
func (*ScriggoEngine) IsFilterDebugEnabled ¶
func (e *ScriggoEngine) IsFilterDebugEnabled() bool
IsFilterDebugEnabled returns true if filter debug logging is currently enabled.
func (*ScriggoEngine) IsProfilingEnabled ¶
func (e *ScriggoEngine) IsProfilingEnabled() bool
IsProfilingEnabled returns whether profiling is enabled for this engine.
func (*ScriggoEngine) IsTracingEnabled ¶
func (e *ScriggoEngine) IsTracingEnabled() bool
IsTracingEnabled returns whether tracing is currently enabled.
func (*ScriggoEngine) MatchIncrementalBindingInputs ¶
func (e *ScriggoEngine) MatchIncrementalBindingInputs( entryPoints []string, bindingContext map[string]any, snapshot *IncrementalBindingInputSnapshot, ) bool
MatchIncrementalBindingInputs compares live private inputs without cloning them on a cache hit.
func (*ScriggoEngine) PostProcess ¶
PostProcess applies a template's configured post-processor chain to text that did not come from that render pass. Plan assembly uses it so a section body spliced into the config is normalised exactly like its surroundings.
func (*ScriggoEngine) PostProcessBatch ¶
func (e *ScriggoEngine) PostProcessBatch( ctx context.Context, templateName string, inputs []string, ) ([]string, error)
PostProcessBatch returns one post-processed output per input in the same order.
func (*ScriggoEngine) PostProcessReuseProof ¶
func (e *ScriggoEngine) PostProcessReuseProof(templateName string) (*PostProcessReuseProof, error)
PostProcessReuseProof returns nil when the chain cannot be proven deterministic.
func (*ScriggoEngine) PrepareExactCycleReplay ¶
func (e *ScriggoEngine) PrepareExactCycleReplay( entryPoints []string, ) (*ExactCycleReplayProgram, error)
PrepareExactCycleReplay rejects root programs with an unproved native surface.
func (*ScriggoEngine) RawTextRenderInstrumented ¶
func (e *ScriggoEngine) RawTextRenderInstrumented() bool
RawTextRenderInstrumented reports whether root post-processing must remain inside Render.
func (*ScriggoEngine) Render ¶
func (e *ScriggoEngine) Render(ctx context.Context, templateName string, templateContext map[string]any) (string, error)
Render executes a template with the given context and returns the output.
func (*ScriggoEngine) RenderIncrementalBindings ¶
func (e *ScriggoEngine) RenderIncrementalBindings( ctx context.Context, templateName string, bindingContext map[string]any, ) ([]byte, error)
RenderIncrementalBindings executes a binding planner and returns canonical JSON.
func (*ScriggoEngine) RenderIncrementalBindingsSnapshot ¶
func (e *ScriggoEngine) RenderIncrementalBindingsSnapshot( ctx context.Context, templateName string, snapshot *IncrementalBindingInputSnapshot, ) ([]byte, error)
RenderIncrementalBindingsSnapshot executes one planner from a matching snapshot.
func (*ScriggoEngine) RenderIncrementalComponent ¶
func (e *ScriggoEngine) RenderIncrementalComponent( ctx context.Context, templateName string, templateContext map[string]any, ) (string, error)
RenderIncrementalComponent executes a component entry point without entry-point post-processing.
func (*ScriggoEngine) RenderIncrementalComponentSourceTransactions ¶
func (e *ScriggoEngine) RenderIncrementalComponentSourceTransactions( ctx context.Context, input IncrementalComponentSourceTransactionsInput, ) (err error)
func (*ScriggoEngine) RenderIncrementalComponentVector ¶
func (e *ScriggoEngine) RenderIncrementalComponentVector( ctx context.Context, templateName string, input IncrementalComponentVectorInput, ) (err error)
func (*ScriggoEngine) RenderIncrementalComponentVectorCarrierWaves ¶
func (e *ScriggoEngine) RenderIncrementalComponentVectorCarrierWaves( ctx context.Context, input IncrementalComponentVectorCarrierWavesInput, ) (err error)
func (*ScriggoEngine) RenderIncrementalComponents ¶
func (e *ScriggoEngine) RenderIncrementalComponents( ctx context.Context, templateName string, items []IncrementalComponentBatchItem, ) ([]string, error)
RenderIncrementalComponents executes one private entry point over isolated contexts while reusing Scriggo's virtual machine and global slots.
func (*ScriggoEngine) RenderRawTo ¶
func (e *ScriggoEngine) RenderRawTo( ctx context.Context, templateName string, templateContext map[string]any, output io.Writer, ) ([]IncludeStats, error)
RenderRawTo streams a render before newline normalization and post-processing.
func (*ScriggoEngine) RenderWithProfiling ¶
func (e *ScriggoEngine) RenderWithProfiling(ctx context.Context, templateName string, templateContext map[string]any) (string, []IncludeStats, error)
RenderWithProfiling renders a template and returns profiling statistics.
When profiling is enabled (via Options.Profiling), this method returns aggregated include timing statistics. When profiling is disabled, returns nil for the stats slice.
func (*ScriggoEngine) RenderWithSourceMap ¶
func (e *ScriggoEngine) RenderWithSourceMap(ctx context.Context, templateName string, templateContext map[string]any) (raw string, spans []SourceSpan, err error)
RenderWithSourceMap renders a template like Render, but additionally returns a source map: one span per contiguous run of output attributing it to the template source (path + line) that produced it. The returned string is the RAW render output BEFORE post-processors run, so the span Length fields sum to its size exactly; callers that display the post-processed output must align the two (post-processors are whitespace-only for the bundled chart). Output from a parallel "{{ go … }}" render is attributed to the go-render call site.
func (*ScriggoEngine) ReuseExactCycleRoot ¶
func (e *ScriggoEngine) ReuseExactCycleRoot(ctx context.Context, templateName string) error
ReuseExactCycleRoot accounts for a root whose previous output the caller reuses, so the cycle's root invocations stay complete and in order.
func (*ScriggoEngine) SnapshotIncrementalBindingInputs ¶
func (e *ScriggoEngine) SnapshotIncrementalBindingInputs( entryPoints []string, bindingContext map[string]any, ) (*IncrementalBindingInputSnapshot, error)
SnapshotIncrementalBindingInputs captures every input used by entryPoints once.
func (*ScriggoEngine) TemplateCount ¶
func (e *ScriggoEngine) TemplateCount() int
TemplateCount returns the number of templates in the engine.
func (*ScriggoEngine) TemplateNames ¶
func (e *ScriggoEngine) TemplateNames() []string
TemplateNames returns the names of all available templates, sorted alphabetically.
type SharedContext ¶
type SharedContext struct {
// contains filtered or unexported fields
}
SharedContext provides thread-safe caching with compute-once semantics. It is used for sharing data between parallel template renders within a single reconciliation cycle.
The API is intentionally minimal to prevent race conditions:
- ComputeIfAbsent stores values atomically (uses singleflight)
- Get provides read-only access to existing values
- No Set method exists - prevents racy check-then-act patterns
- The wasComputed return value enables deduplication (FirstSeen pattern)
func NewSharedContext ¶
func NewSharedContext() *SharedContext
NewSharedContext creates a new thread-safe shared context.
func (*SharedContext) ComputeIfAbsent ¶
func (s *SharedContext) ComputeIfAbsent(key string, compute func() any) (any, bool)
ComputeIfAbsent returns the value for key, computing it if not present. Uses singleflight to ensure only one goroutine computes for a given key. Other goroutines waiting for the same key will receive the computed result.
Returns (value, wasComputed) where:
- value: the stored value (either existing or newly computed)
- wasComputed: true only for the goroutine that actually ran compute()
Use wasComputed for deduplication (FirstSeen pattern):
_, wasFirst := shared.ComputeIfAbsent("seen:"+key, func() any { return true })
if wasFirst {
// First occurrence
}
Use with nil fallback for read-only access:
val, _ := shared.ComputeIfAbsent("key", func() any { return nil })
IMPORTANT: The compute function is called WITHOUT holding the mutex, so it may safely call ComputeIfAbsent for other keys (nested/recursive calls).
func (*SharedContext) Count ¶
func (*SharedContext) Count(_, _ string) int
func (*SharedContext) ExactCycleProtocolState ¶
func (s *SharedContext) ExactCycleProtocolState() (ExactCycleProtocolState, error)
ExactCycleProtocolState proves that this context starts empty and is owned by one render.
func (*SharedContext) Get ¶
func (s *SharedContext) Get(key string) any
Get returns the value for key, or nil if not found. This is a read-only operation - use ComputeIfAbsent for initialization.
func (*SharedContext) Publish ¶
func (*SharedContext) Publish(_, _ string, _ any) string
Publish declares an immutable keyed value inside an incremental component.
func (*SharedContext) PublishRanked ¶
func (*SharedContext) PublishRanked(_, _, _ string, _ any) string
func (*SharedContext) SelectValues ¶
func (*SharedContext) SelectValues(_, _ string) []any
func (*SharedContext) Unique ¶
func (*SharedContext) Unique(_, _, _ string) string
Unique contributes one value per key; the lowest stable owner wins.
type SharedContributionContext ¶
type SharedContributionContext interface {
// contains filtered or unexported methods
}
SharedContributionContext is the deterministic shared-state surface.
func NewLeasedSharedContributionContext ¶
func NewLeasedSharedContributionContext( ctx context.Context, recorder SharedContributionRecorder, selectors ...SharedValueSelector, ) SharedContributionContext
NewLeasedSharedContributionContext rejects work after ctx's component lease ends.
func NewSharedContributionContext ¶
func NewSharedContributionContext( recorder SharedContributionRecorder, selectors ...SharedValueSelector, ) SharedContributionContext
NewSharedContributionContext creates an owner-scoped incremental contribution surface.
type SharedContributionRecorder ¶
type SharedContributionRecorder interface {
}
SharedContributionRecorder receives immutable owner-scoped state operations.
type SharedValueSelector ¶
type SharedValueSelector interface {
}
SharedValueSelector resolves one exact publication for an incremental component.
type SourceFrame ¶
type SourceFrame = scriggo.SourceFrame
type SourceSpan ¶
type SourceSpan = scriggo.SourceSpan
SourceSpan / SourceFrame attribute a contiguous run of rendered output to the template include stack that produced it (see RenderWithSourceMap). They are aliases for the engine-level types so callers need not import the Scriggo package.
type StatusPatch ¶
type StatusPatch struct {
// Namespace of the target Kubernetes resource.
Namespace string
// Name of the target Kubernetes resource.
Name string
// APIVersion of the target resource (e.g., "networking.k8s.io/v1").
APIVersion string
// Kind of the target resource (e.g., "Service", "ConfigMap", or any watched CRD's Kind).
Kind string
// UID identifies the exact source resource incarnation. Empty for offline and legacy inputs.
UID string
// ResourceVersion identifies the exact source resource revision. Empty for offline and legacy inputs.
ResourceVersion string
// ListOwnership encodes status-relative JSON pointers and entry selectors. Empty replaces complete lists.
ListOwnership string
// Variants maps pipeline phase names to desired status payloads.
// Keys are phase names: "rendered", "deployed", "renderFailed", "deployFailed".
// Values are the desired .status content for that phase.
Variants map[string]map[string]any
// SourceTemplate is the template path that called statusPatch() to register
// this patch (best-effort, from native.Env.CallPath). Empty when unknown.
// SourceLine is the 1-based line within that template of the statusPatch()
// call (from native.Env.CallLine), 0 when unknown. Provenance metadata only —
// the controller never reads them; they let the playground jump from a
// rendered status block back to the exact statusPatch() call. Resource-agnostic:
// a template name and line, not a resource path.
SourceTemplate string
SourceLine int
}
StatusPatch represents a status update to apply to a Kubernetes resource. Templates register patches via the statusPatch() function during rendering. Each patch targets a specific resource and contains outcome-keyed variants for different pipeline lifecycle phases.
func (*StatusPatch) Target ¶
func (p *StatusPatch) Target() StatusPatchTarget
Target identifies the resource addressed by p.
type StatusPatchCollector ¶
type StatusPatchCollector struct {
// contains filtered or unexported fields
}
StatusPatchCollector collects status patches registered by templates during rendering. It is thread-safe for concurrent writes from parallel template goroutines. Created per render cycle (same lifecycle as FileRegistry).
func NewStatusPatchCollector ¶
func NewStatusPatchCollector() *StatusPatchCollector
NewStatusPatchCollector creates a new thread-safe collector.
func (*StatusPatchCollector) ExactCycleProtocolState ¶
func (c *StatusPatchCollector) ExactCycleProtocolState() (ExactCycleProtocolState, error)
ExactCycleProtocolState proves that this collector starts empty and mutable.
func (*StatusPatchCollector) Patches ¶
func (c *StatusPatchCollector) Patches() ([]StatusPatch, error)
Patches returns all collected status patches as a detached snapshot.
func (*StatusPatchCollector) Register ¶
func (c *StatusPatchCollector) Register(namespace, name, apiVersion, kind string, variants map[string]map[string]any) error
Register registers a status patch for a Kubernetes resource. If a patch for the same resource already exists, the variant maps are merged (later calls override earlier ones for the same variant key).
The variants parameter maps phase names to status payloads:
- "rendered": applied after successful render
- "deployed": applied after successful deployment
- "renderFailed": applied when later render phases fail
- "deployFailed": applied when deployment fails
func (*StatusPatchCollector) RegisterWithLineage ¶
func (c *StatusPatchCollector) RegisterWithLineage( namespace, name, apiVersion, kind, uid, resourceVersion string, variants map[string]map[string]any, listOwnership ...string, ) error
RegisterWithLineage registers a patch for one exact source resource revision.
func (*StatusPatchCollector) ReplayProjectionPlan ¶
func (c *StatusPatchCollector) ReplayProjectionPlan(replay *StatusPatchProjectionPlanReplay) error
ReplayProjectionPlan stages an authenticated persistent plan without expanding it.
func (*StatusPatchCollector) ReplayProjections ¶
func (c *StatusPatchCollector) ReplayProjections(replays []*StatusPatchProjectionReplay) error
ReplayProjections merges authenticated projections without exposing their cached values.
func (*StatusPatchCollector) SetSource ¶
func (c *StatusPatchCollector) SetSource(namespace, name, apiVersion, kind, sourceTemplate string, sourceLine int)
SetSource records the template and line that registered the patch for the given target, if a patch exists and none is set yet. Best-effort provenance used by the playground; a no-op if the target was never registered. Kept separate from Register so the render-path signature and all its callers stay unchanged.
func (*StatusPatchCollector) Snapshot ¶
func (c *StatusPatchCollector) Snapshot(previous ...*StatusPatchSnapshot) (*StatusPatchSnapshot, error)
Snapshot seals the collector and reuses previous when every patch is exact.
type StatusPatchProjection ¶
type StatusPatchProjection struct {
// contains filtered or unexported fields
}
StatusPatchProjection is an immutable compiled set of status-patch calls.
func NewStatusPatchProjection ¶
func NewStatusPatchProjection(calls []StatusPatch) (*StatusPatchProjection, error)
NewStatusPatchProjection compiles ordered status-patch calls into immutable storage.
func NewStatusPatchProjectionGroup ¶
func NewStatusPatchProjectionGroup(parts []*StatusPatchProjection) (*StatusPatchProjection, error)
NewStatusPatchProjectionGroup composes ordered immutable projections without copying their values.
func (*StatusPatchProjection) PrepareReplay ¶
func (p *StatusPatchProjection) PrepareReplay() (*StatusPatchProjectionReplay, error)
PrepareReplay validates the projection and returns an authenticated replay view.
func (*StatusPatchProjection) ValidateAuthentication ¶
func (p *StatusPatchProjection) ValidateAuthentication() error
ValidateAuthentication verifies the projection's private ownership seal.
type StatusPatchProjectionClaim ¶
type StatusPatchProjectionClaim struct {
Namespace string
Name string
APIVersion string
Kind string
UID string
ResourceVersion string
ListOwnership string
Phase string
}
StatusPatchProjectionClaim identifies one target phase owned by a projection.
type StatusPatchProjectionPlan ¶
type StatusPatchProjectionPlan struct {
// contains filtered or unexported fields
}
StatusPatchProjectionPlan is an immutable persistent index of named projections.
func NewStatusPatchProjectionPlan ¶
func NewStatusPatchProjectionPlan() *StatusPatchProjectionPlan
NewStatusPatchProjectionPlan returns an empty authenticated projection plan.
func NewStatusPatchProjectionPlanFromEntries ¶
func NewStatusPatchProjectionPlanFromEntries( entries []StatusPatchProjectionPlanEntry, ) (*StatusPatchProjectionPlan, error)
NewStatusPatchProjectionPlanFromEntries builds an authenticated plan atomically from ordered entries.
func (*StatusPatchProjectionPlan) PrepareReplay ¶
func (p *StatusPatchProjectionPlan) PrepareReplay() (*StatusPatchProjectionPlanReplay, error)
PrepareReplay validates the plan and returns an authenticated replay view.
func (*StatusPatchProjectionPlan) ReplaceEntry ¶
func (p *StatusPatchProjectionPlan) ReplaceEntry( group, entry string, statusProjection *StatusPatchProjection, ) (*StatusPatchProjectionPlan, error)
ReplaceEntry replaces one lexically ordered projection within a conflict group.
func (*StatusPatchProjectionPlan) ReplaceGroup ¶
func (p *StatusPatchProjectionPlan) ReplaceGroup( group string, statusProjection *StatusPatchProjection, ) (*StatusPatchProjectionPlan, error)
ReplaceGroup returns a fresh plan with group replaced, or the same plan when already exact.
func (*StatusPatchProjectionPlan) ValidateAuthentication ¶
func (p *StatusPatchProjectionPlan) ValidateAuthentication() error
ValidateAuthentication verifies the plan's exact private ownership chain.
type StatusPatchProjectionPlanEntry ¶
type StatusPatchProjectionPlanEntry struct {
Group string
Entry string
Projection *StatusPatchProjection
}
StatusPatchProjectionPlanEntry identifies one ordered projection within a conflict group.
type StatusPatchProjectionPlanReplay ¶
type StatusPatchProjectionPlanReplay struct {
// contains filtered or unexported fields
}
StatusPatchProjectionPlanReplay authenticates one plan for synchronous replay.
func (*StatusPatchProjectionPlanReplay) Empty ¶
func (r *StatusPatchProjectionPlanReplay) Empty() bool
Empty reports whether the plan contains no target resources.
type StatusPatchProjectionReplay ¶
type StatusPatchProjectionReplay struct {
// contains filtered or unexported fields
}
StatusPatchProjectionReplay authenticates one projection for synchronous replay.
func (*StatusPatchProjectionReplay) Empty ¶
func (r *StatusPatchProjectionReplay) Empty() bool
Empty reports whether the projection contains no status-patch calls.
func (*StatusPatchProjectionReplay) VisitClaims ¶
func (r *StatusPatchProjectionReplay) VisitClaims(visit func(StatusPatchProjectionClaim) error) error
VisitClaims visits every unique target phase in deterministic order.
type StatusPatchSnapshot ¶
type StatusPatchSnapshot struct {
// contains filtered or unexported fields
}
StatusPatchSnapshot is an authenticated immutable status-patch set.
func (*StatusPatchSnapshot) ChangedPatchesForPhase ¶
func (s *StatusPatchSnapshot) ChangedPatchesForPhase(previous *StatusPatchSnapshot, phase string) ([]StatusPatch, error)
ChangedPatchesForPhase materializes current patches whose contributions changed. A nil previous selects everything; removed contributions may expose older variants.
func (*StatusPatchSnapshot) ExactEqual ¶
func (s *StatusPatchSnapshot) ExactEqual(other *StatusPatchSnapshot) (bool, error)
ExactEqual compares every patch after detached materialization.
func (*StatusPatchSnapshot) Len ¶
func (s *StatusPatchSnapshot) Len() (int, error)
Len returns the number of target resources in an authenticated snapshot.
func (*StatusPatchSnapshot) Patches ¶
func (s *StatusPatchSnapshot) Patches() ([]StatusPatch, error)
Patches returns a fully detached compatibility view.
func (*StatusPatchSnapshot) PatchesForPhase ¶
func (s *StatusPatchSnapshot) PatchesForPhase(phase string) ([]StatusPatch, error)
PatchesForPhase returns detached patches containing only the requested phase.
func (*StatusPatchSnapshot) PatchesForPhaseTargets ¶
func (s *StatusPatchSnapshot) PatchesForPhaseTargets(phase string, targets []StatusPatchTarget) ([]StatusPatch, error)
PatchesForPhaseTargets materializes current patches for the selected targets. Targets absent from this snapshot or phase contribute no patch.
func (*StatusPatchSnapshot) SameRoot ¶
func (s *StatusPatchSnapshot) SameRoot(other *StatusPatchSnapshot) (bool, error)
SameRoot reports exact authenticated snapshot identity.
func (*StatusPatchSnapshot) ValidateAuthentication ¶
func (s *StatusPatchSnapshot) ValidateAuthentication() error
ValidateAuthentication verifies the snapshot's exact ownership chain.
type StatusPatchTarget ¶
StatusPatchTarget identifies a resource independently of its current patch.
type TemplateNotFoundError ¶
type TemplateNotFoundError struct {
// TemplateName is the name of the requested template
TemplateName string
// AvailableTemplates lists all available template names
AvailableTemplates []string
}
TemplateNotFoundError represents a request for a non-existent template.
func NewTemplateNotFoundError ¶
func NewTemplateNotFoundError(templateName string, availableTemplates []string) *TemplateNotFoundError
NewTemplateNotFoundError creates a TemplateNotFoundError with the list of available templates.
func (*TemplateNotFoundError) Error ¶
func (e *TemplateNotFoundError) Error() string
Error implements the error interface.
type TemplatePostProcessor ¶
type TemplatePostProcessor struct {
// contains filtered or unexported fields
}
TemplatePostProcessor applies a Scriggo template transformation to the rendered output.
The template receives the rendered output as the `input` variable (string) and has access to all standard Scriggo builtins (regexp, replace, len, tostring, etc.). The template's output becomes the new rendered content.
This enables arbitrary post-processing logic using familiar template syntax, such as counting patterns, replacing placeholders with computed values, or validating the rendered output.
func NewTemplatePostProcessor ¶
func NewTemplatePostProcessor(source string, globals native.Declarations) (*TemplatePostProcessor, error)
NewTemplatePostProcessor creates a new template post-processor from Scriggo source.
The source is compiled during engine initialization with all standard globals plus an `input` variable (string) that receives the rendered output at processing time. Compilation errors are caught at init time (fail-fast), not at render time.
Parameters:
- source: Scriggo template source code
- globals: Engine globals to make available in the post-processor template
Returns an error if:
- The source is empty
- The template has syntax errors (compilation failure)
func (*TemplatePostProcessor) Process ¶
func (p *TemplatePostProcessor) Process(input string) (string, error)
Process applies the template transformation to the input string.
The input (previously rendered template output) is passed as the `input` variable. The template's output becomes the new rendered content.
type TextFragment ¶
type TextFragment = native.TextFragment
TextFragment is immutable, replayable text that can be retained by a text sink.
type WorkerGate ¶
type WorkerGate interface {
// TryAcquire reports whether one more worker may run a chunk now.
TryAcquire() bool
// Release returns a worker admitted by TryAcquire.
Release()
}
WorkerGate admits the extra workers of a parallel batch. A batch's first worker always runs, so a gate that admits none still lets the batch finish.
func WorkerGateOf ¶
func WorkerGateOf(ctx context.Context) WorkerGate
WorkerGateOf returns the gate WithWorkerGate attached to ctx, or nil.
Source Files
¶
- cycle_time.go
- declaration_names.go
- deterministic_scalar.go
- engine_interface.go
- engine_scriggo.go
- engine_scriggo_fs.go
- engine_scriggo_tracing.go
- error_formatter.go
- errors.go
- exact_cycle_effects.go
- exact_cycle_protocol_state.go
- exact_cycle_replay.go
- filter_names.go
- filters.go
- filters_archive.go
- filters_cidr.go
- filters_collection.go
- filters_guid.go
- filters_jsonpath.go
- filters_lines.go
- filters_navigation.go
- filters_pipeline.go
- filters_public_key.go
- filters_scriggo.go
- filters_status.go
- filters_string.go
- filters_type.go
- filters_version.go
- filters_yaml.go
- func_types.go
- immutable_projection_value.go
- incremental_component_context.go
- incremental_detached_value.go
- incremental_effects.go
- incremental_globals.go
- incremental_helpers.go
- incremental_http.go
- incremental_immutability.go
- incremental_immutable_certificate_index.go
- incremental_keys.go
- incremental_lane_dispatch.go
- incremental_native_frames.go
- incremental_planner.go
- incremental_resource_binding.go
- incremental_resource_declaration.go
- incremental_resource_keys.go
- incremental_runtime.go
- incremental_serialization.go
- incremental_sort.go
- incremental_source_transaction.go
- incremental_source_transaction_compile.go
- incremental_source_transaction_resource_binding.go
- incremental_vector_carrier_compile.go
- incremental_vector_carrier_execution.go
- incremental_vector_carrier_waves.go
- incremental_vector_compile.go
- incremental_vector_execution.go
- postprocessor.go
- postprocessor_batch.go
- postprocessor_cache.go
- postprocessor_regex.go
- postprocessor_reuse.go
- postprocessor_template.go
- postprocessor_transaction.go
- profiling.go
- regex_cache.go
- render_event.go
- render_event_snapshot.go
- rendered_resource.go
- rendered_resource_snapshot.go
- resource_derivation.go
- shared_context.go
- sorting.go
- sorting_helpers.go
- status_patch.go
- status_patch_delta.go
- status_patch_lists.go
- status_patch_projection.go
- status_patch_projection_plan.go
- status_patch_selection.go
- status_patch_snapshot.go
- synchronous_declarations.go
- types.go
- worker_gate.go