import lab3 files

This commit is contained in:
Голиков Maximillian Антон
2026-10-18 21:14:01 +03:00
parent ec540a1a72
commit 76322040e5
64 changed files with 4446 additions and 0 deletions
+195
View File
@@ -0,0 +1,195 @@
package postgres
import (
"context"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"high-loud-apps-labs/internal/domain"
)
type ChatRepo struct {
pool *pgxpool.Pool
}
func NewChatRepo(pool *pgxpool.Pool) *ChatRepo {
return &ChatRepo{pool: pool}
}
// Create атомарно создаёт чат и его участников.
func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error {
tx, err := r.pool.Begin(ctx)
if err != nil {
return mapError(err)
}
defer func() { _ = tx.Rollback(ctx) }()
const qChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)`
if _, err := tx.Exec(ctx, qChat, chat.ID, chat.Title, chat.CreatedAt); err != nil {
if checkViolation(err) {
return &domain.ValidationError{Field: "chat", Message: "нарушено ограничение целостности"}
}
return mapError(err)
}
const qMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)`
for _, uid := range chat.MemberIDs {
if _, err := tx.Exec(ctx, qMember, chat.ID, uid); err != nil {
if foreignKeyViolation(err) {
return &domain.ValidationError{
Field: "member_ids",
Message: "неизвестный участник " + uid,
}
}
if uniqueViolation(err) {
return &domain.ValidationError{
Field: "member_ids",
Message: "дубликаты запрещены",
}
}
return mapError(err)
}
}
return mapError(tx.Commit(ctx))
}
func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) {
const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid`
c := &domain.Chat{}
err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt)
if err != nil {
return nil, notFound(err, "chat", id)
}
members, err := r.loadMembers(ctx, []string{c.ID})
if err != nil {
return nil, err
}
c.MemberIDs = members[c.ID]
if c.MemberIDs == nil {
c.MemberIDs = []string{}
}
return c, nil
}
func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) {
scope := "chats:" + userID
var (
afterTime time.Time
afterID string
hasCursor bool
)
if cursor != nil {
t, id, err := decodeCursor(*cursor, scope)
if err != nil {
return nil, nil, err
}
afterTime = t
afterID = id
hasCursor = true
}
var (
rows pgx.Rows
err error
)
if hasCursor {
const q = `
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1::uuid
AND (c.created_at, c.id) > ($2, $3::uuid)
ORDER BY c.created_at, c.id
LIMIT $4
`
rows, err = r.pool.Query(ctx, q, userID, afterTime, afterID, limit+1)
} else {
const q = `
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members m ON m.chat_id = c.id
WHERE m.user_id = $1::uuid
ORDER BY c.created_at, c.id
LIMIT $2
`
rows, err = r.pool.Query(ctx, q, userID, limit+1)
}
if err != nil {
return nil, nil, mapError(err)
}
defer rows.Close()
page := make([]domain.Chat, 0, limit)
for rows.Next() {
var c domain.Chat
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
return nil, nil, mapError(err)
}
page = append(page, c)
}
if err := rows.Err(); err != nil {
return nil, nil, mapError(err)
}
var next *string
if len(page) > limit {
page = page[:limit]
last := page[len(page)-1]
c := encodeCursor(scope, last.CreatedAt, last.ID)
next = &c
}
if len(page) > 0 {
ids := make([]string, len(page))
for i := range page {
ids[i] = page[i].ID
}
members, err := r.loadMembers(ctx, ids)
if err != nil {
return nil, nil, err
}
for i := range page {
if m, ok := members[page[i].ID]; ok {
page[i].MemberIDs = m
} else {
page[i].MemberIDs = []string{}
}
}
}
return page, next, nil
}
// loadMembers одним запросом собирает участников для указанных чатов.
func (r *ChatRepo) loadMembers(ctx context.Context, chatIDs []string) (map[string][]string, error) {
if len(chatIDs) == 0 {
return map[string][]string{}, nil
}
const q = `
SELECT chat_id, user_id
FROM chat_members
WHERE chat_id = ANY($1::uuid[])
ORDER BY chat_id, user_id
`
rows, err := r.pool.Query(ctx, q, chatIDs)
if err != nil {
return nil, mapError(err)
}
defer rows.Close()
result := make(map[string][]string, len(chatIDs))
for rows.Next() {
var chatID, userID string
if err := rows.Scan(&chatID, &userID); err != nil {
return nil, mapError(err)
}
result[chatID] = append(result[chatID], userID)
}
return result, mapError(rows.Err())
}
var _ domain.ChatRepository = (*ChatRepo)(nil)
@@ -0,0 +1,46 @@
package postgres
import (
"encoding/base64"
"strings"
"time"
"high-loud-apps-labs/internal/domain"
"github.com/google/uuid"
)
// Взял за основу что в inmemery делал
func encodeCursor(scope string, createdAt time.Time, id string) string {
raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func decodeCursor(cursor, expectedScope string) (time.Time, string, error) {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return time.Time{}, "", badCursor()
}
parts := strings.SplitN(string(data), "|", 3)
if len(parts) != 3 {
return time.Time{}, "", badCursor()
}
if parts[0] != expectedScope {
return time.Time{}, "", badCursor()
}
t, err := time.Parse(time.RFC3339Nano, parts[1])
if err != nil {
return time.Time{}, "", badCursor()
}
if _, err := uuid.Parse(parts[2]); err != nil {
return time.Time{}, "", badCursor()
}
return t, parts[2], nil
}
func badCursor() error {
return &domain.ValidationError{
Field: "cursor",
Message: "некорректный формат",
}
}
+75
View File
@@ -0,0 +1,75 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
"high-loud-apps-labs/migrations"
)
type Config struct {
URL string
MaxConns int32
MinConns int32
MaxConnLifetime time.Duration
MaxConnIdleTime time.Duration
ConnectTimeout time.Duration
}
func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
if cfg.URL == "" {
return nil, fmt.Errorf("DATABASE_URL пустой")
}
poolCfg, err := pgxpool.ParseConfig(cfg.URL)
if err != nil {
return nil, fmt.Errorf("разбор DATABASE_URL: %w", err)
}
if cfg.MaxConns > 0 {
poolCfg.MaxConns = cfg.MaxConns
}
if cfg.MinConns > 0 {
poolCfg.MinConns = cfg.MinConns
}
if cfg.MaxConnLifetime > 0 {
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
}
if cfg.MaxConnIdleTime > 0 {
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
}
if cfg.ConnectTimeout > 0 {
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
}
poolCfg.HealthCheckPeriod = 10 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
if err != nil {
return nil, fmt.Errorf("создание пула: %w", err)
}
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping БД: %w", err)
}
return pool, nil
}
func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error {
db := stdlib.OpenDBFromPool(pool)
goose.SetBaseFS(migrations.FS)
if err := goose.SetDialect("postgres"); err != nil {
return fmt.Errorf("goose dialect: %w", err)
}
if err := goose.UpContext(ctx, db, "."); err != nil {
return fmt.Errorf("применение миграций: %w", err)
}
return nil
}
@@ -0,0 +1,71 @@
package postgres
import (
"context"
"errors"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"high-loud-apps-labs/internal/domain"
)
type coded interface {
Code() domain.ErrorCode
}
// mapError переводит ошибки драйвера в доменные.
func mapError(err error) error {
if err == nil {
return nil
}
var c coded
if errors.As(err, &c) {
return err
}
if errors.Is(err, pgx.ErrNoRows) {
return err
}
if errors.Is(err, context.DeadlineExceeded) {
return &domain.UnavailableError{Reason: "превышено время ожидания БД"}
}
if errors.Is(err, context.Canceled) {
return &domain.UnavailableError{Reason: "запрос отменён"}
}
return &domain.UnavailableError{Reason: err.Error()}
}
func notFound(err error, entity, id string) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return &domain.NotFoundError{Entity: entity, ID: id}
}
return mapError(err)
}
func uniqueViolation(err error) bool {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
return pgErr.Code == pgerrcode.UniqueViolation
}
return false
}
func foreignKeyViolation(err error) bool {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
return pgErr.Code == pgerrcode.ForeignKeyViolation
}
return false
}
func checkViolation(err error) bool {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
return pgErr.Code == pgerrcode.CheckViolation
}
return false
}
@@ -0,0 +1,203 @@
package postgres
import (
"bytes"
"context"
"net/http"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"high-loud-apps-labs/internal/domain"
)
type MessageRepo struct {
pool *pgxpool.Pool
}
func NewMessageRepo(pool *pgxpool.Pool) *MessageRepo {
return &MessageRepo{pool: pool}
}
func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error {
const q = `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
`
_, err := r.pool.Exec(ctx, q, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt)
if err != nil {
if foreignKeyViolation(err) {
return &domain.NotFoundError{Entity: "chat", ID: m.ChatID}
}
if checkViolation(err) {
return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
}
return err
}
return nil
}
func (r *MessageRepo) CreateIdempotent(
ctx context.Context,
scope domain.IdempotencyScope,
requestHash []byte,
fresh *domain.Message,
freshResponse []byte,
ttl time.Duration,
) (*domain.CreateIdempotentResult, error) {
tx, err := r.pool.Begin(ctx)
if err != nil {
return nil, mapError(err)
}
defer func() { _ = tx.Rollback(ctx) }()
// 1) Убираем просроченную запись, чтобы ON CONFLICT сработал
// только на живой, а не на истёкшей строке.
if _, err := tx.Exec(ctx, `
DELETE FROM idempotency_keys
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
AND expires_at <= now()
`, scope.UserID, scope.Method, scope.Path, scope.Key); err != nil {
return nil, mapError(err)
}
// 2) Резервируем слот. Если параллельная реплика уже вставила —
// Postgres заблокирует конфликтный INSERT и мы увидим RowsAffected=0
// только после того, как конкурент закоммитит или откатится.
expiresAt := time.Now().UTC().Add(ttl)
tag, err := tx.Exec(ctx, `
INSERT INTO idempotency_keys
(user_id, method, path, key, request_hash, response_status, response_body, expires_at)
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (user_id, method, path, key) DO NOTHING
`, scope.UserID, scope.Method, scope.Path, scope.Key,
requestHash, http.StatusCreated, freshResponse, expiresAt)
if err != nil {
return nil, mapError(err)
}
// 3) Слот занят — читаем сохранённый ответ в этой же транзакции.
if tag.RowsAffected() == 0 {
var (
storedHash []byte
storedStatus int
storedBody []byte
)
err := tx.QueryRow(ctx, `
SELECT request_hash, response_status, response_body
FROM idempotency_keys
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
`, scope.UserID, scope.Method, scope.Path, scope.Key).
Scan(&storedHash, &storedStatus, &storedBody)
if err != nil {
return nil, mapError(err)
}
if !bytes.Equal(storedHash, requestHash) {
return nil, &domain.IdempotencyConflictError{Key: scope.Key}
}
if err := tx.Commit(ctx); err != nil {
return nil, mapError(err)
}
return &domain.CreateIdempotentResult{
Status: storedStatus,
Body: storedBody,
Replayed: true,
}, nil
}
// 4) Слот наш — вставляем сообщение в той же транзакции.
if _, err := tx.Exec(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
`, fresh.ID, fresh.ChatID, fresh.SenderID, fresh.Text, fresh.CreatedAt); err != nil {
if foreignKeyViolation(err) {
return nil, &domain.NotFoundError{Entity: "chat", ID: fresh.ChatID}
}
if checkViolation(err) {
return nil, &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
}
return nil, mapError(err)
}
if err := tx.Commit(ctx); err != nil {
return nil, mapError(err)
}
return &domain.CreateIdempotentResult{
Status: http.StatusCreated,
Body: freshResponse,
Replayed: false,
}, nil
}
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
scope := "messages:" + chatID
var (
afterTime time.Time
afterID string
hasCursor bool
)
if cursor != nil {
t, id, err := decodeCursor(*cursor, scope)
if err != nil {
return nil, nil, err
}
afterTime = t
afterID = id
hasCursor = true
}
var (
rows pgx.Rows
err error
)
if hasCursor {
const q = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1::uuid
AND (created_at, id) > ($2, $3::uuid)
ORDER BY created_at, id
LIMIT $4
`
rows, err = r.pool.Query(ctx, q, chatID, afterTime, afterID, limit+1)
} else {
const q = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1::uuid
ORDER BY created_at, id
LIMIT $2
`
rows, err = r.pool.Query(ctx, q, chatID, limit+1)
}
if err != nil {
return nil, nil, err
}
defer rows.Close()
page := make([]domain.Message, 0, limit)
for rows.Next() {
var m domain.Message
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
return nil, nil, err
}
page = append(page, m)
}
if err := rows.Err(); err != nil {
return nil, nil, err
}
var next *string
if len(page) > limit {
page = page[:limit]
last := page[len(page)-1]
c := encodeCursor(scope, last.CreatedAt, last.ID)
next = &c
}
return page, next, nil
}
var _ domain.MessageRepository = (*MessageRepo)(nil)
@@ -0,0 +1,59 @@
package postgres
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"high-loud-apps-labs/internal/domain"
)
type SessionRepo struct {
pool *pgxpool.Pool
}
func NewSessionRepo(pool *pgxpool.Pool) *SessionRepo {
return &SessionRepo{pool: pool}
}
func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error {
const q = `
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
VALUES ($1, $2::uuid, $3, $4)
`
_, err := r.pool.Exec(ctx, q, s.TokenHash, s.UserID, s.ExpiresAt, s.CreatedAt)
if err != nil {
if uniqueViolation(err) {
return &domain.AlreadyExistsError{
Entity: "session",
Field: "token_hash",
Value: "",
}
}
return mapError(err)
}
return nil
}
func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) {
const q = `
SELECT token_hash, user_id, expires_at, created_at
FROM sessions
WHERE token_hash = $1
`
s := &domain.Session{}
err := r.pool.QueryRow(ctx, q, tokenHash).
Scan(&s.TokenHash, &s.UserID, &s.ExpiresAt, &s.CreatedAt)
if err != nil {
return nil, notFound(err, "session", "")
}
return s, nil
}
func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error {
const q = `DELETE FROM sessions WHERE token_hash = $1`
_, err := r.pool.Exec(ctx, q, tokenHash)
return mapError(err)
}
var _ domain.SessionRepository = (*SessionRepo)(nil)
@@ -0,0 +1,18 @@
package postgres
import "github.com/jackc/pgx/v5/pgxpool"
type Storage struct {
pool *pgxpool.Pool
}
func New(pool *pgxpool.Pool) *Storage {
return &Storage{pool: pool}
}
func (s *Storage) Pool() *pgxpool.Pool { return s.pool }
func (s *Storage) Users() *UserRepo { return &UserRepo{pool: s.pool} }
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{pool: s.pool} }
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{pool: s.pool} }
func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool: s.pool} }
+76
View File
@@ -0,0 +1,76 @@
package postgres
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"high-loud-apps-labs/internal/domain"
)
type UserRepo struct {
pool *pgxpool.Pool
}
func NewUserRepo(pool *pgxpool.Pool) *UserRepo {
return &UserRepo{pool: pool}
}
func (r *UserRepo) Create(ctx context.Context, user *domain.User) error {
const q = `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1::uuid, $2, $3, $4, $5)
`
_, err := r.pool.Exec(ctx, q,
user.ID, user.Username, user.DisplayName, user.PasswordHash, user.CreatedAt,
)
if err != nil {
if uniqueViolation(err) {
return &domain.AlreadyExistsError{
Entity: "user",
Field: "username",
Value: user.Username,
}
}
if checkViolation(err) {
return &domain.ValidationError{
Field: "user",
Message: "нарушено ограничение целостности",
}
}
return mapError(err)
}
return nil
}
func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) {
const q = `
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE id = $1::uuid
`
u := &domain.User{}
err := r.pool.QueryRow(ctx, q, id).
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if err != nil {
return nil, notFound(err, "user", id)
}
return u, nil
}
func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) {
const q = `
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = $1
`
u := &domain.User{}
err := r.pool.QueryRow(ctx, q, username).
Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if err != nil {
return nil, notFound(err, "user", username)
}
return u, nil
}
var _ domain.UserRepository = (*UserRepo)(nil)