chore: get files from lab6

This commit is contained in:
Голиков Maximillian Антон
2026-11-24 22:32:11 +03:00
parent 20afc2c790
commit 9b88c6f0bd
118 changed files with 9682 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
package redis
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"high-loud-apps-labs/internal/telemetry"
)
func NewClient(url string) (*redis.Client, error) {
opt, err := redis.ParseURL(url)
if err != nil {
return nil, fmt.Errorf("разбор URL: %w", err)
}
opt.DialTimeout = 700 * time.Millisecond
opt.ReadTimeout = 700 * time.Millisecond
opt.WriteTimeout = 700 * time.Millisecond
opt.MaxRetries = 1
opt.PoolSize = 10
opt.ConnMaxIdleTime = time.Minute
client := redis.NewClient(opt)
client.AddHook(tracingHook{tracer: telemetry.Tracer("storage.redis")})
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := client.Ping(ctx).Err(); err != nil {
_ = client.Close()
return nil, fmt.Errorf("ping: %w", err)
}
return client, nil
}
+31
View File
@@ -0,0 +1,31 @@
package redis
import (
"context"
"errors"
"high-loud-apps-labs/internal/domain"
)
type coded interface {
Code() domain.ErrorCode
}
// mapError переводит ошибки драйвера в доменные.
// Любая недоступность redis (dial/read/write/context) → UnavailableError (503).
func mapError(err error) error {
if err == nil {
return nil
}
var c coded
if errors.As(err, &c) {
return err
}
if errors.Is(err, context.DeadlineExceeded) {
return &domain.UnavailableError{Reason: "превышено время ожидания redis"}
}
if errors.Is(err, context.Canceled) {
return &domain.UnavailableError{Reason: "запрос отменён"}
}
return &domain.UnavailableError{Reason: err.Error()}
}
+38
View File
@@ -0,0 +1,38 @@
package redis
import (
"context"
"errors"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
type tracingHook struct{ tracer trace.Tracer }
func (h tracingHook) DialHook(next redis.DialHook) redis.DialHook { return next }
func (h tracingHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
return h.run(ctx, cmd.Name(), func(ctx context.Context) error { return next(ctx, cmd) })
}
}
func (h tracingHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return func(ctx context.Context, cmds []redis.Cmder) error {
return h.run(ctx, "pipeline", func(ctx context.Context) error { return next(ctx, cmds) })
}
}
func (h tracingHook) run(ctx context.Context, op string, call func(context.Context) error) error {
ctx, span := h.tracer.Start(ctx, "redis."+op, trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(attribute.String("db.system.name", "redis"), attribute.String("db.operation.name", op)))
defer span.End()
err := call(ctx)
if err != nil && !errors.Is(err, redis.Nil) {
span.SetStatus(codes.Error, "операция Redis не выполнена")
}
return err
}
+80
View File
@@ -0,0 +1,80 @@
package redis
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"high-loud-apps-labs/internal/domain"
)
const sessionKeyPrefix = "session:"
type SessionRepo struct {
client *redis.Client
}
func NewSessionRepo(client *redis.Client) *SessionRepo {
return &SessionRepo{client: client}
}
type sessionValue struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}
func (r *SessionRepo) key(tokenHash []byte) string {
return sessionKeyPrefix + hex.EncodeToString(tokenHash)
}
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
ttl := time.Until(s.ExpiresAt)
if ttl <= 0 {
return nil
}
data, err := json.Marshal(sessionValue{
UserID: s.UserID,
ExpiresAt: s.ExpiresAt.UTC(),
CreatedAt: s.CreatedAt.UTC(),
})
if err != nil {
return fmt.Errorf("сериализация сессии: %w", err)
}
return mapError(r.client.Set(ctx, r.key(s.TokenHash), data, ttl).Err())
}
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
data, err := r.client.Get(ctx, r.key(tokenHash)).Bytes()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, &domain.NotFoundError{Entity: "session"}
}
return nil, mapError(err)
}
var sv sessionValue
if err := json.Unmarshal(data, &sv); err != nil {
return nil, fmt.Errorf("разбор сессии: %w", err)
}
return &domain.Session{
TokenHash: tokenHash,
UserID: sv.UserID,
ExpiresAt: sv.ExpiresAt,
CreatedAt: sv.CreatedAt,
}, nil
}
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
return mapError(r.client.Del(ctx, r.key(tokenHash)).Err())
}
var _ domain.SessionRepository = (*SessionRepo)(nil)