Skip to content

Commit

Permalink
Breaking signature: Allow context propagation (but without cancel pro…
Browse files Browse the repository at this point in the history
…pagation) in all replaceFn call paths

This allows passing arbitrary context values such as tracing contexts into replaceFn, which should help distributed tracing ecosystem.
  • Loading branch information
motoki317 committed Mar 25, 2024
1 parent c24560d commit 4661a01
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
6 changes: 3 additions & 3 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ retry:
cl := &call[V]{}
cl.wg.Add(1)
c.calls[key] = cl
go c.set(context.Background(), cl, key) // Use empty context so as not to be cancelled by the original context
go c.set(context.WithoutCancel(ctx), cl, key)
}
c.stats.GraceHits++
c.mu.Unlock()
Expand Down Expand Up @@ -187,7 +187,7 @@ func (c *cache[K, V]) GetIfExists(key K) (v V, ok bool) {
}

// Notify instructs the cache to retrieve value for key if value does not exist or is stale, in a non-blocking manner.
func (c *cache[K, V]) Notify(key K) {
func (c *cache[K, V]) Notify(ctx context.Context, key K) {
// Record time as soon as Get is called *before acquiring the lock* - this maximizes the reuse of values
calledAt := monoTimeNow()
c.mu.Lock()
Expand All @@ -205,7 +205,7 @@ func (c *cache[K, V]) Notify(key K) {
cl := &call[V]{}
cl.wg.Add(1)
c.calls[key] = cl
go c.set(context.Background(), cl, key) // Use empty context so as not to be cancelled by the original context
go c.set(context.WithoutCancel(ctx), cl, key)
}
c.mu.Unlock()
}
Expand Down
4 changes: 2 additions & 2 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ func TestCache_Notify(t *testing.T) {
t0 := time.Now()

// Notify value retrieval - this should launch goroutine in background
cache.Notify("k1")
cache.Notify(context.Background(), "k1")
// Test that value is still not here
_, ok := cache.GetIfExists("k1")
assert.False(t, ok)
Expand All @@ -477,7 +477,7 @@ func TestCache_Notify(t *testing.T) {
assert.EqualValues(t, 1, cnt)

// t=750ms, notify once again - this should do *nothing*
cache.Notify("k1")
cache.Notify(context.Background(), "k1")

time.Sleep(750 * time.Millisecond)
// t=1500ms, assert that value was replaced only once
Expand Down

0 comments on commit 4661a01

Please sign in to comment.