Files
kubevela/pkg/definition/defkit/component.go
Vishal Kumar 732b49d236 Feat: defkit api completeness (#7064)
* docs: map existing codebase

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs: initialize project

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* Fix: add Short() and Ignore() methods to FloatParam for API completeness

FloatParam was the only param type missing Short(string) and Ignore()
fluent methods; the underlying baseParam fields already existed. Adds
matching test cases following the existing BoolParam/IntParam pattern.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(defkit): add StatusDetails() to all 4 definition types via baseDefinition

Adds statusDetails string field to baseDefinition with setStatusDetails()
setter and GetStatusDetails() getter. Exposes StatusDetails(string) fluent
method on ComponentDefinition, TraitDefinition, WorkflowStepDefinition, and
PolicyDefinition. Updates writeStatus in cuegen.go and the inline status
render block in trait.go to render statusDetails as a #"""..."""# CUE block
alongside customStatus and healthPolicy when set.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(01-02): add ForceOptional() to IntParam, FloatParam, EnumParam

- IntParam.ForceOptional() *IntParam
- FloatParam.ForceOptional() *FloatParam
- EnumParam.ForceOptional() *EnumParam
- Test cases for all three types following BoolParam/StringParam patterns

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-01): add Labels()/GetLabels() to PolicyDefinition and fix hardcoded labels CUE

- Add labels map[string]string field to PolicyDefinition struct
- Add Labels() fluent setter and GetLabels() getter
- Replace hardcoded labels: {} in PolicyCUEGenerator with nil-conditional sorted output
- Add sort import to policy.go

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(02-01): add Ginkgo tests for PolicyDefinition.Labels

- Test store/return labels
- Test sorted key output in CUE
- Test labels block omitted when Labels() never called
- Test empty labels block when Labels called with empty map

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(02-01): complete Labels on PolicyDefinition plan

- SUMMARY.md: plan 02-01 execution results
- STATE.md: phase 2 in progress, B1 satisfied, key decisions recorded
- ROADMAP.md: phase 2 progress updated (1/3 plans)
- REQUIREMENTS.md: B1 marked complete

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): add annotations field to baseDefinition with getter/setter

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-03): wire status block rendering into WorkflowStep and Policy CUE generators

- Add status: { customStatus, healthPolicy, statusDetails } rendering to WorkflowStepCUEGenerator.GenerateTemplate
- Add same status block rendering to PolicyCUEGenerator.GenerateTemplate
- Block only emitted when at least one status field is non-empty, matching trait.go pattern

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): add Annotations() fluent method to all 4 definition types

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): conditional sorted annotations CUE block for component, trait, policy

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(02-03): add Ginkgo status block CUE render tests for WorkflowStep and Policy

- 5 new tests in WorkflowStepDefinition/Status Block CUE Render context
- 5 new tests in PolicyDefinition/Status Block CUE Render context
- Rule 3 fix: restore sort import in trait.go (used by annotations render, spuriously flagged)

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): merge user annotations before category in workflow step CUE block

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): add sorted annotations CUE block to WorkflowStepCUEGenerator

- Wire sorted user annotations rendering into WorkflowStep.GenerateFullDefinition
- Matches pattern already added to Component, Trait, and Policy generators

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(02-02): merge user annotations into metadata.annotations in ToYAML for all 4 types

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(02-03): complete Wire Status Block Rendering plan

- Add 02-03-SUMMARY.md with full execution record
- Update STATE.md: phase 2 complete, new decision recorded
- Update ROADMAP.md progress for phase 2
- Mark B4 complete in REQUIREMENTS.md

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(02-02): add Annotations Ginkgo tests for all 4 definition types

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(02-02): complete Annotations plan - SUMMARY, STATE, ROADMAP updated

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03): create phase 3 plans for missing CRD spec fields

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-01): add Version() fluent method and GetVersion() to all 4 definition types

