Files
mtusi2026lab2/internal/platform/cache/singleflight.go
T
Vladislav Kunetskiy 5ea57db639
Application / Lint (pull_request) Canceled after 0s
Application / Unit tests (pull_request) Canceled after 0s
Application / Docker build (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab2
2026-10-06 00:19:15 +03:00

80 lines
1.6 KiB
Go

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()
}