Skip to content

Commit 1121d7c

Browse files
committed
feat(serv): stop cache gracefully
Refs: #119
1 parent 2454079 commit 1121d7c

File tree

4 files changed

+17
-0
lines changed

4 files changed

+17
-0
lines changed

internal/quit.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ package internal
2020

2121
import (
2222
"github.com/lazybytez/jojo-discord-bot/api"
23+
"github.com/lazybytez/jojo-discord-bot/services/cache"
2324
"github.com/rs/zerolog/log"
2425
"os"
2526
)
@@ -66,5 +67,6 @@ func releaseResources() {
6667
UnloadComponents(discord)
6768
api.DeinitCommandHandling()
6869
shutdownApiWebserver()
70+
cache.Deinit()
6971
stopBot()
7072
}

services/cache/cache.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ type Provider interface {
4545
Get(key string, t reflect.Type) (interface{}, bool)
4646
Update(key string, t reflect.Type, value interface{}) error
4747
Invalidate(key string, t reflect.Type) bool
48+
Shutdown()
4849
}
4950

5051
// cache is the currently active Provider that manages the underlying
@@ -108,6 +109,12 @@ func Invalidate[T any](key string, t T) bool {
108109
return cache.Invalidate(key, reflect.TypeOf(t))
109110
}
110111

112+
// Deinit stops the cache and ensures that all open connections
113+
// to external services are closed before the application exits.
114+
func Deinit() {
115+
cache.Shutdown()
116+
}
117+
111118
// validatePointersAreNotAllowed panics if t is a pointer.
112119
// The cache is not designed to deal with pointers, therefore it is
113120
// not allowed to pass some. Passing a pointer is considered a fatal error

services/cache/memory/memory_cache.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,3 +223,6 @@ func (provider *InMemoryCacheProvider) Invalidate(key string, t reflect.Type) bo
223223

224224
return true
225225
}
226+
227+
// Shutdown on in-memory cache does nothing, as no external services are used.
228+
func (provider *InMemoryCacheProvider) Shutdown() {}

services/cache/redis/redis_cache.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,11 @@ func (grc *GoRedisCacheProvider) Invalidate(key string, t reflect.Type) bool {
152152
return grc.cache.Delete(context.TODO(), computeCacheKeyFromKeyAndType(key, t)) == nil
153153
}
154154

155+
// Shutdown closes the Redis client attached to the cache instance.
156+
func (grc *GoRedisCacheProvider) Shutdown() {
157+
_ = grc.client.Close()
158+
}
159+
155160
// computeCacheKeyFromKeyAndType creates a new cache key from a key and a type.
156161
// The format is "PackagePath_TypeName_Key".
157162
func computeCacheKeyFromKeyAndType(key string, t reflect.Type) string {

0 commit comments

Comments
 (0)