-
Notifications
You must be signed in to change notification settings - Fork 508
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #448 from TarsCloud/per/traceid_spanid
perf(trace): optimize traceId and spanId generation
- Loading branch information
Showing
4 changed files
with
56 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package trace | ||
|
||
import ( | ||
crand "crypto/rand" | ||
"encoding/binary" | ||
"encoding/hex" | ||
"math/rand" | ||
"sync" | ||
) | ||
|
||
type randomIDGenerator struct { | ||
sync.Mutex | ||
randSource *rand.Rand | ||
} | ||
|
||
func newGenerator() *randomIDGenerator { | ||
var rngSeed int64 | ||
_ = binary.Read(crand.Reader, binary.LittleEndian, &rngSeed) | ||
return &randomIDGenerator{randSource: rand.New(rand.NewSource(rngSeed))} | ||
} | ||
|
||
// NewSpanID returns a non-zero span ID from a randomly-chosen sequence. | ||
func (gen *randomIDGenerator) NewSpanID() string { | ||
gen.Lock() | ||
defer gen.Unlock() | ||
sid := [8]byte{} | ||
_, _ = gen.randSource.Read(sid[:]) | ||
return hex.EncodeToString(sid[:]) | ||
} | ||
|
||
// NewTraceID returns a non-zero trace ID from a randomly-chosen sequence. | ||
func (gen *randomIDGenerator) NewTraceID() string { | ||
gen.Lock() | ||
defer gen.Unlock() | ||
tid := [16]byte{} | ||
_, _ = gen.randSource.Read(tid[:]) | ||
return hex.EncodeToString(tid[:]) | ||
} | ||
|
||
// NewIDs returns a non-zero trace ID and a non-zero span ID from a | ||
// randomly-chosen sequence. | ||
func (gen *randomIDGenerator) NewIDs() (string, string) { | ||
gen.Lock() | ||
defer gen.Unlock() | ||
tid := [16]byte{} | ||
_, _ = gen.randSource.Read(tid[:]) | ||
sid := [8]byte{} | ||
_, _ = gen.randSource.Read(sid[:]) | ||
return hex.EncodeToString(tid[:]), hex.EncodeToString(sid[:]) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters