From cbda1e753c008a6963671bf9171b691efc202465 Mon Sep 17 00:00:00 2001 From: Amir Raminfar Date: Mon, 13 May 2024 15:32:51 -0700 Subject: [PATCH] chore: fixes race condition (#2959) --- internal/cache/expire.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/cache/expire.go b/internal/cache/expire.go index 7a2bda93..451061d7 100644 --- a/internal/cache/expire.go +++ b/internal/cache/expire.go @@ -1,6 +1,7 @@ package cache import ( + "sync" "time" log "github.com/sirupsen/logrus" @@ -11,6 +12,7 @@ type Cache[T any] struct { Timestamp time.Time Duration time.Duration Data T + mu sync.Mutex } func New[T any](f func() (T, error), duration time.Duration) *Cache[T] { @@ -21,6 +23,8 @@ func New[T any](f func() (T, error), duration time.Duration) *Cache[T] { } func (c *Cache[T]) GetWithHit() (T, error, bool) { + c.mu.Lock() + defer c.mu.Unlock() hit := true if c.Timestamp.IsZero() || time.Since(c.Timestamp) > c.Duration { hit = false