chore: refactor (#5068)

This commit is contained in:
Kevin Wan
2025-08-08 23:30:03 +08:00
committed by GitHub
parent b46d507a1d
commit a2b98dbcf7
2 changed files with 11 additions and 8 deletions

View File

@@ -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.

View File

@@ -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])
}
}