File: generator.go

package info (click to toggle)
golang-gitlab-gitlab-org-labkit 1.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,092 kB
  • sloc: sh: 210; javascript: 49; makefile: 4
file content (62 lines) | stat: -rw-r--r-- 1,929 bytes parent folder | download | duplicates (4)
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
package correlation

import (
	"crypto/rand"
	"io"
	"sync"
	"time"

	"github.com/oklog/ulid/v2"
)

// Replaceable for testing purposes.
var ulidEntropySource io.Reader = &safeMonotonicReader{
	delegate: ulid.Monotonic(rand.Reader, 0),
}

func generatePseudorandomCorrelationID() string {
	return "E:" + encodeReverseBase62(time.Now().UnixNano())
}

// generateRandomCorrelationID will attempt to generate a correlationid randomly
// if this fails, will log a message and fallback to a pseudorandom approach.
func generateRandomCorrelationIDWithFallback() string {
	uid, err := ulid.New(ulid.Timestamp(time.Now()), ulidEntropySource)
	if err != nil {
		// Swallow the error and return a pseudorandom correlation_id.
		// Operators can determine that an error occurred by the shape of the
		// correlation_id, which will be prefixed with a `E:`
		return generatePseudorandomCorrelationID()
	}

	return uid.String()
}

// RandomID generates a random correlation ID.
// Deprecated: use SafeRandomID instead.
// Note, that this method will not return an error, it is here for compatibility reasons only.
func RandomID() (string, error) { return generateRandomCorrelationIDWithFallback(), nil }

// SafeRandomID generates a random correlation ID.
func SafeRandomID() string { return generateRandomCorrelationIDWithFallback() }

// safeMonotonicReader is a thread-safe wrapper around a ulid.Monotonic instance, which is not safe for concurrent use by itself.
// See https://godoc.org/github.com/oklog/ulid#Monotonic.
type safeMonotonicReader struct {
	mtx      sync.Mutex
	delegate ulid.MonotonicReader
}

var _ ulid.MonotonicReader = &safeMonotonicReader{}

func (r *safeMonotonicReader) MonotonicRead(ms uint64, p []byte) error {
	r.mtx.Lock()
	defer r.mtx.Unlock()
	return r.delegate.MonotonicRead(ms, p)
}

func (r *safeMonotonicReader) Read(p []byte) (int, error) {
	r.mtx.Lock()
	defer r.mtx.Unlock()
	return r.delegate.Read(p)
}