- version string field added to baseDefinition struct
- setVersion/GetVersion methods on baseDefinition following existing pattern
- Version(string) fluent setter on TraitDefinition, ComponentDefinition, PolicyDefinition, WorkflowStepDefinition
- TDD RED+GREEN: tests for round-trip pass; CUE/YAML render tests added (fail, to be fixed in next task)

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-02): add ManageWorkload/ControlPlaneOnly/RevisionEnabled to TraitDefinition

- Add manageWorkload, controlPlaneOnly, revisionEnabled bool fields to TraitDefinition struct
- Add ManageWorkload(), ControlPlaneOnly(), RevisionEnabled() fluent setters
- Add IsManageWorkload(), IsControlPlaneOnly(), IsRevisionEnabled() getters
- Emit conditionally in ToYAML only when true; ToCue() unaffected
- Add 11 round-trip tests covering defaults, setters, and YAML emission

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(03-03): add Ginkgo tests for ChildResourceKind accumulator on ComponentDefinition

- 7 specs covering nil default, single entry, multi-entry accumulation,
  selector preservation, ToYAML emit/omit, and chaining

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-02): add ManageHealthCheck to PolicyDefinition

- Add manageHealthCheck bool field to PolicyDefinition struct
- Add ManageHealthCheck() fluent setter and IsManageHealthCheck() getter
- Emit conditionally in ToYAML only when true; ToCue() unaffected
- Add 5 round-trip tests covering default, setter, YAML emission, and chaining

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* test(03-03): add Ginkgo tests for PodSpecPath on ComponentDefinition

- 5 specs covering empty default, set/get round-trip, ToYAML emit/omit,
  and chaining; both fields satisfy C5 (childResourceKinds) and C6 (podSpecPath)

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(03-01): render version in CUE output and spec.version in ToYAML for all 4 definition types

- cuegen.go: conditional version emit in ComponentDefinition GenerateFullDefinition (after description)
- trait.go: conditional version emit in TraitCUEGenerator.GenerateFullDefinition; spec.version in ToYAML
- policy.go: conditional version emit in PolicyCUEGenerator.GenerateFullDefinition; spec.version in ToYAML
- workflow_step.go: conditional version emit in WorkflowStepCUEGenerator.GenerateFullDefinition; spec.version in ToYAML
- version omitted entirely when not set; TDD GREEN phase complete

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03-03): complete ChildResourceKind+PodSpecPath plan - SUMMARY, STATE, ROADMAP updated

- C5 (childResourceKinds accumulator) and C6 (podSpecPath) requirements satisfied
- 12 Ginkgo specs added covering both fields

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03-02): complete boolean CRD spec fields plan — manageWorkload/controlPlaneOnly/revisionEnabled/manageHealthCheck

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(03-01): complete Version() plan — SUMMARY, STATE, ROADMAP updated

- 03-01-SUMMARY.md created documenting Version() on all 4 definition types
- STATE.md: 03-01 session log entry added; phase 3 marked complete; decision recorded
- ROADMAP.md: phase 3 updated to 3/3 plans executed; status Complete
- REQUIREMENTS.md: C1 marked complete

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(04): add gap closure plan 04-03 for vela-go-definitions call sites

Closes 17 ArrayOf→Of and 1 FilterPred→Filter call sites broken by the phase 04 renames.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(phase-4): low-risk renames — SetField→Set, ArrayOf→Of, FilterPred→Filter

A1: PolicyTemplate.SetField() renamed to Set()
A3: StructField.ArrayOf() renamed to Of()
A5: HelperBuilder.FilterPred(Predicate) renamed to Filter(Predicate);
    HelperBuilder.Filter(Condition) renamed to FilterCond(Condition)

All callers within defkit updated. Verification: 894 Ginkgo specs pass,
go build exits 0, zero occurrences of old names in pkg/definition/defkit/.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* docs(05-high-impact-renames): create phase plan

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat(phase-5): high-impact renames — Values→Enum, Fields→WithFields

A4: EnumParam.Values() renamed to Enum() — aligns with StringParam.Enum()
    and StructField.Enum(); 10 call sites updated in defkit tests

