Skip to content

Commit

Permalink
fix: correct race conditions
Browse files Browse the repository at this point in the history
Signed-off-by: Shiwei Zhang <[email protected]>
  • Loading branch information
shizhMSFT committed Mar 19, 2024
1 parent c4548d8 commit 3a355e2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
33 changes: 33 additions & 0 deletions internal/syncutil/oncefunc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package syncutil

import (
"sync"
"sync/atomic"
)

// OnceRetryOnError returns a function that invokes f only once if f returns
// nil. Otherwise, it retries on the next call.
func OnceRetryOnError(f func() error) func() error {
var done atomic.Bool
var lock sync.Mutex

return func() error {
// fast path
if done.Load() {
return nil
}

Check warning on line 18 in internal/syncutil/oncefunc.go

View check run for this annotation

Codecov / codecov/patch

internal/syncutil/oncefunc.go#L10-L18

Added lines #L10 - L18 were not covered by tests

// slow path
lock.Lock()
defer lock.Unlock()

if done.Load() {
return nil
}
if err := f(); err != nil {
return err
}
done.Store(true)
return nil

Check warning on line 31 in internal/syncutil/oncefunc.go

View check run for this annotation

Codecov / codecov/patch

internal/syncutil/oncefunc.go#L21-L31

Added lines #L21 - L31 were not covered by tests
}
}
10 changes: 3 additions & 7 deletions registry/remote/credentials/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ import (
"fmt"
"os"
"path/filepath"
"sync"

"oras.land/oras-go/v2/internal/syncutil"
"oras.land/oras-go/v2/registry/remote/auth"
"oras.land/oras-go/v2/registry/remote/credentials/internal/config"
)
Expand Down Expand Up @@ -107,18 +107,14 @@ func NewStore(configPath string, opts StoreOptions) (*DynamicStore, error) {
// no authentication configured, detect the default credentials store
ds.detectedCredsStore = getDefaultHelperSuffix()
}
var setCredsStore func() error
setCredsStore = func() error {
ds.setCredsStoreOnce = syncutil.OnceRetryOnError(func() error {
if ds.detectedCredsStore != "" {
if err := ds.config.SetCredentialsStore(ds.detectedCredsStore); err != nil {
// retry on next call
ds.setCredsStoreOnce = sync.OnceValue(setCredsStore)
return fmt.Errorf("failed to set credsStore: %w", err)
}

Check warning on line 114 in registry/remote/credentials/store.go

View check run for this annotation

Codecov / codecov/patch

registry/remote/credentials/store.go#L112-L114

Added lines #L112 - L114 were not covered by tests
}
return nil
}
ds.setCredsStoreOnce = sync.OnceValue(setCredsStore)
})
return ds, nil
}

Expand Down

0 comments on commit 3a355e2

Please sign in to comment.