Skip to content

Commit

Permalink
feat(serv): stop cache gracefully
Browse files Browse the repository at this point in the history
Refs: #119
  • Loading branch information
pascal-zarrad committed Mar 3, 2023
1 parent 2454079 commit 1121d7c
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 0 deletions.
2 changes: 2 additions & 0 deletions internal/quit.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package internal

import (
"github.com/lazybytez/jojo-discord-bot/api"
"github.com/lazybytez/jojo-discord-bot/services/cache"
"github.com/rs/zerolog/log"
"os"
)
Expand Down Expand Up @@ -66,5 +67,6 @@ func releaseResources() {
UnloadComponents(discord)
api.DeinitCommandHandling()
shutdownApiWebserver()
cache.Deinit()
stopBot()
}
7 changes: 7 additions & 0 deletions services/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type Provider interface {
Get(key string, t reflect.Type) (interface{}, bool)
Update(key string, t reflect.Type, value interface{}) error
Invalidate(key string, t reflect.Type) bool
Shutdown()
}

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

// Deinit stops the cache and ensures that all open connections
// to external services are closed before the application exits.
func Deinit() {
cache.Shutdown()
}

// validatePointersAreNotAllowed panics if t is a pointer.
// The cache is not designed to deal with pointers, therefore it is
// not allowed to pass some. Passing a pointer is considered a fatal error
Expand Down
3 changes: 3 additions & 0 deletions services/cache/memory/memory_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,6 @@ func (provider *InMemoryCacheProvider) Invalidate(key string, t reflect.Type) bo

return true
}

// Shutdown on in-memory cache does nothing, as no external services are used.
func (provider *InMemoryCacheProvider) Shutdown() {}
5 changes: 5 additions & 0 deletions services/cache/redis/redis_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ func (grc *GoRedisCacheProvider) Invalidate(key string, t reflect.Type) bool {
return grc.cache.Delete(context.TODO(), computeCacheKeyFromKeyAndType(key, t)) == nil
}

// Shutdown closes the Redis client attached to the cache instance.
func (grc *GoRedisCacheProvider) Shutdown() {
_ = grc.client.Close()
}

// computeCacheKeyFromKeyAndType creates a new cache key from a key and a type.
// The format is "PackagePath_TypeName_Key".
func computeCacheKeyFromKeyAndType(key string, t reflect.Type) string {
Expand Down

0 comments on commit 1121d7c

Please sign in to comment.