Skip to content

Commit

Permalink
refactor: compile regex in validation method on the first use
Browse files Browse the repository at this point in the history
See #7578

With this change and #7590, init allocation:

```
init github.com/siderolabs/talos/pkg/machinery/config/types/v1alpha1 @2.1 ms, 0.006 ms clock, 1408 bytes, 26 allocs
```

Previously, it was:

```
init github.com/siderolabs/talos/pkg/machinery/config/types/v1alpha1 @3.8 ms, 0.30 ms clock, 184248 bytes, 1176 allocs
```

Signed-off-by: Andrey Smirnov <[email protected]>
  • Loading branch information
smira committed Aug 9, 2023
1 parent daa4c18 commit e1b2886
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions pkg/machinery/config/types/v1alpha1/v1alpha1_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"regexp"
"strconv"
"strings"
"sync"

"github.com/hashicorp/go-multierror"
sideronet "github.com/siderolabs/net"
Expand Down Expand Up @@ -308,14 +309,49 @@ func (c *Config) Validate(mode validation.RuntimeMode, options ...validation.Opt
return warnings, result.ErrorOrNil()
}

var rxDNSName = regexp.MustCompile(`^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`)
// onceValue is a straight copy from Go 1.21, change to sync.OnceValue once upgraded to Go 1.21.
func onceValue[T any](f func() T) func() T {
var (
once sync.Once
valid bool
p any
result T
)

g := func() {
defer func() {
p = recover()

if !valid {
panic(p)
}
}()

result = f()
valid = true
}

return func() T {
once.Do(g)

if !valid {
panic(p)
}

return result
}
}

var rxDNSNameRegexp = onceValue(func() *regexp.Regexp {
return regexp.MustCompile(`^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`)
})

func isValidDNSName(name string) bool {
if name == "" || len(name)-strings.Count(name, ".") > 255 {
return false
}

return rxDNSName.MatchString(name)
return rxDNSNameRegexp().MatchString(name)
}

// Validate validates the config.
Expand Down

0 comments on commit e1b2886

Please sign in to comment.