Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/docs/operator/building-blocks/entities.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public class EntitySpec
- `[RangeMinimum]` and `[RangeMaximum]`: Defines numeric value ranges
- `[MultipleOf]`: Specifies that a number must be a multiple of a given value
- `[Items]`: Defines minimum and maximum items for arrays
- `[ValidationRule]`: Defines custom validation rules using CEL expressions
- `[ValidationRule]`: Defines custom validation rules using CEL expressions. Can be applied to properties and to class types — in both cases it emits `x-kubernetes-validations` on the corresponding schema node. When applied to both a class and a property of that type, the rules are merged (class rules first, then property rules)

### Documentation Attributes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ namespace KubeOps.Abstractions.Entities.Attributes;
/// <param name="reason">
/// reason provides a machine-readable validation failure reason that is returned to the caller when a request fails this validation rule.
/// </param>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true)]
public sealed class ValidationRuleAttribute(
string rule,
string? fieldPath = null,
Expand Down
38 changes: 27 additions & 11 deletions src/KubeOps.Transpiler/Crds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ public static V1CustomResourceDefinition Transpile(this MetadataLoadContext cont
{ Count: > 0 } list => list,
_ => null,
},
XKubernetesValidations = context.MapValidationRules(
type.GetCustomAttributesData<ValidationRuleAttribute>()),
},
};

Expand Down Expand Up @@ -309,18 +311,12 @@ private static V1JSONSchemaProps Map(this MetadataLoadContext context, PropertyI
props.Properties = null;
}

if (prop.GetCustomAttributesData<ValidationRuleAttribute>().ToArray() is { Length: > 0 } validations)
var propValidations = context.MapValidationRules(prop.GetCustomAttributesData<ValidationRuleAttribute>());
if (propValidations != null)
{
props.XKubernetesValidations = validations
.Select(validation => new V1ValidationRule
{
Rule = validation.GetCustomAttributeCtorArg<string>(context, 0),
FieldPath = validation.GetCustomAttributeCtorArg<string?>(context, 1),
Message = validation.GetCustomAttributeCtorArg<string?>(context, 2),
MessageExpression = validation.GetCustomAttributeCtorArg<string?>(context, 3),
Reason = validation.GetCustomAttributeCtorArg<string?>(context, 4),
})
.ToList();
props.XKubernetesValidations = props.XKubernetesValidations is { } existing
? [.. existing, .. propValidations]
: propValidations;
}

return props;
Expand Down Expand Up @@ -411,6 +407,24 @@ static Type GetRootBaseType(Type type)
};
}

private static List<V1ValidationRule>? MapValidationRules(
this MetadataLoadContext context,
IEnumerable<CustomAttributeData> attributesData)
{
var rules = attributesData
.Select(v => new V1ValidationRule
{
Rule = v.GetCustomAttributeCtorArg<string>(context, 0),
FieldPath = v.GetCustomAttributeCtorArg<string?>(context, 1),
Message = v.GetCustomAttributeCtorArg<string?>(context, 2),
MessageExpression = v.GetCustomAttributeCtorArg<string?>(context, 3),
Reason = v.GetCustomAttributeCtorArg<string?>(context, 4),
})
.ToList();

return rules.Count > 0 ? rules : null;
}

private static IList<object> GetEnumNames(this MetadataLoadContext context, Type type)
{
#if NET9_0_OR_GREATER
Expand Down Expand Up @@ -484,6 +498,8 @@ private static V1JSONSchemaProps MapObjectType(this MetadataLoadContext context,
},
XKubernetesPreserveUnknownFields =
type.GetCustomAttributeData<PreserveUnknownFieldsAttribute>() != null ? true : null,
XKubernetesValidations = context.MapValidationRules(
type.GetCustomAttributesData<ValidationRuleAttribute>()),
};
}
}
Expand Down
87 changes: 87 additions & 0 deletions test/KubeOps.Transpiler.Test/Crds.Mlc.ValidationRule.Test.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,53 @@ public void Should_Omit_Validations()
specProperties.XKubernetesValidations.Should().BeNull();
}

[Fact]
public void Should_Set_Validations_On_Root_Class()
{
var crd = _mlc.Transpile(typeof(RootClassValidateAttrEntity));

var schema = crd.Spec.Versions[0].Schema.OpenAPIV3Schema;
schema.XKubernetesValidations.Should().HaveCount(1);
schema.XKubernetesValidations[0].Rule.Should().Be(Rule1);
schema.XKubernetesValidations[0].Message.Should().Be(Message1);
schema.XKubernetesValidations[0].MessageExpression.Should().BeNull();
schema.XKubernetesValidations[0].FieldPath.Should().BeNull();
schema.XKubernetesValidations[0].Reason.Should().BeNull();
}

[Fact]
public void Should_Set_Multiple_Validations_On_Root_Class()
{
var crd = _mlc.Transpile(typeof(MultiRootClassValidateAttrEntity));

var schema = crd.Spec.Versions[0].Schema.OpenAPIV3Schema;
schema.XKubernetesValidations.Should().HaveCount(2);
schema.XKubernetesValidations[0].Rule.Should().Be(Rule1);
schema.XKubernetesValidations[1].Rule.Should().Be(Rule2);
}

[Fact]
public void Should_Set_Validations_On_Nested_Class()
{
var crd = _mlc.Transpile(typeof(NestedClassValidateAttrEntity));

var nestedSchema = crd.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["nested"];
nestedSchema.XKubernetesValidations.Should().HaveCount(1);
nestedSchema.XKubernetesValidations[0].Rule.Should().Be(Rule1);
nestedSchema.XKubernetesValidations[0].Message.Should().Be(Message1);
}

[Fact]
public void Should_Merge_Class_And_Property_Validations()
{
var crd = _mlc.Transpile(typeof(ClassAndPropertyValidateAttrEntity));

var nestedSchema = crd.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["nested"];
nestedSchema.XKubernetesValidations.Should().HaveCount(2);
nestedSchema.XKubernetesValidations[0].Rule.Should().Be(Rule1);
nestedSchema.XKubernetesValidations[1].Rule.Should().Be(Rule2);
}

[Fact]
public void Should_Set_ValidationFields()
{
Expand All @@ -86,6 +133,46 @@ public sealed class NoValidateAttrEntity : CustomKubernetesEntity
public string Property { get; set; } = null!;
}

[KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
[ValidationRule(Rule1, message: Message1)]
public sealed class RootClassValidateAttrEntity : CustomKubernetesEntity
{
public string Property { get; set; } = null!;
}

[KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
[ValidationRule(Rule1, message: Message1)]
[ValidationRule(Rule2, message: Message2)]
public sealed class MultiRootClassValidateAttrEntity : CustomKubernetesEntity
{
public string Property { get; set; } = null!;
}

[KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
public sealed class NestedClassValidateAttrEntity : CustomKubernetesEntity
{
public NestedObject Nested { get; set; } = new();

[ValidationRule(Rule1, message: Message1)]
public sealed class NestedObject
{
public string Name { get; set; } = null!;
}
}

[KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
public sealed class ClassAndPropertyValidateAttrEntity : CustomKubernetesEntity
{
[ValidationRule(Rule2, message: Message2)]
public NestedWithClassRule Nested { get; set; } = new();

[ValidationRule(Rule1, message: Message1)]
public sealed class NestedWithClassRule
{
public string Name { get; set; } = null!;
}
}

[KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "TestEntity")]
public sealed class SingleValidateAttrEntity : CustomKubernetesEntity
{
Expand Down
Loading