From a2b98dbcf7d74fae2d4167623c23a6fce2d3a532 Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Fri, 8 Aug 2025 23:30:03 +0800 Subject: [PATCH] chore: refactor (#5068) --- core/syncx/immutableresource.go | 3 +-- core/syncx/immutableresource_test.go | 16 ++++++++++------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/core/syncx/immutableresource.go b/core/syncx/immutableresource.go index 8b79a6ce5..e8fa364a3 100644 --- a/core/syncx/immutableresource.go +++ b/core/syncx/immutableresource.go @@ -70,9 +70,8 @@ func (ir *ImmutableResource) Get() (any, error) { } func (ir *ImmutableResource) shouldRefresh() bool { - now := timex.Now() lastTime := ir.lastTime.Load() - return lastTime == 0 || lastTime+ir.refreshInterval < now + return lastTime == 0 || lastTime+ir.refreshInterval < timex.Now() } // WithRefreshIntervalOnFailure sets refresh interval on failure. diff --git a/core/syncx/immutableresource_test.go b/core/syncx/immutableresource_test.go index 3405f4d3c..837957df5 100644 --- a/core/syncx/immutableresource_test.go +++ b/core/syncx/immutableresource_test.go @@ -58,20 +58,24 @@ func TestImmutableResourceError(t *testing.T) { assert.Equal(t, 2, count) } +// It's hard to test more than one goroutine fetching the resource at the same time, +// because it's difficult to make more than one goroutine to pass the first read lock +// and wait another to pass the read lock before it gets the write lock. func TestImmutableResourceConcurrent(t *testing.T) { + const message = "hello" var count int32 ready := make(chan struct{}) r := NewImmutableResource(func() (any, error) { atomic.AddInt32(&count, 1) close(ready) // signal that fetch started time.Sleep(10 * time.Millisecond) // simulate slow fetch - return "hello", nil + return message, nil }) - const goroutines = 100 + const goroutines = 10 var wg sync.WaitGroup results := make([]any, goroutines) - errors := make([]error, goroutines) + errs := make([]error, goroutines) wg.Add(goroutines) for i := 0; i < goroutines; i++ { @@ -79,7 +83,7 @@ func TestImmutableResourceConcurrent(t *testing.T) { defer wg.Done() res, err := r.Get() results[idx] = res - errors[idx] = err + errs[idx] = err }(i) } @@ -93,8 +97,8 @@ func TestImmutableResourceConcurrent(t *testing.T) { // all goroutines should eventually get the same result for i := 0; i < goroutines; i++ { - assert.Nil(t, errors[i]) - assert.Equal(t, "hello", results[i]) + assert.Nil(t, errs[i]) + assert.Equal(t, message, results[i]) } }