Реализовать lab3 на оценку 4: балансировка и отказ API
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ErrUnavailable = errors.New("storage unavailable")
|
||||
|
||||
type ProfileCache interface {
|
||||
Get(context.Context, string) (model.User, bool)
|
||||
Set(context.Context, model.User)
|
||||
}
|
||||
|
||||
type PostgresStore struct {
|
||||
pool *pgxpool.Pool
|
||||
profiles ProfileCache
|
||||
}
|
||||
|
||||
func NewPostgresStore(pool *pgxpool.Pool) *PostgresStore {
|
||||
return &PostgresStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *PostgresStore) WithProfiles(profiles ProfileCache) *PostgresStore {
|
||||
s.profiles = profiles
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *PostgresStore) profile(ctx context.Context, id string) (model.User, error) {
|
||||
if s.profiles != nil {
|
||||
if user, ok := s.profiles.Get(ctx, id); ok {
|
||||
return user, nil
|
||||
}
|
||||
}
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT id::text, username, display_name, created_at FROM users WHERE id=$1`, id).Scan(
|
||||
&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
if s.profiles != nil {
|
||||
s.profiles.Set(ctx, user)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, errors.New("cannot generate user ID")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.User
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id::text, username, display_name, created_at`,
|
||||
id, username, displayName, passwordHash,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key" {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user