sdk-golang icon indicating copy to clipboard operation
sdk-golang copied to clipboard

Fix data race when creating context

Open barweiss opened this issue 1 month ago • 0 comments

There's a data race that exists when creating Ziti contexts:

==================
WARNING: DATA RACE
Read at 0x000104174c90 by goroutine 2003:
  github.com/openziti/sdk-golang/ziti.NewId()
      /Users/bar/go/pkg/mod/github.com/openziti/[email protected]/ziti/contexts.go:46 +0x60
  github.com/openziti/sdk-golang/ziti.NewContextWithOpts()
      /Users/bar/go/pkg/mod/github.com/openziti/[email protected]/ziti/contexts.go:85 +0x3e4
...

The issue is that NewId() increments a global counter without any synchronization:

var idCount = 0

// NewId will return a unique string id suitable for ziti.Context Id functionality.
func NewId() string {
	idCount = idCount + 1

	return strconv.Itoa(idCount)
}

An easy way to solve this can be to the atomic package

barweiss avatar Oct 27 '25 16:10 barweiss