lab2
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

This commit is contained in:
Vladislav Kunetskiy
2026-10-06 00:19:15 +03:00
parent 51b236a69f
commit 5ea57db639
119 changed files with 9935 additions and 2138 deletions
+25
View File
@@ -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 }
+101
View File
@@ -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
View File
@@ -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
View File
@@ -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))
}
+52
View File
@@ -0,0 +1,52 @@
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonTime = 1
argonMemory = 64 * 1024
argonThreads = 4
argonKeyLen = 32
argonSaltLen = 16
)
func Hash(plain string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return "argon2id$" +
base64.RawStdEncoding.EncodeToString(salt) + "$" +
base64.RawStdEncoding.EncodeToString(hash), nil
}
func Verify(plain, encoded string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 3 || parts[0] != "argon2id" {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil {
return false
}
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
if err != nil || len(salt) != argonSaltLen || len(expected) != argonKeyLen {
return false
}
actual := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return subtle.ConstantTimeCompare(actual, expected) == 1
}
@@ -0,0 +1,33 @@
package password_test
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/password"
)
func TestHashVerifyRoundTrip(t *testing.T) {
encoded, err := password.Hash("very-secret-password")
require.NoError(t, err)
require.True(t, password.Verify("very-secret-password", encoded))
require.False(t, password.Verify("wrong-password-value", encoded))
}
func TestHashIsSalted(t *testing.T) {
first, err := password.Hash("very-secret-password")
require.NoError(t, err)
second, err := password.Hash("very-secret-password")
require.NoError(t, err)
require.NotEqual(t, first, second)
}
func TestVerifyRejectsMalformedHash(t *testing.T) {
require.False(t, password.Verify("very-secret-password", ""))
require.False(t, password.Verify("very-secret-password", "plain-text"))
require.False(t, password.Verify("very-secret-password", strings.Repeat("x", 64)))
}
+40
View File
@@ -0,0 +1,40 @@
package token
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"errors"
)
const size = 32
var ErrInvalid = errors.New("invalid token")
type Token struct{}
func New() Token {
return Token{}
}
func (Token) Generate() (string, []byte, error) {
raw := make([]byte, size)
if _, err := rand.Read(raw); err != nil {
return "", nil, err
}
sum := sha256.Sum256(raw)
return base64.RawURLEncoding.EncodeToString(raw), sum[:], nil
}
func (Token) Hash(raw string) ([]byte, error) {
decoded, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil || len(decoded) != size {
return nil, ErrInvalid
}
sum := sha256.Sum256(decoded)
return sum[:], nil
}
+44
View File
@@ -0,0 +1,44 @@
package token_test
import (
"crypto/sha256"
"testing"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/token"
)
func TestGenerateProducesUniqueOpaqueTokens(t *testing.T) {
tokens := token.New()
first, firstHash, err := tokens.Generate()
require.NoError(t, err)
require.NotEmpty(t, first)
require.Len(t, firstHash, sha256.Size)
second, secondHash, err := tokens.Generate()
require.NoError(t, err)
require.NotEqual(t, first, second)
require.NotEqual(t, firstHash, secondHash)
}
func TestHashMatchesGeneratedHash(t *testing.T) {
tokens := token.New()
raw, hash, err := tokens.Generate()
require.NoError(t, err)
actual, err := tokens.Hash(raw)
require.NoError(t, err)
require.Equal(t, hash, actual)
}
func TestHashRejectsMalformed(t *testing.T) {
tokens := token.New()
for _, raw := range []string{"", "not-base64!", "c2hvcnQ"} {
_, err := tokens.Hash(raw)
require.ErrorIs(t, err, token.ErrInvalid, raw)
}
}