forked from zalando/skipper
/
ulid.go
58 lines (50 loc) · 1.66 KB
/
ulid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package flowid
import (
"github.com/oklog/ulid"
"io"
"math/rand"
"regexp"
"sync"
"time"
)
type ulidGenerator struct {
sync.Mutex
r io.Reader
}
var ulidFlowIDRegex = regexp.MustCompile(`^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$`)
// NewULIDGenerator returns a flow ID generator that is able to generate Universally Unique Lexicographically
// Sortable Identifier (ULID) flow IDs.
// It uses a shared, pseudo-random source of entropy, seeded with the current timestamp.
// It is safe for concurrent usage.
func NewULIDGenerator() Generator {
return NewULIDGeneratorWithEntropyProvider(rand.New(rand.NewSource(time.Now().UTC().UnixNano())))
}
// NewULIDGeneratorWithEntropyProvider behaves like NewULIDGenerator but allows you to specify your own source of
// entropy.
// Access to the entropy provider is safe for concurrent usage.
func NewULIDGeneratorWithEntropyProvider(r io.Reader) Generator {
return &ulidGenerator{r: r}
}
// Generate returns a random ULID flow ID or an empty string in case of failure. The returned error can be inspected
// to assess the failure reason
func (g *ulidGenerator) Generate() (string, error) {
g.Lock()
id, err := ulid.New(ulid.Now(), g.r)
g.Unlock()
if err != nil {
return "", err
}
return id.String(), nil
}
// MustGenerate behaves like Generate but panics in case of failure
func (g *ulidGenerator) MustGenerate() string {
flowId, err := g.Generate()
if err != nil {
panic(err)
}
return flowId
}
// IsValid checks if the given flowId follows the format of this generator
func (g *ulidGenerator) IsValid(flowId string) bool {
return len(flowId) >= MinLength && len(flowId) <= MaxLength && ulidFlowIDRegex.MatchString(flowId)
}