github.com/safing/portbase@v0.19.5/utils/uuid.go (about) 1 package utils 2 3 import ( 4 "encoding/binary" 5 "time" 6 7 "github.com/gofrs/uuid" 8 ) 9 10 var ( 11 constantUUID = uuid.Must(uuid.FromString("e8dba9f7-21e2-4c82-96cb-6586922c6422")) 12 instanceUUID = RandomUUID("instance") 13 ) 14 15 // RandomUUID returns a new random UUID with optionally provided ns. 16 func RandomUUID(ns string) uuid.UUID { 17 randUUID, err := uuid.NewV4() 18 switch { 19 case err != nil: 20 // fallback 21 // should practically never happen 22 return uuid.NewV5(uuidFromTime(), ns) 23 case ns != "": 24 // mix ns into the UUID 25 return uuid.NewV5(randUUID, ns) 26 default: 27 return randUUID 28 } 29 } 30 31 // DerivedUUID returns a new UUID that is derived from the input only, and therefore is always reproducible. 32 func DerivedUUID(input string) uuid.UUID { 33 return uuid.NewV5(constantUUID, input) 34 } 35 36 // DerivedInstanceUUID returns a new UUID that is derived from the input, but is unique per instance (execution) and therefore is only reproducible with the same process. 37 func DerivedInstanceUUID(input string) uuid.UUID { 38 return uuid.NewV5(instanceUUID, input) 39 } 40 41 func uuidFromTime() uuid.UUID { 42 var timeUUID uuid.UUID 43 binary.LittleEndian.PutUint64(timeUUID[:], uint64(time.Now().UnixNano())) 44 return timeUUID 45 }