Skip to content

Commit

Permalink
fix: fix data race of TelemetryInstances variable (#136)
Browse files Browse the repository at this point in the history
Co-authored-by: Maksym Kryvchun <[email protected]>
  • Loading branch information
jimmyjames and Kryvchun authored Oct 21, 2024
1 parent 60d2786 commit cae58d7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions telemetry/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package telemetry

import (
"context"
"sync"

"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/metric"
Expand Down Expand Up @@ -42,6 +43,9 @@ type QueryDurationMetricParameters struct {
type TelemetryContextKey struct{}

var (
telemetryInstancesLock sync.Mutex
// Warning: do not use directly, it may cause data race.
// Deprecated: this map will be renamed to telemetryInstances.
TelemetryInstances map[*Configuration]*Telemetry
TelemetryContext TelemetryContextKey
)
Expand All @@ -65,6 +69,9 @@ func Get(factory TelemetryFactoryParameters) *Telemetry {
configuration = DefaultTelemetryConfiguration()
}

telemetryInstancesLock.Lock()
defer telemetryInstancesLock.Unlock()

if TelemetryInstances == nil {
TelemetryInstances = make(map[*Configuration]*Telemetry)
}
Expand Down
22 changes: 22 additions & 0 deletions telemetry/telemetry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package telemetry
import (
"context"
"net/http"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -225,3 +226,24 @@ func TestBuildTelemetryAttributesMethod(t *testing.T) {
t.Fatalf("Expected requestDuration to be 100, but got %v", requestDuration)
}
}

// Run this test with the "-race" flag.
//
// go test -race -run ^TestGetRace$ github.com/openfga/go-sdk/telemetry
func TestGetRace(t *testing.T) {
t.Parallel()

var wg sync.WaitGroup

for i := 0; i < 10; i++ {
wg.Add(1)

go func() {
defer wg.Done()

Get(TelemetryFactoryParameters{})
}()
}

wg.Wait()
}

0 comments on commit cae58d7

Please sign in to comment.