refactor(backend): standardize errors and simplify configuration and test setup
This commit is contained in:
1 parent
1535c19b8c
commit
138666a7bb
92 files changed
+3994
-210
No files matched your search
@@ -0,0 +1,111 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
cachekit "github.com/wahrwelt-kit/go-cachekit"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
connectionLimit = 10
|
||||
disabledRetries = -1
|
||||
)
|
||||
|
||||
type Cache struct {
|
||||
client *redis.Client
|
||||
store *cachekit.RedisKeyValueStore
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var (
|
||||
_ outbound.Cache = (*Cache)(nil)
|
||||
_ outbound.ReadinessChecker = (*Cache)(nil)
|
||||
)
|
||||
|
||||
// NewCache creates a lazy connection pool. Readiness checks verify connectivity.
|
||||
func NewCache(settings config.Config, logger *slog.Logger) (*Cache, func(), error) {
|
||||
if err := settings.ValidateRedis(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: settings.RedisAddr,
|
||||
Password: settings.RedisPassword,
|
||||
DB: settings.RedisDB,
|
||||
DialTimeout: settings.RedisTimeout,
|
||||
ReadTimeout: settings.RedisTimeout,
|
||||
WriteTimeout: settings.RedisTimeout,
|
||||
PoolTimeout: settings.RedisTimeout,
|
||||
ContextTimeoutEnabled: true,
|
||||
MaxRetries: disabledRetries,
|
||||
PoolSize: connectionLimit,
|
||||
MaxActiveConns: connectionLimit,
|
||||
})
|
||||
cache := &Cache{
|
||||
client: client,
|
||||
store: &cachekit.RedisKeyValueStore{Client: client},
|
||||
timeout: settings.RedisTimeout,
|
||||
}
|
||||
return cache, func() {
|
||||
if err := client.Close(); err != nil {
|
||||
logger.Error("redis.NewCache - close client", "error", err)
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
value, err := cache.store.Get(ctx, key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Cache.Get - get value: %w", cacheError(err))
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
if err := cache.store.Set(ctx, key, value, ttl); err != nil {
|
||||
return fmt.Errorf("Cache.Set - set value: %w", cacheError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Del(ctx context.Context, keys ...string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
if err := cache.store.Del(ctx, keys...); err != nil {
|
||||
return fmt.Errorf("Cache.Del - delete values: %w", cacheError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cache *Cache) Check(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
|
||||
defer cancel()
|
||||
if err := cache.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("Cache.Check - ping Redis: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cacheError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, cachekit.ErrNotFound):
|
||||
return outbound.ErrCacheMiss
|
||||
case errors.Is(err, cachekit.ErrEmptyKey):
|
||||
return outbound.ErrInvalidCacheKey
|
||||
case errors.Is(err, cachekit.ErrInvalidTTL):
|
||||
return outbound.ErrInvalidCacheTTL
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestColdConnectionHonorsTimeout(t *testing.T) {
|
||||
for _, callerDeadline := range []bool{false, true} {
|
||||
name := "configured timeout"
|
||||
if callerDeadline {
|
||||
name = "shorter caller deadline"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer connection.Close()
|
||||
<-release
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
close(release)
|
||||
_ = listener.Close()
|
||||
<-done
|
||||
})
|
||||
timeout := 100 * time.Millisecond
|
||||
if callerDeadline {
|
||||
timeout = time.Second
|
||||
}
|
||||
cache, cleanup, err := NewCache(config.Config{RedisAddr: listener.Addr().String(), RedisTimeout: timeout}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
ctx := t.Context()
|
||||
if callerDeadline {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
|
||||
defer cancel()
|
||||
}
|
||||
started := time.Now()
|
||||
_, err = cache.Get(ctx, "absent")
|
||||
elapsed := time.Since(started)
|
||||
if err == nil || errors.Is(err, outbound.ErrCacheMiss) {
|
||||
t.Fatalf("unresponsive server: %v", err)
|
||||
}
|
||||
if elapsed > 500*time.Millisecond {
|
||||
t.Fatalf("cold connection ignored timeout: elapsed=%s error=%v", elapsed, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user