// Package ident generates and parses entity identifiers. // // Identifiers are UUIDv7 (RFC 9562): the first 48 bits carry a Unix // millisecond timestamp and google/uuid keeps them strictly increasing within // one process even when the system clock steps backwards, so lexicographic // order of ids equals creation order. package ident import ( "crypto/rand" "encoding/hex" "errors" "time" "github.com/google/uuid" ) var ErrInvalid = errors.New("invalid uuid") // New panics only if the platform random source is unavailable, which is a // fatal environment fault rather than a request error. func New() uuid.UUID { id, err := uuid.NewV7() if err != nil { panic("ident: random source unavailable: " + err.Error()) } return id } // NewAlias names one server process for X-Instance-Id; random rather than the // hostname, so the header reveals nothing about the infrastructure. func NewAlias() string { var raw [8]byte _, _ = rand.Read(raw[:]) // crypto/rand.Read never returns an error since Go 1.24. return hex.EncodeToString(raw[:]) } // TimeOf extracts the creation time carried by a UUIDv7 as UTC with // millisecond precision. func TimeOf(id uuid.UUID) time.Time { sec, nsec := id.Time().UnixTime() return time.Unix(sec, nsec).UTC() } // Parse accepts only the canonical 36-character form; uuid.Parse alone would // also take braces, urn prefixes and bare hex. func Parse(raw string) (uuid.UUID, error) { if len(raw) != 36 { return uuid.Nil, ErrInvalid } id, err := uuid.Parse(raw) if err != nil { return uuid.Nil, ErrInvalid } return id, nil }