From 0f8b7f7ab1d39393504f0acd90f97d94b701392f Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Mon, 24 Feb 2025 12:02:12 +0000 Subject: [PATCH] Abstract the cleanup logic and add helper for cache valid. --- autocleanup.go | 18 ++++++++++++++++++ cache.go | 11 +---------- metadata_cache.go | 19 ++++++------------- 3 files changed, 25 insertions(+), 23 deletions(-) create mode 100644 autocleanup.go diff --git a/autocleanup.go b/autocleanup.go new file mode 100644 index 0000000..523ed2c --- /dev/null +++ b/autocleanup.go @@ -0,0 +1,18 @@ +package traefikoidc + +import "time" + +// autoCleanupRoutine runs a ticker that calls the provided cleanup function at the specified interval. +// It stops when a value is received on the stop channel. +func autoCleanupRoutine(interval time.Duration, stop <-chan struct{}, cleanup func()) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + cleanup() + case <-stop: + return + } + } +} \ No newline at end of file diff --git a/cache.go b/cache.go index 5619391..12f6ab2 100644 --- a/cache.go +++ b/cache.go @@ -178,16 +178,7 @@ func (c *Cache) removeItem(key string) { // startAutoCleanup initiates a goroutine that periodically cleans up expired cache items. func (c *Cache) startAutoCleanup() { - ticker := time.NewTicker(c.autoCleanupInterval) - for { - select { - case <-ticker.C: - c.Cleanup() - case <-c.stopCleanup: - ticker.Stop() - return - } - } + autoCleanupRoutine(c.autoCleanupInterval, c.stopCleanup, c.Cleanup) } // Close terminates the auto cleanup goroutine. diff --git a/metadata_cache.go b/metadata_cache.go index 38cfa81..d99dc3b 100644 --- a/metadata_cache.go +++ b/metadata_cache.go @@ -34,11 +34,13 @@ func (c *MetadataCache) Cleanup() { c.metadata = nil } } - +func (c *MetadataCache) isCacheValid() bool { + return c.metadata != nil && time.Now().Before(c.expiresAt) +} // GetMetadata retrieves the metadata from cache or fetches it if expired func (c *MetadataCache) GetMetadata(providerURL string, httpClient *http.Client, logger *Logger) (*ProviderMetadata, error) { c.mutex.RLock() - if c.metadata != nil && time.Now().Before(c.expiresAt) { + if c.isCacheValid() { defer c.mutex.RUnlock() return c.metadata, nil } @@ -48,7 +50,7 @@ func (c *MetadataCache) GetMetadata(providerURL string, httpClient *http.Client, defer c.mutex.Unlock() // Double-check after acquiring write lock - if c.metadata != nil && time.Now().Before(c.expiresAt) { + if c.isCacheValid() { return c.metadata, nil } @@ -79,16 +81,7 @@ func (c *MetadataCache) GetMetadata(providerURL string, httpClient *http.Client, } func (c *MetadataCache) startAutoCleanup() { - ticker := time.NewTicker(c.autoCleanupInterval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - c.Cleanup() - case <-c.stopCleanup: - return - } - } + autoCleanupRoutine(c.autoCleanupInterval, c.stopCleanup, c.Cleanup) } func (c *MetadataCache) Close() {