Skip to content

Commit f3a30fb

Browse files
fix: Cleanup stale map in a background goroutine. (#1)
Instead of iterating over map every call to Translate(), we should cleanup all spans in a background thread outside of the hotpath.
1 parent 2af1d50 commit f3a30fb

File tree

1 file changed

+29
-12
lines changed

1 file changed

+29
-12
lines changed

internal/translator/translator.go

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,47 @@ type Translator struct {
1919
mu sync.RWMutex
2020
span2trace map[string]spanEntry
2121
ttl time.Duration
22+
stop chan struct{}
2223
}
2324

2425
func NewTranslator() *Translator {
25-
return &Translator{
26+
t := &Translator{
2627
span2trace: make(map[string]spanEntry),
2728
ttl: 5 * time.Minute,
29+
stop: make(chan struct{}),
2830
}
31+
if t.ttl > 0 {
32+
go t.clean()
33+
}
34+
return t
2935
}
3036

31-
// Translate converts every OTLP span in the request to a Run slice.
32-
func (t *Translator) Translate(req *collectortracepb.ExportTraceServiceRequest) []*model.Run {
33-
total := 0
34-
// gc stale aliases first
35-
if t.ttl > 0 {
36-
cutoff := time.Now().Add(-t.ttl)
37-
t.mu.Lock()
38-
for k, v := range t.span2trace {
39-
if v.ts.Before(cutoff) {
40-
delete(t.span2trace, k)
37+
func (t *Translator) clean() {
38+
ticker := time.NewTicker(t.ttl / 2)
39+
defer ticker.Stop()
40+
for {
41+
select {
42+
case <-ticker.C:
43+
cutoff := time.Now().Add(-t.ttl)
44+
t.mu.Lock()
45+
for k, v := range t.span2trace {
46+
if v.ts.Before(cutoff) {
47+
delete(t.span2trace, k)
48+
}
4149
}
50+
t.mu.Unlock()
51+
case <-t.stop:
52+
return
4253
}
43-
t.mu.Unlock()
4454
}
55+
}
56+
57+
func (t *Translator) Close() { close(t.stop) }
4558

59+
// Translate converts every OTLP span in the request to a Run slice.
60+
// Creating a new one spins up a new goroutine to clean up stale aliases.
61+
func (t *Translator) Translate(req *collectortracepb.ExportTraceServiceRequest) []*model.Run {
62+
total := 0
4663
// count total spans
4764
for _, rs := range req.ResourceSpans {
4865
for _, ss := range rs.ScopeSpans {

0 commit comments

Comments
 (0)