fix: replace moby/moby namesgenerator with internal implementation (#21377)

Replace the external moby/moby/pkg/namesgenerator dependency with an
internal implementation using gofakeit/v7. The moby package has ~25k
unique name combinations, and with its retry parameter only adds a
random digit 0-9, giving ~250k possibilities. In parallel tests, this
has led to collisions (flakes).

The new internal API at coderd/util/namesgenerator eliminates the
external dependnecy and offers functions with explicit uniqueness
guarantees. This PR also consolidates fragmented name generation in a
few places to use the new package.

| Old (moby/moby)                     | New                    |
|-------------------------------------|------------------------|
| namesgenerator.GetRandomName(0)     | NameWith("_")          |
| namesgenerator.GetRandomName(>0)    | NameDigitWith("_")     |
| testutil.GetRandomName(t)           | UniqueName()           |
| testutil.GetRandomNameHyphenated(t) | UniqueNameWith("-")    |

namesgenerator package API:
- NameWith(delim): random name, not unique
- NameDigitWith(delim): random name with 1-9 suffix, not unique
- UniqueName(): guaranteed unique via atomic counter
- UniqueNameWith(delim): unique with custom delimiter

Names continue to be docker style `[adjective][delim][surname]`. Unique
names are truncated to 32 characters (preserving the numeric suffix) to
fit common name length limits in Coder.

Related test flakes:
https://github.com/coder/internal/issues/1212
https://github.com/coder/internal/issues/118
https://github.com/coder/internal/issues/1068
This commit is contained in:
Zach
2026-01-09 15:40:26 -07:00
committed by GitHub
parent 1bfd776cb4
commit 091d31224d
18 changed files with 250 additions and 149 deletions
@@ -0,0 +1,82 @@
// Package namesgenerator generates random names.
//
// This package provides functions for generating random names in the format
// "adjective_surname" with various options for delimiters and uniqueness.
//
// For identifiers that must be unique within a process, use UniqueName or
// UniqueNameWith. For display purposes where uniqueness is not required,
// use NameWith.
package namesgenerator
import (
"math/rand/v2"
"strconv"
"strings"
"sync/atomic"
"github.com/brianvoe/gofakeit/v7"
)
// maxNameLen is the maximum length for names. Many places in Coder have a 32
// character limit for names (e.g. usernames, workspace names).
const maxNameLen = 32
// counter provides unique suffixes for UniqueName functions.
var counter atomic.Int64
// NameWith returns a random name with a custom delimiter.
// Names are not guaranteed to be unique.
func NameWith(delim string) string {
const seed = 0 // gofakeit will use a random crypto seed.
faker := gofakeit.New(seed)
adjective := strings.ToLower(faker.AdjectiveDescriptive())
last := strings.ToLower(faker.LastName())
return adjective + delim + last
}
// NameDigitWith returns a random name with a single random digit suffix (1-9),
// in the format "[adjective][delim][surname][digit]" e.g. "happy_smith9".
// Provides some collision resistance while keeping names short and clean.
// Not guaranteed to be unique.
func NameDigitWith(delim string) string {
const (
minDigit = 1
maxDigit = 9
)
//nolint:gosec // The random digit doesn't need to be cryptographically secure.
return NameWith(delim) + strconv.Itoa(rand.IntN(maxDigit-minDigit+1))
}
// UniqueName returns a random name with a monotonically increasing suffix,
// guaranteeing uniqueness within the process. The name is truncated to 32
// characters if necessary, preserving the numeric suffix.
func UniqueName() string {
return UniqueNameWith("_")
}
// UniqueNameWith returns a unique name with a custom delimiter.
// See UniqueName for details on uniqueness guarantees.
func UniqueNameWith(delim string) string {
name := NameWith(delim) + strconv.FormatInt(counter.Add(1), 10)
return truncate(name, maxNameLen)
}
// truncate truncates a name to maxLen characters. It assumes the name ends with
// a numeric suffix and preserves it, truncating the base name portion instead.
func truncate(name string, maxLen int) string {
if len(name) <= maxLen {
return name
}
// Find where the numeric suffix starts.
suffixStart := len(name)
for suffixStart > 0 && name[suffixStart-1] >= '0' && name[suffixStart-1] <= '9' {
suffixStart--
}
base := name[:suffixStart]
suffix := name[suffixStart:]
truncateAt := maxLen - len(suffix)
if truncateAt <= 0 {
return strconv.Itoa(maxLen) // Fallback, shouldn't happen in practice.
}
return base[:truncateAt] + suffix
}
@@ -0,0 +1,103 @@
package namesgenerator
import (
"strings"
"testing"
"unicode"
"github.com/stretchr/testify/assert"
)
func TestTruncate(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input string
maxLen int
want string
}{
{
name: "no truncation needed",
input: "foo1",
maxLen: 10,
want: "foo1",
},
{
name: "exact fit",
input: "foo1",
maxLen: 4,
want: "foo1",
},
{
name: "truncate base",
input: "foobar42",
maxLen: 5,
want: "foo42",
},
{
name: "truncate more",
input: "foobar3",
maxLen: 3,
want: "fo3",
},
{
name: "long suffix",
input: "foo123456",
maxLen: 8,
want: "fo123456",
},
{
name: "realistic name",
input: "condescending_proskuriakova999999",
maxLen: 32,
want: "condescending_proskuriakov999999",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := truncate(tt.input, tt.maxLen)
assert.Equal(t, tt.want, got)
assert.LessOrEqual(t, len(got), tt.maxLen)
})
}
}
func TestUniqueNameLength(t *testing.T) {
t.Parallel()
// Generate many names to exercise the truncation logic.
const iter = 10000
for range iter {
name := UniqueName()
assert.LessOrEqual(t, len(name), maxNameLen)
assert.Contains(t, name, "_")
assert.Equal(t, name, strings.ToLower(name))
verifyNoWhitespace(t, name)
}
}
func TestUniqueNameWithLength(t *testing.T) {
t.Parallel()
// Generate many names with hyphen delimiter.
const iter = 10000
for range iter {
name := UniqueNameWith("-")
assert.LessOrEqual(t, len(name), maxNameLen)
assert.Contains(t, name, "-")
assert.Equal(t, name, strings.ToLower(name))
verifyNoWhitespace(t, name)
}
}
func verifyNoWhitespace(t *testing.T, s string) {
t.Helper()
for _, r := range s {
if unicode.IsSpace(r) {
t.Fatalf("found whitespace in string %q: %v", s, r)
}
}
}