Skip to content

Commit 56773c5

Browse files
committed
add hash function to generate common guid
1 parent 1b7e38e commit 56773c5

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

utils/guid/id.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package guid
1717
import (
1818
"crypto/rand"
1919
"crypto/sha1"
20+
"crypto/sha256"
2021
"fmt"
2122
mrand "math/rand/v2"
2223
"os"
@@ -48,6 +49,7 @@ const (
4849
WHIPResourcePrefix = "WH_"
4950
RTMPResourcePrefix = "RT_"
5051
URLResourcePrefix = "UR_"
52+
AgentPrefix = "A_"
5153
AgentWorkerPrefix = "AW_"
5254
AgentJobPrefix = "AJ_"
5355
AgentDispatchPrefix = "AD_"
@@ -70,6 +72,11 @@ func New(prefix string) string {
7072
return g.New(prefix)
7173
}
7274

75+
func Hash(prefix string, data []byte) string {
76+
g := newGeneratorFromSeed(sha256.Sum256(data))
77+
return g.New(prefix)
78+
}
79+
7380
// HashedID creates a hashed ID from a unique string
7481
func HashedID(id string) string {
7582
h := sha1.New()
@@ -108,9 +115,13 @@ func newGenerator() (*guidGenerator, error) {
108115
return nil, err
109116
}
110117

118+
return newGeneratorFromSeed(seed), nil
119+
}
120+
121+
func newGeneratorFromSeed(seed [32]byte) *guidGenerator {
111122
return &guidGenerator{
112123
rng: mrand.NewChaCha8(seed),
113-
}, nil
124+
}
114125
}
115126

116127
func (g *guidGenerator) readIDChars(b []byte) {

utils/guid/id_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ func TestMarshalAppend(t *testing.T) {
4141
require.Equal(t, id1, Unmarshal[livekit.RoomID](livekit.GuidBlock(b[9:])))
4242
}
4343

44+
func TestHash(t *testing.T) {
45+
id := Hash(AgentPrefix, []byte("test"))
46+
require.Equal(t, "A_SFo4igEG5Dg5", id)
47+
}
48+
4449
func BenchmarkNew(b *testing.B) {
4550
b.Run("new", func(b *testing.B) {
4651
var guid string

0 commit comments

Comments
 (0)