-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathuuid.go
72 lines (62 loc) · 1.91 KB
/
uuid.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package appinsights
import (
crand "crypto/rand"
"encoding/binary"
"io"
"math/rand"
"sync"
"time"
"github.com/gofrs/uuid"
)
// uuidGenerator is a wrapper for gofrs/uuid, an active fork of satori/go.uuid used for a few reasons:
// - Avoids build failures due to version differences when a project imports us but
// does not respect our vendoring. (satori/go.uuid#77, #71, #66, ...)
// - Avoids error output when creaing new UUID's: if the crypto reader fails,
// this will fallback on the standard library PRNG, since this is never used
// for a sensitive application.
// - Uses io.ReadFull to guarantee fully-populated UUID's (satori/go.uuid#73)
type uuidGenerator struct {
sync.Mutex
fallbackRand *rand.Rand
reader io.Reader
}
var uuidgen *uuidGenerator = newUuidGenerator(crand.Reader)
// newUuidGenerator creates a new uuiGenerator with the specified crypto random reader.
func newUuidGenerator(reader io.Reader) *uuidGenerator {
// Setup seed for fallback random generator
var seed int64
b := make([]byte, 8)
if _, err := io.ReadFull(reader, b); err == nil {
seed = int64(binary.BigEndian.Uint64(b))
} else {
// Otherwise just use the timestamp
seed = time.Now().UTC().UnixNano()
}
return &uuidGenerator{
reader: reader,
fallbackRand: rand.New(rand.NewSource(seed)),
}
}
// newUUID generates a new V4 UUID
func (gen *uuidGenerator) newUUID() uuid.UUID {
//call the standard generator
u, err := uuid.NewV4()
//err will be either EOF or unexpected EOF
if err != nil {
gen.fallback(&u)
}
return u
}
// fallback populates the specified UUID with the standard library's PRNG
func (gen *uuidGenerator) fallback(u *uuid.UUID) {
gen.Lock()
defer gen.Unlock()
// This does not fail as per documentation
gen.fallbackRand.Read(u[:])
u.SetVersion(uuid.V4)
u.SetVariant(uuid.VariantRFC4122)
}
// newUUID generates a new V4 UUID
func newUUID() uuid.UUID {
return uuidgen.newUUID()
}