Data race on GCS/FTP/Azure storage adapter fields written by the background retry goroutine
Describe the bug
When the first connect fails, the GCS, FTP and Azure file stores start a background retry loop (go f.startRetryConnect() at file/gcs/fs.go:76, file/ftp/fs.go:97, file/azure/fs.go:84). The loop calls CommonFileSystem.Connect, which calls the provider's Connect, and that writes the adapter's client fields with no synchronization:
- GCS,
pkg/gofr/datasource/file/gcs/storage_adapter.go:112-113
s.client = client
s.bucket = bucket(and saEmail / saPrivateKey at :105-106)
- FTP,
pkg/gofr/datasource/file/ftp/storage_adapter.go:85:s.conn = conn - Azure,
pkg/gofr/datasource/file/azure/storage_adapter.go:102:s.shareClient = shareClient
Meanwhile the app keeps serving requests, and every file operation and the health check read the same fields from other goroutines (e.g. gcs Health at storage_adapter.go:137, StatObject at :255, ftp :96/:102, azure :109/:113).
This is the same class of race as #4314, but on the provider side. #4357 makes CommonFileSystem's connected/disableRetry flags safe and leaves these fields as they are. Making connected atomic doesn't fix it on its own, because the file operations don't go through IsConnected() before touching the adapter.
To Reproduce
The retry loop only ticks once a minute, so this test calls CommonFileSystem.Connect from a goroutine directly, the same way the loop does, against an httptest server that answers the bucket lookup:
func TestAdapterFieldRace(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"name":"bkt"}`))
}))
defer srv.Close()
fsys := New(&Config{EndPoint: srv.URL, BucketName: "bkt"}).(*fileSystem)
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); _ = fsys.CommonFileSystem.Connect(t.Context()) }() // retry goroutine
go func() {
defer wg.Done()
for i := 0; i < 200; i++ {
_ = fsys.adapter.Health(t.Context()) // health check / request goroutine
}
}()
wg.Wait()
}go test -race -run TestAdapterFieldRace ./pkg/gofr/datasource/file/gcs reports WARNING: DATA RACE with the write at storage_adapter.go:112 and the read at storage_adapter.go:137. FTP and Azure have the same pattern.
Expected behavior
The adapter state set up by Connect should be published safely to the goroutines that use it, e.g. guarded by a sync.RWMutex, or built into a small struct stored in an atomic.Pointer and loaded once per operation. That way readers see either "not connected" or a fully initialized client.
Additional context
Found while working on #4357 (fix for #4314), which lists this as a follow-up.
Source: gofr-dev/gofr