Skip to content

Commit 16382a6

Browse files
committed
refactor: compile regex in validation method on the first use
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 <andrey.smirnov@siderolabs.com> (cherry picked from commit e1b2886)
1 parent f0364d2 commit 16382a6

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

pkg/machinery/config/types/v1alpha1/v1alpha1_validation.go

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"regexp"
1616
"strconv"
1717
"strings"
18+
"sync"
1819

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

311-
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})*[\._]?$`)
312+
// onceValue is a straight copy from Go 1.21, change to sync.OnceValue once upgraded to Go 1.21.
313+
func onceValue[T any](f func() T) func() T {
314+
var (
315+
once sync.Once
316+
valid bool
317+
p any
318+
result T
319+
)
320+
321+
g := func() {
322+
defer func() {
323+
p = recover()
324+
325+
if !valid {
326+
panic(p)
327+
}
328+
}()
329+
330+
result = f()
331+
valid = true
332+
}
333+
334+
return func() T {
335+
once.Do(g)
336+
337+
if !valid {
338+
panic(p)
339+
}
340+
341+
return result
342+
}
343+
}
344+
345+
var rxDNSNameRegexp = onceValue(func() *regexp.Regexp {
346+
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})*[\._]?$`)
347+
})
312348

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

318-
return rxDNSName.MatchString(name)
354+
return rxDNSNameRegexp().MatchString(name)
319355
}
320356

321357
// Validate validates the config.

0 commit comments

Comments
 (0)