Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: henrywhitaker3/flow
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v1.8.1
Choose a base ref
...
head repository: henrywhitaker3/flow
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: v1.8.2
Choose a head ref
  • 1 commit
  • 2 files changed
  • 1 contributor

Commits on Jul 31, 2024

  1. fix: use time.After instead of timer

    henrywhitaker3 committed Jul 31, 2024
    Copy the full SHA
    5dba4d2 View commit details
Showing with 23 additions and 10 deletions.
  1. +10 −10 expiring_store.go
  2. +13 −0 expiring_store_test.go
20 changes: 10 additions & 10 deletions expiring_store.go
Original file line number Diff line number Diff line change
@@ -46,29 +46,29 @@ type ExpiryCallbacks[T any] func(key string, val T)

func (e *ExpiringStore[T]) Put(id string, val T, exp time.Duration, callbacks ...ExpiryCallbacks[T]) {
e.store.Put(id, val)
e.expireAfter(id, val, exp, callbacks...)
}

func (e *ExpiringStore[T]) expireAfter(id string, val T, exp time.Duration, callbacks ...ExpiryCallbacks[T]) {
e.waits.Add(1)

cancel := make(chan struct{}, 1)
e.cancelMutex.Lock()
e.cancel[id] = cancel
e.cancelMutex.Unlock()

go func() {
defer e.waits.Done()
timer := time.NewTimer(exp)
defer timer.Stop()
select {
case <-e.Closed():
return
case <-cancel:
return
case <-timer.C:
item, ok := e.Get(id)
if ok {
e.store.Delete(id)
for _, cb := range callbacks {
cb(id, item)
}
case <-time.After(exp):
for _, cb := range callbacks {
cb(id, val)
}
return
e.store.Delete(id)
}
}()
}
13 changes: 13 additions & 0 deletions expiring_store_test.go
Original file line number Diff line number Diff line change
@@ -41,3 +41,16 @@ func TestItCallsCallbacksWhenExpiringAnItem(t *testing.T) {
store.Close()
require.True(t, called)
}

func TestItDoesntBlockWhenDeleting(t *testing.T) {
store := flow.NewExpiringStore[string]()
word := "ahkhge"
called := false
store.Put("bongo", word, time.Millisecond, func(key string, val string) {
require.Equal(t, word, val)
called = true
})
store.Delete("bongo")
store.Close()
require.False(t, called)
}