47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
// 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 (
|
|
"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
|
|
}
|
|
|
|
// 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
|
|
}
|