Chore: Replace short UID generation with more standard UUIDs (#62731)

This commit is contained in:
Ryan McKinley
2023-02-06 20:44:37 -05:00
committed by GitHub
parent ee2e294b4e
commit b1e58eb47e
11 changed files with 64 additions and 84 deletions
+23 -9
View File
@@ -1,21 +1,22 @@
package util
import (
"math/rand"
"regexp"
"time"
"github.com/teris-io/shortid"
"github.com/google/uuid"
)
var allowedChars = shortid.DefaultABC
var uidrand = rand.New(rand.NewSource(time.Now().UnixNano()))
var alphaRunes = []rune("abcdefghijklmnopqrstuvwxyz")
var hexLetters = []rune("abcdef")
// Legacy UID pattern
var validUIDPattern = regexp.MustCompile(`^[a-zA-Z0-9\-\_]*$`).MatchString
func init() {
gen, _ := shortid.New(1, allowedChars, 1)
shortid.SetDefault(gen)
}
// IsValidShortUID checks if short unique identifier contains valid characters
// NOTE: future Grafana UIDs will need conform to https://github.com/kubernetes/apimachinery/blob/master/pkg/util/validation/validation.go#L43
func IsValidShortUID(uid string) bool {
return validUIDPattern(uid)
}
@@ -25,7 +26,20 @@ func IsShortUIDTooLong(uid string) bool {
return len(uid) > 40
}
// GenerateShortUID generates a short unique identifier.
// GenerateShortUID will generate a UUID that can also be a k8s name
// it is guaranteed to have a character as the first letter
// This UID will be a valid k8s name
func GenerateShortUID() string {
return shortid.MustGenerate()
uid, err := uuid.NewRandom()
if err != nil {
// This should never happen... but this seems better than a panic
for i := range uid {
uid[i] = byte(uidrand.Intn(255))
}
}
uuid := uid.String()
if rune(uuid[0]) < rune('a') {
return string(hexLetters[uidrand.Intn(len(hexLetters))]) + uuid[1:]
}
return uuid
}
+23 -2
View File
@@ -3,17 +3,38 @@ package util
import (
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/util/validation"
)
func TestAllowedCharMatchesUidPattern(t *testing.T) {
for _, c := range allowedChars {
for _, c := range alphaRunes {
if !IsValidShortUID(string(c)) {
t.Fatalf("charset for creating new shortids contains chars not present in uid pattern")
}
}
}
func TestRandomUIDs(t *testing.T) {
for i := 0; i < 100; i++ {
v := GenerateShortUID()
if !IsValidShortUID(v) {
t.Fatalf("charset for creating new shortids contains chars not present in uid pattern")
}
validation := validation.IsQualifiedName(v)
if validation != nil {
t.Fatalf("created invalid name: %v", validation)
}
_, err := uuid.Parse(v)
require.NoError(t, err)
//fmt.Println(v)
}
// t.FailNow()
}
func TestIsShortUIDTooLong(t *testing.T) {
var tests = []struct {
name string
@@ -22,7 +43,7 @@ func TestIsShortUIDTooLong(t *testing.T) {
}{
{
name: "when the length of uid is longer than 40 chars then IsShortUIDTooLong should return true",
uid: allowedChars,
uid: string(alphaRunes) + string(alphaRunes),
expected: true,
},
{