Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retool how validators register and are called: everything's a tag! #89

Merged
merged 72 commits into from
Feb 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
72 commits
Select commit Hold shift + click to select a range
eb8d5b9
Update gengo dep to 20250207200755-1244d31929d7
thockin Feb 7, 2025
9b5bf7d
Remove unused parameter
thockin Jan 4, 2025
2ffce15
Change validation tag registry, do +optional
thockin Dec 30, 2024
fcd26ec
Add comments to Validations
thockin Jan 11, 2025
bf9cb96
Add tag tests for +optional, +required, +forbidden
thockin Jan 11, 2025
c38de17
Make +validate{True,False,Error} be regular tags
thockin Dec 31, 2024
f89e1e5
Add tag tests for +validate{False,True}
thockin Jan 12, 2025
cbb9164
Get rid of old TagContext
thockin Jan 1, 2025
48e55b6
Fix docs to use shared info
thockin Jan 1, 2025
67159a9
Rename TagContext2 -> TagContext
thockin Jan 1, 2025
29a75f0
Clean up documentation around the tag registry
thockin Jan 1, 2025
a761f17
Make +required and +forbidden be regular tags
thockin Jan 1, 2025
30065e5
Make +format, +maxLength, +maxItems regular tags
thockin Jan 2, 2025
3fcd5de
Add tag tests for +format, +maxLength, +maxItems
thockin Jan 12, 2025
f0e4c88
We don't need the TagDescriptor type assertion
thockin Jan 2, 2025
5a2e5ca
Make +enum be a regular tag
thockin Jan 2, 2025
716fafc
Add tag tests for +enum
thockin Jan 13, 2025
cdf5497
Distinguish TagValidators from TypeValidators
thockin Jan 13, 2025
bca2bc9
Make +union be a regular tag
thockin Jan 13, 2025
ebb5193
Add tag tests for +union and +unionMember
thockin Jan 13, 2025
45d8d97
Cleanup: always use validations.Add
thockin Jan 3, 2025
27a28e3
Rename TagRegistry -> ValidatorRegistry
thockin Jan 3, 2025
1a49693
Rename TagDescriptor -> TagValidator
thockin Jan 3, 2025
8964c8b
Rename TagContext -> Context
thockin Jan 3, 2025
afa6974
Rename TagScope -> Scope
thockin Jan 3, 2025
5c25581
Rename TagDoc.Contexts -> TagDoc.Scopes
thockin Jan 3, 2025
4d55b9b
Merge tags.go and validators.go
thockin Jan 4, 2025
8f68b6a
Rename tag-validator types to all be ...Validator
thockin Jan 3, 2025
20a8c9d
Make Init() take a config type like before
thockin Jan 4, 2025
c1eb2fd
Make +ifOption{En,Dis}abled be regular tags
thockin Jan 4, 2025
f30b42b
Add tag tests for +ifOption{En,Dis}abled
thockin Jan 13, 2025
a4b7f33
Sort tags before collecting validations
thockin Jan 4, 2025
09c6160
Remove older validator code, now dead
thockin Jan 4, 2025
6e004e8
Rename things to older, simpler names
thockin Jan 4, 2025
b24da8a
Hide registry impl behind an interface
thockin Jan 4, 2025
4b5795b
Clean up tag-docs, add args and usage
thockin Jan 4, 2025
d46956c
Use new SnippetWriter method to propagate errors
thockin Jan 11, 2025
34326fa
Reorder args to type-validation funcs
thockin Jan 18, 2025
053b7d0
Reorder arguments to internal function literals
thockin Jan 18, 2025
85c4a52
Use 2 list/map elements in the test fixture
thockin Jan 20, 2025
3e5ee73
Make tests for slices more robust and regular
thockin Jan 20, 2025
c849967
Make tests for maps more robust and regular
thockin Jan 20, 2025
721f3e5
Move IsDNS1123Subdomain() to pkg content
thockin Jan 21, 2025
3a16430
Move IsQualifiedName() to pkg content
thockin Jan 21, 2025
b3b4616
Move IsLabelValue() to pkg content
thockin Jan 21, 2025
a0127e7
Add +immutable as a regular tag
thockin Jan 14, 2025
81d0268
Make tests for list-maps more robust and regular
thockin Jan 21, 2025
d3ab2a2
Fix double-validation for aliases to slices/maps
thockin Jan 20, 2025
38a7290
Make +eachVal a regular tag
thockin Jan 15, 2025
43c1369
Add tag tests for +eachVal for lists
thockin Jan 28, 2025
78d9ba0
Regenerate
thockin Jan 28, 2025
645b233
Add tag tests for +eachVal for maps
thockin Jan 28, 2025
36b33be
Regenerate
thockin Jan 28, 2025
adfa4f4
Add tag tests for +eachVal for list-maps
thockin Jan 28, 2025
13d7ea9
Regenerate
thockin Jan 28, 2025
0af2f09
Make +eachKey a regular tag
thockin Jan 11, 2025
eee05be
Add tag tests for +eachKey for maps
thockin Jan 28, 2025
ed4df73
Regenerate
thockin Jan 28, 2025
00af5b3
Make +subfield a regular tag
thockin Jan 10, 2025
05130d9
Add tag tests for +subfield
thockin Jan 28, 2025
6390280
Regenerate
thockin Jan 28, 2025
7e8f2b5
Clean up old eachKey code
thockin Jan 28, 2025
8a87a9b
Regenerate
thockin Jan 28, 2025
a7d8fea
Clean up old eachVal code
thockin Jan 28, 2025
9b5dd66
Regenerate
thockin Jan 28, 2025
248a975
Clean up old subfield code
thockin Jan 28, 2025
6bf363a
Test scheme: update args in the wrong order
thockin Feb 4, 2025
5f46c07
Fix non-tag list & map iteration, clean up listmap
thockin Jan 18, 2025
6ca9e0e
Get rid of forEachField, simpler
thockin Jan 28, 2025
19216b2
Clean up tag name consts
thockin Jan 28, 2025
2a39408
If WrapperFunction has no args, just call the func
thockin Jan 28, 2025
45c00a6
Fix lint to use proper +default tag
thockin Jan 29, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ require (
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/gengo/v2 v2.0.0-20250106234829-0359904fc2a6 // indirect
k8s.io/gengo/v2 v2.0.0-20250207200755-1244d31929d7 // indirect
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.1 // indirect
sigs.k8s.io/json v0.0.0-20241010143419-9aa6b5e7a4b3 // indirect
sigs.k8s.io/kustomize/api v0.18.0 // indirect
Expand Down
168 changes: 166 additions & 2 deletions go.sum

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion staging/src/k8s.io/apiextensions-apiserver/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ require (
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/gengo/v2 v2.0.0-20250106234829-0359904fc2a6 // indirect
k8s.io/gengo/v2 v2.0.0-20250207200755-1244d31929d7 // indirect
k8s.io/kms v0.0.0 // indirect
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.1 // indirect
)
Expand Down
4 changes: 2 additions & 2 deletions staging/src/k8s.io/apiextensions-apiserver/go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 0 additions & 44 deletions staging/src/k8s.io/apimachinery/pkg/api/safe/safe.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,47 +76,3 @@ func Cast[T any](value any) T {
result, _ := value.(T)
return result
}

// NewListMap creates a ListMap from the given elements and keyer.
func NewListMap[T any, K comparable](elements []T, keyer func(v *T) K) *ListMap[T, K] {
if len(elements) == 0 { // optimize for empty maps since this is a common case
return nil
}
keyed := map[K]*T{}
for i := range elements {
e := &elements[i]
keyed[keyer(e)] = e
}
return &ListMap[T, K]{Map: keyed, Keyer: keyer}
}

// ListMap provides map access to a slice where each element in the slice
// has a key that can be computed from the element by the provided keyer function.
type ListMap[T any, K comparable] struct {
Map map[K]*T
Keyer func(v *T) K
}

// Get returns the element in the ListMap matching the key, or nil if there is no matching element.
func (lm *ListMap[T, K]) Get(key K) *T {
if lm == nil {
return nil
}
if v, ok := lm.Map[key]; ok {
return v
}
return nil
}

// WithMatchingKey finds the element in the ListMap with the same key and returns it,
// or returns nil if no matching element was found.
func (lm *ListMap[T, K]) WithMatchingKey(value T) *T {
if lm == nil {
return nil
}
k := lm.Keyer(&value)
if v, ok := lm.Map[k]; ok {
return v
}
return nil
}
26 changes: 26 additions & 0 deletions staging/src/k8s.io/apimachinery/pkg/api/validate/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
Copyright 2024 The Kubernetes 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 validate

import (
"k8s.io/apimachinery/pkg/api/operation"
"k8s.io/apimachinery/pkg/util/validation/field"
)

// ValidateFunc is a function that validates a value, possibly considering the
// old value (if any).
type ValidateFunc[T any] func(opCtx operation.Context, fldPath *field.Path, newValue, oldValue T) field.ErrorList
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ but they should still use a slice return type.

Good validation failure messages follow the Kubernetes API conventions, for
example using "must" instead of "should".

This package should have almost no external dependecies (except stdlib).
102 changes: 82 additions & 20 deletions staging/src/k8s.io/apimachinery/pkg/api/validate/content/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package content

import (
"regexp"
"strings"
"unicode"
)

Expand All @@ -32,37 +33,98 @@ const DNS1123LabelMaxLength int = dns1123LabelMaxLength

var dnsLabelRegexp = regexp.MustCompile("^" + dns1123LabelInteriorFmt + "$")

// IsDNS1123Label returns error messages if the specified value does not
// parse as per the definition of a label in DNS (approximately RFC 1123).
// IsDNS1123Label returns error messages if the specified value is not
// a valid DNS "label" (approximately RFC 1123).
func IsDNS1123Label(value string) []string {
var errs []string
if len(value) > dns1123LabelMaxLength {
errs = append(errs, MaxLenError(dns1123LabelMaxLength))
return errs // Don't run further validation if we know it is too long.
}
if len(value) == 0 {
errs = append(errs, "must contain at least 1 character")
return errs // No point in going further.
// Don't run further validation if we know it is too long.
return []string{MaxLenError(dns1123LabelMaxLength)}
}
return isDNS1123LabelExceptMaxLength(value)
}

isAlNum := func(r rune) bool {
if r > unicode.MaxASCII {
return false
}
if unicode.IsLetter(r) && unicode.IsLower(r) {
return true
}
if unicode.IsDigit(r) {
return true
}
func isAlNumLower(r rune) bool {
if r > unicode.MaxASCII {
return false
}
if unicode.IsLetter(r) && unicode.IsLower(r) {
return true
}
if unicode.IsDigit(r) {
return true
}
return false
}

// Due to historical reasons, we need to be able to validate the format of a
// label without checking the max length.
func isDNS1123LabelExceptMaxLength(value string) []string {
if len(value) == 0 {
// No point in going further.
return []string{EmptyError()}
}

var errs []string

runes := []rune(value)
if !isAlNum(runes[0]) || !isAlNum(runes[len(runes)-1]) {
if !isAlNumLower(runes[0]) || !isAlNumLower(runes[len(runes)-1]) {
errs = append(errs, "must start and end with lower-case alphanumeric characters")
}
if len(runes) > 2 && !dnsLabelRegexp.MatchString(string(runes[1:len(runes)-1])) {
errs = append(errs, "must contain only lower-case alphanumeric characters or '-'")
}
return errs
}

const dns1123SubdomainMaxLength int = 253

// DNS1123SubdomainMaxLength is a DNS subdomain's max length (RFC 1123).
const DNS1123SubdomainMaxLength int = dns1123SubdomainMaxLength

// IsDNS1123Subdomain returns error messages if the specified value is not
// a valid DNS "subdomain" (approximately RFC 1123).
// subdomain in DNS (RFC 1123).
func IsDNS1123Subdomain(value string) []string {
if len(value) > DNS1123SubdomainMaxLength {
// Don't run further validation if we know it is too long.
return []string{MaxLenError(dns1123SubdomainMaxLength)}
}
if len(value) == 0 {
// No point in going further.
return []string{EmptyError()}
}

var errs []string

trimmed := strings.Trim(value, ".")
if trimmed != value {
errs = append(errs, "must start and end with lower-case alphanumeric characters")
}

value = strings.Trim(value, ".")
if len(value) > 0 {
parts := strings.Split(value, ".")
for _, part := range parts {
if msgs := isDNS1123LabelExceptMaxLength(part); len(msgs) > 0 {
// We don't need duplicate errors, but each part might have
// different errors. Making a set for such little data is expensive.
for _, msg := range msgs {
msg := "each part " + msg
if !msgExists(errs, msg) {
errs = append(errs, msg)
}
}
}
}
}
return errs
}

func msgExists(haystack []string, needle string) bool {
for _, msg := range haystack {
if msg == needle {
return true
}
}
return false
}
131 changes: 131 additions & 0 deletions staging/src/k8s.io/apimachinery/pkg/api/validate/content/dns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,134 @@ func TestIsDNS1123Label(t *testing.T) {
testVerify(t, i, tc.input, tc.expect, result)
}
}

func TestIsDNS1123Subdomain(t *testing.T) {
// errors expected
const minSizeError = "must contain at least 1 character"
const partMinSizeError = "each part must contain at least 1 character"
const maxSizeError = "must be no more than 253 characters"
const startEndError = "must start and end with lower-case alphanumeric characters"
const partStartEndError = "each part must start and end with lower-case alphanumeric characters"
const partInteriorError = "each part must contain only lower-case alphanumeric characters or '-'"

cases := []struct {
input string
expect []string // regexes
}{
// Good values
{"a", nil},
{"ab", nil},
{"abc", nil},
{"a1", nil},
{"a-1", nil},
{"a--1--2--b", nil},
{"0", nil},
{"01", nil},
{"012", nil},
{"1a", nil},
{"1-a", nil},
{"1--a--b--2", nil},
{strings.Repeat("a", 63), nil},
{strings.Repeat("a", 64), nil}, // allowed for backwards compat
{strings.Repeat("a", 253), nil}, // allowed for backwards compat
{"a.a", nil},
{"ab.a", nil},
{"abc.a", nil},
{"a1.a", nil},
{"a-1.a", nil},
{"a--1--2--b.a", nil},
{"0.a", nil},
{"01.a", nil},
{"012.a", nil},
{"1a.a", nil},
{"1-a.a", nil},
{"1--a--b--2.a", nil},
{strings.Repeat("a", 63) + ".a", nil},
{strings.Repeat("a", 64) + ".a", nil}, // allowed for backwards compat
{strings.Repeat("a", 251) + ".a", nil}, // allowed for backwards compat
{"a.1", nil},
{"ab.1", nil},
{"abc.1", nil},
{"a1.1", nil},
{"a-1.1", nil},
{"a--1--2--b.1", nil},
{"0.1", nil},
{"01.1", nil},
{"012.1", nil},
{"1a.1", nil},
{"1-a.1", nil},
{"1--a--b--2.1", nil},
{strings.Repeat("a", 63) + ".1", nil},
{strings.Repeat("a", 64) + ".1", nil}, // allowed for backwards compat
{strings.Repeat("a", 251) + ".1", nil}, // allowed for backwards compat
{"a.b.c.d.e", nil},
{"aa.bb.cc.dd.ee", nil},
{"1.2.3.4.5", nil},
{"11.22.33.44.55", nil},
{strings.Repeat("a", 126) + "." + strings.Repeat("b", 126), nil},
{strings.Repeat("0", 126) + "." + strings.Repeat("1", 126), nil},
{strings.Repeat("0.", 126) + "0", nil},

// Bad values
{"", mkMsgs(minSizeError)},
{"A", mkMsgs(startEndError)},
{"ABC", mkMsgs(startEndError, partInteriorError)},
{"aBc", mkMsgs(partInteriorError)},
{"AbC", mkMsgs(startEndError)},
{"A1", mkMsgs(startEndError)},
{"A-1", mkMsgs(startEndError)},
{"1-A", mkMsgs(startEndError)},
{"-", mkMsgs(startEndError)},
{"a-", mkMsgs(startEndError)},
{"-a", mkMsgs(startEndError)},
{"1-", mkMsgs(startEndError)},
{"-1", mkMsgs(startEndError)},
{"_", mkMsgs(startEndError)},
{"a_", mkMsgs(startEndError)},
{"_a", mkMsgs(startEndError)},
{"a_b", mkMsgs(partInteriorError)},
{"1_", mkMsgs(startEndError)},
{"_1", mkMsgs(startEndError)},
{"1_2", mkMsgs(partInteriorError)},
{".", mkMsgs(startEndError)},
{"a.", mkMsgs(startEndError)},
{".a", mkMsgs(startEndError)},
{"1.", mkMsgs(startEndError)},
{".1", mkMsgs(startEndError)},
{"a..b", mkMsgs(partMinSizeError)},
{"0..1", mkMsgs(partMinSizeError)},
{" ", mkMsgs(startEndError)},
{"a ", mkMsgs(startEndError)},
{" a", mkMsgs(startEndError)},
{"a b", mkMsgs(partInteriorError)},
{"1 ", mkMsgs(startEndError)},
{" 1", mkMsgs(startEndError)},
{"1 2", mkMsgs(partInteriorError)},
{"A.b", mkMsgs(startEndError)},
{"aB.b", mkMsgs(partStartEndError)},
{"ab.A", mkMsgs(startEndError)},
{"A.0", mkMsgs(startEndError)},
{"0B.0", mkMsgs(partStartEndError)},
{"00.A", mkMsgs(startEndError)},
{"A.B.C.D.E", mkMsgs(startEndError)},
{"AA.BB.CC.DD.EE", mkMsgs(startEndError)},
{"a.B.c.d.e", mkMsgs(startEndError)},
{"aa.bB.cc.dd.ee", mkMsgs(startEndError)},
{"a@b", mkMsgs(partInteriorError)},
{"a,b", mkMsgs(partInteriorError)},
{"a_b", mkMsgs(partInteriorError)},
{"a;b", mkMsgs(partInteriorError)},
{"a:b", mkMsgs(partInteriorError)},
{`a%b`, mkMsgs(partInteriorError)},
{"a?b", mkMsgs(partInteriorError)},
{"a$b", mkMsgs(partInteriorError)},
{strings.Repeat("a", 254), mkMsgs(maxSizeError)},
{strings.Repeat("-", 254), mkMsgs(maxSizeError)},
{strings.Repeat(".", 254), mkMsgs(maxSizeError)},
}

for i, tc := range cases {
result := IsDNS1123Subdomain(tc.input)
testVerify(t, i, tc.input, tc.expect, result)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ import (
func MaxLenError(length int) string {
return fmt.Sprintf("must be no more than %d characters", length)
}

// EmptyError returns a string explanation of an "empty string" validation.
func EmptyError() string {
return "must contain at least 1 character"
}
Loading
Loading