lab2
This commit is contained in:
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrCacheMiss = errors.New("cache miss")
|
||||
|
||||
type Cache interface {
|
||||
Get(ctx context.Context, key string) ([]byte, error)
|
||||
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
|
||||
Delete(ctx context.Context, keys ...string) error
|
||||
Ping(ctx context.Context) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type NoOpCache struct{}
|
||||
|
||||
func (NoOpCache) Get(context.Context, string) ([]byte, error) { return nil, ErrCacheMiss }
|
||||
func (NoOpCache) Set(context.Context, string, []byte, time.Duration) error { return nil }
|
||||
func (NoOpCache) Delete(context.Context, ...string) error { return nil }
|
||||
func (NoOpCache) Ping(context.Context) error { return nil }
|
||||
func (NoOpCache) Close() error { return nil }
|
||||
Vendored
+101
@@ -0,0 +1,101 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RedisConfig struct {
|
||||
Host string
|
||||
Port int
|
||||
Password string
|
||||
DB int
|
||||
MaxRetries int
|
||||
DialTimeout time.Duration
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
PoolSize int
|
||||
}
|
||||
|
||||
type RedisCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewRedis(cfg RedisConfig) (*RedisCache, error) {
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
DialTimeout: cfg.DialTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
PoolSize: cfg.PoolSize,
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
|
||||
return nil, fmt.Errorf("ping redis: %w", err)
|
||||
}
|
||||
|
||||
return &RedisCache{client: client}, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
value, err := r.client.Get(ctx, key).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, ErrCacheMiss
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("redis get %q: %w", key, err)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
if err := r.client.Set(ctx, key, value, ttl).Err(); err != nil {
|
||||
return fmt.Errorf("redis set %q: %w", key, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Delete(ctx context.Context, keys ...string) error {
|
||||
if len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := r.client.Del(ctx, keys...).Err(); err != nil {
|
||||
return fmt.Errorf("redis delete: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Ping(ctx context.Context) error {
|
||||
if err := r.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("redis ping: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Close() error {
|
||||
if err := r.client.Close(); err != nil {
|
||||
return fmt.Errorf("redis close: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
type SingleflightCache struct {
|
||||
cache Cache
|
||||
group singleflight.Group
|
||||
}
|
||||
|
||||
func WithSingleflight(cache Cache) *SingleflightCache {
|
||||
return &SingleflightCache{cache: cache}
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) GetOrLoad(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
value, err := s.cache.Get(ctx, key)
|
||||
if err == nil {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if !errors.Is(err, ErrCacheMiss) {
|
||||
return loader(ctx)
|
||||
}
|
||||
|
||||
result, err, _ := s.group.Do(key, func() (any, error) {
|
||||
loadCtx := context.WithoutCancel(ctx)
|
||||
if cached, err := s.cache.Get(loadCtx, key); err == nil {
|
||||
return cached, nil
|
||||
}
|
||||
loaded, loadErr := loader(loadCtx)
|
||||
if loadErr != nil {
|
||||
return nil, loadErr
|
||||
}
|
||||
|
||||
_ = s.cache.Set(loadCtx, key, loaded, ttl)
|
||||
|
||||
return loaded, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
loaded, ok := result.([]byte)
|
||||
if !ok {
|
||||
return nil, errors.New("cache: unexpected singleflight result")
|
||||
}
|
||||
|
||||
return loaded, nil
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
return s.cache.Get(ctx, key)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
return s.cache.Set(ctx, key, value, ttl)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Delete(ctx context.Context, keys ...string) error {
|
||||
return s.cache.Delete(ctx, keys...)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Ping(ctx context.Context) error {
|
||||
return s.cache.Ping(ctx)
|
||||
}
|
||||
|
||||
func (s *SingleflightCache) Close() error {
|
||||
return s.cache.Close()
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package cache_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
type memoryCache struct {
|
||||
mu sync.Mutex
|
||||
data map[string][]byte
|
||||
}
|
||||
|
||||
func newMemoryCache() *memoryCache {
|
||||
return &memoryCache{data: make(map[string][]byte)}
|
||||
}
|
||||
|
||||
func (m *memoryCache) Get(_ context.Context, key string) ([]byte, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
value, ok := m.data[key]
|
||||
if !ok {
|
||||
return nil, cache.ErrCacheMiss
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (m *memoryCache) Set(_ context.Context, key string, value []byte, _ time.Duration) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
m.data[key] = value
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryCache) Delete(_ context.Context, keys ...string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
for _, key := range keys {
|
||||
delete(m.data, key)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memoryCache) Ping(context.Context) error { return nil }
|
||||
func (m *memoryCache) Close() error { return nil }
|
||||
|
||||
func TestNoOpCacheAlwaysMisses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
noop := cache.NoOpCache{}
|
||||
|
||||
_, err := noop.Get(context.Background(), "key")
|
||||
require.ErrorIs(t, err, cache.ErrCacheMiss)
|
||||
require.NoError(t, noop.Set(context.Background(), "key", []byte("v"), time.Minute))
|
||||
}
|
||||
|
||||
func TestGetOrLoadCachesResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sf := cache.WithSingleflight(newMemoryCache())
|
||||
ctx := context.Background()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
loader := func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("payload"), nil
|
||||
}
|
||||
|
||||
first, err := sf.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("payload"), first)
|
||||
|
||||
second, err := sf.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("payload"), second)
|
||||
|
||||
require.Equal(t, int32(1), calls.Load(), "loader must run once")
|
||||
}
|
||||
|
||||
func TestGetOrLoadDeduplicatesConcurrentMisses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sf := cache.WithSingleflight(newMemoryCache())
|
||||
ctx := context.Background()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
loader := func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
return []byte("payload"), nil
|
||||
}
|
||||
|
||||
const workers = 50
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for range workers {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
value, err := sf.GetOrLoad(ctx, "shared", time.Minute, loader)
|
||||
if err != nil || string(value) != "payload" {
|
||||
failures.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
require.Zero(t, failures.Load())
|
||||
require.Equal(t, int32(1), calls.Load(), "singleflight must collapse concurrent misses")
|
||||
}
|
||||
|
||||
func TestLeaderCancellationDoesNotCancelSharedLoad(t *testing.T) {
|
||||
t.Parallel()
|
||||
sf := cache.WithSingleflight(newMemoryCache())
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := sf.GetOrLoad(ctx, "cancelled-leader", time.Minute,
|
||||
func(loadCtx context.Context) ([]byte, error) {
|
||||
close(started)
|
||||
<-release
|
||||
if err := loadCtx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []byte("payload"), nil
|
||||
})
|
||||
result <- err
|
||||
}()
|
||||
<-started
|
||||
cancel()
|
||||
close(release)
|
||||
require.NoError(t, <-result)
|
||||
value, err := sf.GetOrLoad(t.Context(), "cancelled-leader", time.Minute,
|
||||
func(context.Context) ([]byte, error) {
|
||||
return []byte("unexpected reload"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "payload", string(value))
|
||||
}
|
||||
Reference in New Issue
Block a user