feat(model): generate random ids as canonical 128-bit base62 values

This commit is contained in:
Deluan 2026-07-19 21:39:32 -04:00
parent c2c67e35eb
commit 38eb7c4b78
2 changed files with 18 additions and 8 deletions

View File

@ -2,20 +2,16 @@ package id
import (
"crypto/md5"
"crypto/rand"
"fmt"
"math/big"
"strings"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/utils/nanoid"
)
func NewRandom() string {
id, err := nanoid.Generate("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 22)
if err != nil {
log.Error("Could not generate new ID", err)
}
return id
var b [16]byte
_, _ = rand.Read(b[:]) // never fails since Go 1.24
return Encode128(b[:])
}
// Encode128 renders a 16-byte value as the canonical 22-char zero-padded base62 id.

View File

@ -34,6 +34,20 @@ var _ = Describe("Encode128/Decode128", func() {
})
})
var _ = Describe("NewRandom", func() {
It("emits 22-char canonical ids that always fit 128 bits", func() {
seen := make(map[string]struct{})
for range 1000 {
s := id.NewRandom()
Expect(s).To(HaveLen(22))
_, err := id.Decode128(s)
Expect(err).ToNot(HaveOccurred(), "id %q must decode to 128 bits", s)
seen[s] = struct{}{}
}
Expect(seen).To(HaveLen(1000))
})
})
var _ = Describe("NewHash", func() {
It("keeps its historical output byte-for-byte (golden)", func() {
Expect(id.NewHash("test")).To(Equal("5cLJPkLA5DK2BADhoeotPk"))