A2: StructParam.Fields() and OneOfVariant.Fields() renamed to WithFields()
    — aligns with ArrayParam and MapParam; ~50 call sites updated in defkit tests

Both repos build clean. go test ./pkg/definition/defkit/... passes.
Non-target .Fields() methods (InCondition, StructBuilder, ArrayElement etc.)
correctly preserved.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* chore: exclude .planning/ and .claude/ from version control

Local development artifacts only — not for upstream.

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* refactor: adjust formatting for consistency in component and policy definitions

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: add FilterCond method for filtering items by Condition expression

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: enhance filter condition handling with AND-composition for multiple filters

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>

* feat: rename Enum method to Values for consistency in parameter definitions

Signed-off-by: Jerrin Francis <jfo@>

* feat: simplify labels handling in policy and trait definitions

Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>

---------

Signed-off-by: Vishal Kumar <vishal210893@gmail.com>
Signed-off-by: Jerrin Francis <jfo@>
Signed-off-by: Jerrin Francis <jerrinfrancis7@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-03-10 11:28:23 +00:00

338 lines
11 KiB
Go

/*
Copyright 2025 The KubeVela Authors.
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 defkit
import (
"sigs.k8s.io/yaml"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/pkg/definition/defkit/placement"
)
// ComponentDefinition represents a KubeVela ComponentDefinition.
//
// ComponentDefinition embeds baseDefinition for common fields and methods shared
// with TraitDefinition and other definition types.
type ComponentDefinition struct {
baseDefinition // embedded common fields (name, description, params, template, etc.)
workload WorkloadType
labels map[string]string // metadata labels for the component definition
childResourceKinds []common.ChildResourceKind
podSpecPath string
}
// WorkloadType represents the workload type for a component.
type WorkloadType struct {
apiVersion string
kind string
autodetect bool // when true, uses "autodetects.core.oam.dev" without definition block
}
// NewComponent creates a new ComponentDefinition builder.
func NewComponent(name string) *ComponentDefinition {
return &ComponentDefinition{
baseDefinition: baseDefinition{
name: name,
params: make([]Param, 0),
},
}
}
// Description sets the component description.
func (c *ComponentDefinition) Description(desc string) *ComponentDefinition {
c.setDescription(desc)
return c
}
// Workload sets the workload type for this component.
func (c *ComponentDefinition) Workload(apiVersion, kind string) *ComponentDefinition {
c.workload = WorkloadType{apiVersion: apiVersion, kind: kind}
return c
}
// AutodetectWorkload sets the workload type to "autodetects.core.oam.dev".
// This is used for components where the workload type is auto-detected at runtime
// rather than being statically defined.
func (c *ComponentDefinition) AutodetectWorkload() *ComponentDefinition {
c.workload = WorkloadType{autodetect: true}
return c
}
// Params adds multiple parameter definitions to the component.
func (c *ComponentDefinition) Params(params ...Param) *ComponentDefinition {
c.addParams(params...)
return c
}
// Param adds a single parameter definition to the component.
// This provides a more fluent API when adding parameters one at a time.
func (c *ComponentDefinition) Param(param Param) *ComponentDefinition {
c.addParams(param)
return c
}
// Template sets the template function for the component.
func (c *ComponentDefinition) Template(fn func(tpl *Template)) *ComponentDefinition {
c.setTemplate(fn)
return c
}
// CustomStatus sets the custom status CUE expression for the component.
// This expression is used to compute a human-readable status message.
func (c *ComponentDefinition) CustomStatus(expr string) *ComponentDefinition {
c.setCustomStatus(expr)
return c
}
// HealthPolicy sets the health policy CUE expression for the component.
// This expression determines whether the component is healthy.
// For raw CUE strings, use this method directly.
// For composable health expressions, use HealthPolicyExpr with Health().
func (c *ComponentDefinition) HealthPolicy(expr string) *ComponentDefinition {
c.setHealthPolicy(expr)
return c
}
// HealthPolicyExpr sets the health policy using a composable HealthExpression.
// This allows building health checks programmatically using primitives like
// Condition, Field, Phase, Exists, And, Or, Not via Health().
//
// Example:
//
// h := defkit.Health()
// def.HealthPolicyExpr(h.Condition("Ready").IsTrue())
// def.HealthPolicyExpr(h.AllTrue("Ready", "Synced"))
// def.HealthPolicyExpr(h.And(
// h.Condition("Ready").IsTrue(),
// h.Field("status.replicas").Gt(0),
// ))
func (c *ComponentDefinition) HealthPolicyExpr(expr HealthExpression) *ComponentDefinition {
c.setHealthPolicyExpr(expr)
return c
}
// StatusDetails sets the status details CUE expression for the component.
func (c *ComponentDefinition) StatusDetails(details string) *ComponentDefinition {
c.setStatusDetails(details)
return c
}
// Annotations sets metadata annotations on the component definition.
func (c *ComponentDefinition) Annotations(annotations map[string]string) *ComponentDefinition {
c.setAnnotations(annotations)
return c
}
// Version sets the version string for the component definition.
func (c *ComponentDefinition) Version(v string) *ComponentDefinition {
c.setVersion(v)
return c
}
// DefName implements Definition.DefName - returns the definition name.
func (c *ComponentDefinition) DefName() string { return c.name }
// DefType implements Definition.DefType - returns the definition type.
func (c *ComponentDefinition) DefType() DefinitionType { return DefinitionTypeComponent }
// GetWorkload returns the workload type.
func (c *ComponentDefinition) GetWorkload() WorkloadType { return c.workload }
// Helper adds a helper type definition using fluent API.
// The param defines the schema for the helper type.
// Example:
//
// Helper("HealthProbe", defkit.Object("probe").WithFields(...))
func (c *ComponentDefinition) Helper(name string, param Param) *ComponentDefinition {
c.addHelper(name, param)
return c
}
// Labels sets metadata labels on the component definition.
// Usage: component.Labels(map[string]string{"ui-hidden": "true"})
func (c *ComponentDefinition) Labels(labels map[string]string) *ComponentDefinition {
c.labels = labels
return c
}
// GetLabels returns the component's metadata labels.
func (c *ComponentDefinition) GetLabels() map[string]string { return c.labels }
// ChildResourceKind adds a child resource kind entry to the component definition.
// Multiple calls accumulate entries.
func (c *ComponentDefinition) ChildResourceKind(apiVersion, kind string, selector map[string]string) *ComponentDefinition {
c.childResourceKinds = append(c.childResourceKinds, common.ChildResourceKind{
APIVersion: apiVersion,
Kind: kind,
Selector: selector,
})
return c
}
// GetChildResourceKinds returns all accumulated child resource kind entries.
func (c *ComponentDefinition) GetChildResourceKinds() []common.ChildResourceKind {
return c.childResourceKinds
}
// PodSpecPath sets the pod spec path for the component definition.
func (c *ComponentDefinition) PodSpecPath(path string) *ComponentDefinition {
c.podSpecPath = path
return c
}
// GetPodSpecPath returns the pod spec path.
func (c *ComponentDefinition) GetPodSpecPath() string { return c.podSpecPath }
// RawCUE sets raw CUE for complex component definitions that don't fit the builder pattern.
// When set, this bypasses all other template settings and outputs the raw CUE directly.
func (c *ComponentDefinition) RawCUE(cue string) *ComponentDefinition {
c.setRawCUE(cue)
return c
}
// WithImports adds CUE imports to the component definition.
// Usage: component.WithImports("strconv", "strings", "list")
func (c *ComponentDefinition) WithImports(imports ...string) *ComponentDefinition {
c.addImports(imports...)
return c
}
// RunOn adds placement conditions specifying which clusters this definition should run on.
// Use the placement package's fluent API to build conditions.
//
// Example:
//
// defkit.NewComponent("eks-only").
// RunOn(placement.Label("provider").Eq("aws")).
// RunOn(placement.Label("cluster-type").NotEq("vcluster"))
//
// Multiple RunOn calls are combined with AND semantics (all conditions must match).
func (c *ComponentDefinition) RunOn(conditions ...placement.Condition) *ComponentDefinition {
c.addRunOn(conditions...)
return c
}
// NotRunOn adds placement conditions specifying which clusters this definition should NOT run on.
// Use the placement package's fluent API to build conditions.
//
// Example:
//
// defkit.NewComponent("no-vclusters").
// NotRunOn(placement.Label("cluster-type").Eq("vcluster"))
//
// If any NotRunOn condition matches, the definition is ineligible for that cluster.
func (c *ComponentDefinition) NotRunOn(conditions ...placement.Condition) *ComponentDefinition {
c.addNotRunOn(conditions...)
return c
}
// ToCue generates the complete CUE definition string for this component.
// This is a convenience method that creates a CUEGenerator and calls GenerateFullDefinition.
func (c *ComponentDefinition) ToCue() string {
// If raw CUE is set, use it with the name from NewComponent() taking precedence
if c.HasRawCUE() {
return c.GetRawCUEWithName()
}
gen := NewCUEGenerator()
if len(c.GetImports()) > 0 {
gen.WithImports(c.GetImports()...)
}
return gen.GenerateFullDefinition(c)
}
// ToCueWithImports generates the CUE definition with the specified imports.
// Use this when the definition requires CUE standard library imports.
// Example: component.ToCueWithImports(CUEImports.Strconv, CUEImports.List)
func (c *ComponentDefinition) ToCueWithImports(imports ...string) string {
gen := NewCUEGenerator().WithImports(imports...)
return gen.GenerateFullDefinition(c)
}
// ToParameterSchema generates only the parameter schema block.
// This is useful for testing or comparing parameter schemas.
func (c *ComponentDefinition) ToParameterSchema() string {
gen := NewCUEGenerator()
return gen.GenerateParameterSchema(c)
}
// ToYAML generates the Kubernetes YAML representation of the ComponentDefinition.
// This produces a ComponentDefinition custom resource that can be applied to a cluster.
// Note: The CUE template is embedded in the spec.schematic.cue field.
func (c *ComponentDefinition) ToYAML() ([]byte, error) {
cueStr := c.ToCue()
// Build the ComponentDefinition CR structure
cr := map[string]any{
"apiVersion": "core.oam.dev/v1beta1",
"kind": "ComponentDefinition",
"metadata": map[string]any{
"name": c.GetName(),
"annotations": func() map[string]any {
a := map[string]any{}
for k, v := range c.GetAnnotations() {
a[k] = v
}
a["definition.oam.dev/description"] = c.GetDescription()
return a
}(),
},
"spec": map[string]any{
"workload": map[string]any{
"definition": map[string]any{
"apiVersion": c.workload.apiVersion,
"kind": c.workload.kind,
},
},
"schematic": map[string]any{
"cue": map[string]any{
"template": cueStr,
},
},
},
}
// Handle autodetect workload type
if c.workload.autodetect {
cr["spec"].(map[string]any)["workload"] = map[string]any{
"type": "autodetects.core.oam.dev",
}
}
if len(c.childResourceKinds) > 0 {
cr["spec"].(map[string]any)["childResourceKinds"] = c.childResourceKinds
}
if c.podSpecPath != "" {
cr["spec"].(map[string]any)["podSpecPath"] = c.podSpecPath
}
if c.GetVersion() != "" {
cr["spec"].(map[string]any)["version"] = c.GetVersion()
}
return yaml.Marshal(cr)
}
// APIVersion returns the workload API version.
func (w WorkloadType) APIVersion() string { return w.apiVersion }
// Kind returns the workload kind.
func (w WorkloadType) Kind() string { return w.kind }
// IsAutodetect returns true if the workload type is auto-detected at runtime.
func (w WorkloadType) IsAutodetect() bool { return w.autodetect }