feat:lab4-catchup

This commit is contained in:
Оля Мороз
2026-11-16 11:46:03 +03:00
parent 276dbdad8a
commit 0a361367c7
29 changed files with 2851 additions and 0 deletions
+189
View File
@@ -0,0 +1,189 @@
package domain
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// CreateAttachmentPending резервирует строку ДО записи в S3.
// Это даёт точку компенсации: если S3 PUT упал, строка снимается/чистится.
func (s *Store) CreateAttachmentPending(ctx context.Context, chatID, ownerID, objectKey, filename string) (string, error) {
id := uuid.NewString()
_, err := s.pool.Exec(ctx,
`INSERT INTO attachments (id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, width, height, status)
VALUES ($1,$2,$3,$4,$5,'image/png',1,repeat('0',64),1,1,'pending')`,
id, chatID, ownerID, objectKey, filename)
if err != nil {
return "", classifyDBError(err)
}
return id, nil
}
// FinalizeAttachment атомарно переводит pending→ready с реальными метаданными.
func (s *Store) FinalizeAttachment(ctx context.Context, id, contentType string, size int64, sha string, w, h int) (*Attachment, error) {
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return nil, classifyDBError(err)
}
defer tx.Rollback(ctx)
var a Attachment
var errCode *string
err = tx.QueryRow(ctx,
`UPDATE attachments
SET content_type=$2, size_bytes=$3, sha256=$4, width=$5, height=$6,
status='ready', error_code=NULL, updated_at=now()
WHERE id=$1 AND status='pending'
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
status, error_code, created_at, updated_at`,
id, contentType, size, sha, w, h,
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
&a.Status, &errCode, &a.CreatedAt, &a.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, classifyDBError(err)
}
a.ErrorCode = errCode
a.Variants = []Variant{}
if err := tx.Commit(ctx); err != nil {
return nil, classifyDBError(err)
}
return &a, nil
}
// MarkAttachmentFailed помечает pending как failed (компенсация).
func (s *Store) MarkAttachmentFailed(ctx context.Context, id, code string) error {
_, err := s.pool.Exec(ctx,
`UPDATE attachments SET status='failed', error_code=$2, updated_at=now()
WHERE id=$1 AND status='pending'`, id, code)
return classifyDBError(err)
}
// ScheduleObjectGC ставит object_key в очередь на удаление (grace period).
func (s *Store) ScheduleObjectGC(ctx context.Context, objectKey, reason string) error {
_, err := s.pool.Exec(ctx,
`INSERT INTO attachment_gc (object_key, reason) VALUES ($1,$2)
ON CONFLICT (object_key) DO NOTHING`, objectKey, reason)
return classifyDBError(err)
}
// GetAttachmentForUser возвращает вложение, только если пользователь — участник чата.
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID string) (*Attachment, error) {
var a Attachment
var errCode *string
err := s.pool.QueryRow(ctx, `
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
a.status, a.error_code, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id
WHERE a.id=$1 AND m.user_id=$2 AND a.status='ready'`, id, userID,
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
&a.Status, &errCode, &a.CreatedAt, &a.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, classifyDBError(err)
}
a.ErrorCode = errCode
a.Variants = []Variant{}
return &a, nil
}
// GetAttachmentObjectKey — только для внутреннего download после проверки ACL.
func (s *Store) GetAttachmentObjectKey(ctx context.Context, id string) (string, error) {
var key string
err := s.pool.QueryRow(ctx, `SELECT object_key FROM attachments WHERE id=$1`, id).Scan(&key)
if errors.Is(err, pgx.ErrNoRows) {
return "", ErrNotFound
}
if err != nil {
return "", classifyDBError(err)
}
return key, nil
}
// ValidateAttachmentIDsForChat проверяет, что все вложения принадлежат чату,
// имеют статус ready и лимит 10. Возвращает ErrInvalid/ErrNotFound.
func (s *Store) ValidateAttachmentIDsForChat(ctx context.Context, chatID string, ids []string) error {
if len(ids) > 10 {
return ErrInvalid
}
seen := map[string]bool{}
for _, id := range ids {
if seen[id] {
return ErrInvalid
}
seen[id] = true
var ok bool
err := s.pool.QueryRow(ctx,
`SELECT true FROM attachments WHERE id=$1 AND chat_id=$2 AND status='ready'`,
id, chatID).Scan(&ok)
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
if err != nil {
return classifyDBError(err)
}
}
return nil
}
// ReconcileOrphans: удаляет объекты из attachment_gc старше grace, которых нет в БД,
// и «призрачные» объекты pending старше grace. Вызывается из фонового тикера.
func (s *Store) ReconcileOrphans(ctx context.Context, s3 *S3Store, grace time.Duration) error {
// 1) GC-очередь: удалить объекты в S3, затем строку.
rows, err := s.pool.Query(ctx,
`SELECT object_key FROM attachment_gc WHERE created_at < now() - $1::interval LIMIT 100`,
grace.String())
if err != nil {
return classifyDBError(err)
}
var keys []string
for rows.Next() {
var k string
if err := rows.Scan(&k); err != nil {
rows.Close()
return classifyDBError(err)
}
keys = append(keys, k)
}
rows.Close()
for _, k := range keys {
if err := s3.DeleteObject(ctx, k); err != nil {
continue
}
_, _ = s.pool.Exec(ctx, `DELETE FROM attachment_gc WHERE object_key=$1`, k)
}
// 2) pending-записи старше grace: объект мог попасть в S3, а commit — нет.
prow, err := s.pool.Query(ctx,
`SELECT id, object_key FROM attachments
WHERE status='pending' AND created_at < now() - $1::interval LIMIT 100`,
grace.String())
if err != nil {
return classifyDBError(err)
}
type pend struct{ id, key string }
var pendings []pend
for prow.Next() {
var p pend
if err := prow.Scan(&p.id, &p.key); err != nil {
prow.Close()
return classifyDBError(err)
}
pendings = append(pendings, p)
}
prow.Close()
for _, p := range pendings {
_ = s3.DeleteObject(ctx, p.key)
_, _ = s.pool.Exec(ctx, `DELETE FROM attachments WHERE id=$1 AND status='pending'`, p.id)
}
return nil
}
+91
View File
@@ -0,0 +1,91 @@
package domain
import (
"context"
"encoding/json"
"time"
"github.com/redis/go-redis/v9"
)
// SessionCache — необязательный кэш сессий поверх Redis.
// Источник истины — PostgreSQL. Кэш ускоряет проверку токена.
type SessionCache struct {
rdb *redis.Client
}
func NewSessionCache(ctx context.Context, url string) (*SessionCache, error) {
opt, err := redis.ParseURL(url)
if err != nil {
return nil, err
}
// Жёсткие короткие таймауты: Redis — кэш, а не критический путь.
opt.DialTimeout = 1 * time.Second
opt.ReadTimeout = 500 * time.Millisecond
opt.WriteTimeout = 500 * time.Millisecond
opt.MaxRetries = 0 // без автоматических ретраев: одна попытка — и уходим в БД
opt.PoolTimeout = 1 * time.Second
rdb := redis.NewClient(opt)
// Проверка связи при старте — короткая.
c, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
if err := rdb.Ping(c).Err(); err != nil {
_ = rdb.Close()
return nil, err
}
return &SessionCache{rdb: rdb}, nil
}
func (c *SessionCache) userKey(userID string) string { return "user:" + userID }
// opCtx возвращает контекст с коротким таймаутом для каждой операции.
// Не наследуем HTTP-контекст напрямую, чтобы не блокировать ответ клиенту.
func (c *SessionCache) opCtx() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), 500*time.Millisecond)
}
// SetUser кладёт публичные данные пользователя в кэш с TTL до конца сессии.
func (c *SessionCache) SetUser(ctx context.Context, userID string, u User, expires time.Time) {
ttl := time.Until(expires)
if ttl <= 0 {
return
}
b, err := json.Marshal(u)
if err != nil {
return
}
opCtx, cancel := c.opCtx()
defer cancel()
_ = c.rdb.Set(opCtx, c.userKey(userID), b, ttl).Err()
}
func (c *SessionCache) GetUser(ctx context.Context, userID string) (User, bool) {
opCtx, cancel := c.opCtx()
defer cancel()
b, err := c.rdb.Get(opCtx, c.userKey(userID)).Bytes()
if err != nil {
return User{}, false
}
var u User
if err := json.Unmarshal(b, &u); err != nil {
return User{}, false
}
return u, true
}
// DelUser — на случай удаления пользователя (в lab2 не вызывается).
func (c *SessionCache) DelUser(ctx context.Context, userID string) error {
opCtx, cancel := c.opCtx()
defer cancel()
return c.rdb.Del(opCtx, c.userKey(userID)).Err()
}
func (c *SessionCache) Ping(ctx context.Context) error {
c2, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
return c.rdb.Ping(c2).Err()
}
func (c *SessionCache) Close() error { return c.rdb.Close() }
+75
View File
@@ -0,0 +1,75 @@
package domain
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"time"
"github.com/jackc/pgx/v5"
)
// IdempotencyRecord — сохранённый результат POST.
type IdempotencyRecord struct {
StatusCode int
Response json.RawMessage
}
// LookupIdempotency возвращает запись, если ключ уже использован.
// Второй аргумент — совпадает ли хеш тела с сохранённым.
func (s *Store) LookupIdempotency(ctx context.Context, userID, method, path, key, bodyHash string) (*IdempotencyRecord, bool, error) {
var (
storedHash string
rec IdempotencyRecord
)
err := s.pool.QueryRow(ctx,
`SELECT request_hash, status_code, response
FROM idempotency_keys
WHERE user_id=$1 AND method=$2 AND path=$3 AND key=$4`,
userID, method, path, key,
).Scan(&storedHash, &rec.StatusCode, &rec.Response)
if errors.Is(err, pgx.ErrNoRows) {
return nil, false, nil
}
if err != nil {
return nil, false, classifyDBError(err)
}
if storedHash != bodyHash {
return nil, true, ErrConflict
}
return &rec, true, nil
}
// SaveIdempotency пишет результат. Конфликт PK означает, что параллельный
// запрос успел раньше — вызывающий должен перечитать через LookupIdempotency.
func (s *Store) SaveIdempotency(ctx context.Context, userID, method, path, key, bodyHash string, status int, resp json.RawMessage) error {
_, err := s.pool.Exec(ctx,
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
userID, method, path, key, bodyHash, status, resp)
return classifyDBError(err)
}
// HashBody — стабильный хеш JSON независимо от порядка ключей.
func HashBody(raw []byte) (string, error) {
var v any
if err := json.Unmarshal(raw, &v); err != nil {
return "", err
}
normalized, err := json.Marshal(v) // map keys сортируются
if err != nil {
return "", err
}
sum := sha256.Sum256(normalized)
return hex.EncodeToString(sum[:]), nil
}
// CleanupIdempotency — можно звать из фонового тикера (опционально).
func (s *Store) CleanupIdempotency(ctx context.Context, olderThan time.Duration) error {
_, err := s.pool.Exec(ctx,
`DELETE FROM idempotency_keys WHERE created_at < now() - $1::interval`,
olderThan.String())
return err
}
+92
View File
@@ -0,0 +1,92 @@
package domain
import (
"errors"
"time"
)
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt time.Time `json:"created_at"`
}
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type MessagePage struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
User User `json:"user"`
}
type ErrorBody struct {
Error ErrorDetail `json:"error"`
}
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []Variant `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrInvalid = errors.New("invalid request")
ErrUnauthorized = errors.New("unauthorized")
ErrTimeout = errors.New("timeout")
ErrUnavailable = errors.New("unavailable")
ErrTooLarge = errors.New("payload too large")
ErrUnsupported = errors.New("unsupported media type")
ErrNotImage = errors.New("not a valid image")
)
+608
View File
@@ -0,0 +1,608 @@
package domain
import (
"context"
"errors"
"fmt"
"strings"
"time"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/argon2"
)
type Store struct {
pool *pgxpool.Pool
}
func NewStore(ctx context.Context, dsn string) (*Store, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, classifyDBError(err)
}
cfg.MaxConns = 10
cfg.MinConns = 1
cfg.MaxConnLifetime = time.Hour
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
_, err := conn.Exec(ctx, `
SET statement_timeout = '5s';
SET lock_timeout = '2s';
SET idle_in_transaction_session_timeout = '5s';
`)
return err
}
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, classifyDBError(err)
}
ctxPing, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(ctxPing); err != nil {
pool.Close()
return nil, classifyDBError(err)
}
return &Store{pool: pool}, nil
}
func (s *Store) Close() { s.pool.Close() }
func (s *Store) Ping(ctx context.Context) error {
c, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
return s.pool.Ping(c)
}
// Argon2id параметры — OWASP baseline: m=19456 KiB (19 MiB), t=2, p=1.
// Хеш кодируется в формате PHC: $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
const (
argonMemory uint32 = 19456
argonTime uint32 = 2
argonThreads uint8 = 1
argonKeyLen uint32 = 32
argonSaltLen = 16
)
func hashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Key := base64.RawStdEncoding.EncodeToString(key)
// PHC string; параметры можно будет менять в будущем, старые хеши останутся валидными.
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
argonMemory, argonTime, argonThreads, b64Salt, b64Key), nil
}
func verifyPassword(password, encoded string) bool {
// Минимальный парсер PHC-строки.
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false
}
var mem, time uint32
var threads uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &mem, &time, &threads); err != nil {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false
}
wantKey, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false
}
gotKey := argon2.IDKey([]byte(password), salt, time, mem, threads, uint32(len(wantKey)))
return subtle.ConstantTimeCompare(gotKey, wantKey) == 1
}
// --- Users ---
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
hash, err := hashPassword(password)
if err != nil {
return nil, classifyDBError(err)
}
id := uuid.NewString()
var u User
err = s.pool.QueryRow(ctx,
`INSERT INTO users (id, username, display_name, password_hash)
VALUES ($1,$2,$3,$4)
RETURNING id, username, display_name, created_at`,
id, username, displayName, string(hash),
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return nil, ErrConflict
}
return nil, classifyDBError(err)
}
return &u, nil
}
func (s *Store) GetUserByID(ctx context.Context, id string) (*User, error) {
var u User
err := s.pool.QueryRow(ctx,
`SELECT id, username, display_name, created_at FROM users WHERE id=$1`, id,
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, classifyDBError(err)
}
return &u, nil
}
// VerifyPassword возвращает пользователя, если пароль верный; иначе ErrUnauthorized.
func (s *Store) VerifyPassword(ctx context.Context, username, password string) (*User, error) {
var u User
var hash string
err := s.pool.QueryRow(ctx,
`SELECT id, username, display_name, created_at, password_hash FROM users WHERE username=$1`,
username,
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
if errors.Is(err, pgx.ErrNoRows) {
// Тратим сопоставимое время на проверку фиктивного хеша,
// чтобы не различать "нет пользователя" и "неверный пароль" по таймингу.
_ = verifyPassword(password, "$argon2id$v=19$m=19456,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
return nil, ErrUnauthorized
}
if err != nil {
return nil, classifyDBError(err)
}
if !verifyPassword(password, hash) {
return nil, ErrUnauthorized
}
return &u, nil
}
// --- Chats ---
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, creatorID string) (*Chat, error) {
// Проверка входных данных.
seen := map[string]bool{}
for _, id := range memberIDs {
if seen[id] {
return nil, ErrInvalid
}
seen[id] = true
}
if !seen[creatorID] {
return nil, ErrInvalid
}
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return nil, classifyDBError(err)
}
defer tx.Rollback(ctx)
// Проверяем, что все участники существуют.
for id := range seen {
var exists bool
if err := tx.QueryRow(ctx, `SELECT true FROM users WHERE id=$1`, id).Scan(&exists); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrInvalid
}
return nil, classifyDBError(err)
}
}
chatID := uuid.NewString()
var c Chat
err = tx.QueryRow(ctx,
`INSERT INTO chats (id, title) VALUES ($1,$2) RETURNING id, title, created_at`,
chatID, title,
).Scan(&c.ID, &c.Title, &c.CreatedAt)
if err != nil {
return nil, classifyDBError(err)
}
for id := range seen {
if _, err := tx.Exec(ctx,
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1,$2)`,
c.ID, id,
); err != nil {
return nil, classifyDBError(err)
}
}
if err := tx.Commit(ctx); err != nil {
return nil, classifyDBError(err)
}
// Порядок member_ids — как в запросе.
c.MemberIDs = append([]string(nil), memberIDs...)
return &c, nil
}
func (s *Store) GetChat(ctx context.Context, chatID, userID string) (*Chat, error) {
var exists bool
err := s.pool.QueryRow(ctx,
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
chatID, userID,
).Scan(&exists)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, classifyDBError(err)
}
var c Chat
err = s.pool.QueryRow(ctx,
`SELECT id, title, created_at FROM chats WHERE id=$1`, chatID,
).Scan(&c.ID, &c.Title, &c.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, classifyDBError(err)
}
rows, err := s.pool.Query(ctx,
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chatID)
if err != nil {
return nil, classifyDBError(err)
}
defer rows.Close()
for rows.Next() {
var uid string
if err := rows.Scan(&uid); err != nil {
return nil, classifyDBError(err)
}
c.MemberIDs = append(c.MemberIDs, uid)
}
return &c, rows.Err()
}
// ListChats возвращает чаты пользователя с keyset-пагинацией по (created_at, id).
func (s *Store) ListChats(ctx context.Context, userID string, limit int, cursor string) ([]Chat, *string, error) {
var rows pgx.Rows
var err error
if cursor == "" {
rows, err = s.pool.Query(ctx,
`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
ORDER BY c.created_at, c.id
LIMIT $2`, userID, limit+1)
} else {
var cCreated time.Time
if err := s.pool.QueryRow(ctx,
`SELECT created_at FROM chats WHERE id=$1`, cursor,
).Scan(&cCreated); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil, ErrInvalid
}
return nil, nil, classifyDBError(err)
}
rows, err = s.pool.Query(ctx,
`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
AND (c.created_at, c.id) > ($2, $3)
ORDER BY c.created_at, c.id
LIMIT $4`, userID, cCreated, cursor, limit+1)
}
if err != nil {
return nil, nil, classifyDBError(err)
}
defer rows.Close()
var chats []Chat
for rows.Next() {
var c Chat
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
return nil, nil, classifyDBError(err)
}
chats = append(chats, c)
}
if err := rows.Err(); err != nil {
return nil, nil, classifyDBError(err)
}
var next *string
if len(chats) > limit {
chats = chats[:limit]
last := chats[len(chats)-1].ID
next = &last
}
if chats == nil {
chats = []Chat{}
}
// Догружаем участников.
for i := range chats {
mrows, err := s.pool.Query(ctx,
`SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id`, chats[i].ID)
if err != nil {
return nil, nil, classifyDBError(err)
}
for mrows.Next() {
var uid string
if err := mrows.Scan(&uid); err != nil {
mrows.Close()
return nil, nil, classifyDBError(err)
}
chats[i].MemberIDs = append(chats[i].MemberIDs, uid)
}
mrows.Close()
}
return chats, next, nil
}
// --- Messages ---
func (s *Store) AddMessage(ctx context.Context, chatID, senderID, text string) (*Message, error) {
// Проверка членства + вставка в одной транзакции.
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return nil, classifyDBError(err)
}
defer tx.Rollback(ctx)
var ok bool
if err := tx.QueryRow(ctx,
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
chatID, senderID,
).Scan(&ok); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, classifyDBError(err)
}
var m Message
var attach []string
err = tx.QueryRow(ctx,
`INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids)
VALUES ($1,$2,$3,$4,$5)
RETURNING id, chat_id, sender_id, text, created_at, attachment_ids`,
uuid.NewString(), chatID, senderID, text, []string{},
).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &attach)
if err != nil {
return nil, classifyDBError(err)
}
if err := tx.Commit(ctx); err != nil {
return nil, classifyDBError(err)
}
m.AttachmentIDs = attach
if m.AttachmentIDs == nil {
m.AttachmentIDs = []string{}
}
return &m, nil
}
// ListMessages — keyset-пагинация по (created_at, id).
// Курсор — это id последнего элемента предыдущей страницы; сам id уникален,
// поэтому используем его для поиска (created_at, id) в БД.
func (s *Store) ListMessages(ctx context.Context, chatID string, limit int, cursor string) ([]Message, *string, error) {
var rows pgx.Rows
var err error
if cursor == "" {
rows, err = s.pool.Query(ctx,
`SELECT id, chat_id, sender_id, text, created_at, attachment_ids
FROM messages
WHERE chat_id=$1
ORDER BY created_at, id
LIMIT $2`, chatID, limit+1)
} else {
// Определяем позицию курсора.
var cCreated time.Time
if err := s.pool.QueryRow(ctx,
`SELECT created_at FROM messages WHERE id=$1 AND chat_id=$2`,
cursor, chatID,
).Scan(&cCreated); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil, ErrInvalid
}
return nil, nil, classifyDBError(err)
}
rows, err = s.pool.Query(ctx,
`SELECT id, chat_id, sender_id, text, created_at, attachment_ids
FROM messages
WHERE chat_id=$1
AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT $4`, chatID, cCreated, cursor, limit+1)
}
if err != nil {
return nil, nil, classifyDBError(err)
}
defer rows.Close()
var items []Message
for rows.Next() {
var m Message
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
return nil, nil, classifyDBError(err)
}
if m.AttachmentIDs == nil {
m.AttachmentIDs = []string{}
}
items = append(items, m)
}
if err := rows.Err(); err != nil {
return nil, nil, classifyDBError(err)
}
var next *string
if len(items) > limit {
items = items[:limit]
last := items[len(items)-1].ID
next = &last
}
if items == nil {
items = []Message{}
}
return items, next, nil
}
func classifyDBError(err error) error {
if err == nil {
return nil
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch pgErr.Code {
case "57014": // query_canceled (statement_timeout)
return ErrTimeout
case "55P03": // lock_not_available (lock_timeout)
return ErrTimeout
case "40001": // serialization_failure
return ErrUnavailable
case "53300": // too_many_connections
return ErrUnavailable
case "22P02", "22007", "22023": // invalid_text_representation / invalid_datetime_format / invalid_parameter_value
return ErrInvalid
}
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return ErrTimeout
}
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound
}
return err
}
// AddMessageIdempotent — атомарно проверяет членство, вставляет сообщение
// и сохраняет результат идемпотентности в одной транзакции.
// Если ключ уже есть с тем же body — возвращает сохранённый ответ и replay=true.
func (s *Store) AddMessageIdempotent(
ctx context.Context,
chatID, senderID, text string,
attachmentIDs []string,
key, bodyHash string,
) (msg *Message, rec *IdempotencyRecord, replay bool, err error) {
path := "/api/v1/chats/" + chatID + "/messages"
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})
if err != nil {
return nil, nil, false, classifyDBError(err)
}
defer tx.Rollback(ctx)
// 1) Членство.
var ok bool
if err := tx.QueryRow(ctx,
`SELECT true FROM chat_members WHERE chat_id=$1 AND user_id=$2`,
chatID, senderID,
).Scan(&ok); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil, false, ErrNotFound
}
return nil, nil, false, classifyDBError(err)
}
// Вложения должны принадлежать этому чату и быть ready.
if len(attachmentIDs) > 10 {
return nil, nil, false, ErrInvalid
}
seen := map[string]bool{}
for _, aid := range attachmentIDs {
if seen[aid] {
return nil, nil, false, ErrInvalid
}
seen[aid] = true
var ok bool
if err := tx.QueryRow(ctx,
`SELECT true FROM attachments WHERE id=$1 AND chat_id=$2 AND status='ready'`,
aid, chatID).Scan(&ok); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil, false, ErrNotFound
}
return nil, nil, false, classifyDBError(err)
}
}
// 2) Уже был такой ключ?
var storedHash string
var storedStatus int
var storedResp json.RawMessage
err = tx.QueryRow(ctx,
`SELECT request_hash, status_code, response
FROM idempotency_keys
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
senderID, path, key,
).Scan(&storedHash, &storedStatus, &storedResp)
switch {
case err == nil:
if storedHash != bodyHash {
return nil, nil, false, ErrConflict
}
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
case !errors.Is(err, pgx.ErrNoRows):
return nil, nil, false, classifyDBError(err)
}
// 3) Вставка сообщения.
var m Message
var attach []string
err = tx.QueryRow(ctx,
`INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids)
VALUES ($1,$2,$3,$4,$5)
RETURNING id, chat_id, sender_id, text, created_at, attachment_ids`,
uuid.NewString(), chatID, senderID, text, attachmentIDs,
).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &attach)
if err != nil {
// Гонка на одном ключе в разных репликах: unique violation в idempotency_keys
// маловероятен здесь, но serialization failure возможен.
return nil, nil, false, classifyDBError(err)
}
m.AttachmentIDs = attach
if m.AttachmentIDs == nil {
m.AttachmentIDs = []string{}
}
// 4) Сохранение ответа.
respJSON, _ := json.Marshal(m)
_, err = tx.Exec(ctx,
`INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
VALUES ($1,'POST',$2,$3,$4,201,$5)`,
senderID, path, key, bodyHash, respJSON)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
// Кто-то параллельно успел вставить: перечитываем в этой же tx.
if err2 := tx.QueryRow(ctx,
`SELECT request_hash, status_code, response
FROM idempotency_keys
WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3`,
senderID, path, key,
).Scan(&storedHash, &storedStatus, &storedResp); err2 == nil {
if storedHash != bodyHash {
return nil, nil, false, ErrConflict
}
return nil, &IdempotencyRecord{StatusCode: storedStatus, Response: storedResp}, true, nil
}
}
return nil, nil, false, classifyDBError(err)
}
if err := tx.Commit(ctx); err != nil {
return nil, nil, false, classifyDBError(err)
}
return &m, nil, false, nil
}
+213
View File
@@ -0,0 +1,213 @@
package domain
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type S3Store struct {
client *minio.Client
bucket string
maxBytes int64
maxPixels int64
tr *http.Transport
}
func NewS3Store(ctx context.Context, endpoint, region, bucket, access, secret string, maxBytes, maxPixels int64) (*S3Store, error) {
if endpoint == "" || access == "" || secret == "" || bucket == "" {
return nil, errors.New("s3 configuration incomplete")
}
tr := &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 30 * time.Second,
DialContext: (&net.Dialer{
Timeout: 3 * time.Second, // Быстрый отказ при недоступности
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
}
cli, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(access, secret, ""),
Secure: strings.HasPrefix(endpoint, "https://"),
Region: region,
Transport: tr,
})
if err != nil {
return nil, err
}
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if _, err := cli.BucketExists(pingCtx, bucket); err != nil {
return nil, fmt.Errorf("s3 bucket check: %w", err)
}
return &S3Store{client: cli, bucket: bucket, maxBytes: maxBytes, maxPixels: maxPixels, tr: tr}, nil
}
type UploadResult struct {
ObjectKey string
ContentType string
SizeBytes int64
SHA256 string
Width int
Height int
}
// PutValidatedImage читает тело потоково во временный файл на диске,
// проверяет размер, MIME, пиксели и затем стримит в S3.
// Это гарантирует, что память не растёт с размером файла.
func (s *S3Store) PutValidatedImage(ctx context.Context, objectKey string, body io.Reader) (*UploadResult, error) {
// 1. Создаём временный файл.
tmpFile, err := os.CreateTemp("", "upload-*")
if err != nil {
return nil, err
}
tmpPath := tmpFile.Name()
defer func() {
tmpFile.Close()
os.Remove(tmpPath)
}()
// 2. Копируем тело в файл с ограничением.
limited := io.LimitReader(body, s.maxBytes+1)
size, err := io.Copy(tmpFile, limited)
if err != nil {
return nil, err
}
if size > s.maxBytes {
return nil, ErrTooLarge
}
if size == 0 {
return nil, ErrUnsupported
}
// 3. Проверяем MIME по первым 512 байтам.
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
return nil, err
}
header := make([]byte, 512)
n, err := io.ReadFull(tmpFile, header)
if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
return nil, err
}
header = header[:n]
ct := http.DetectContentType(header)
if ct != "image/png" && ct != "image/jpeg" {
return nil, ErrUnsupported
}
// 4. Проверяем заголовок изображения (размеры).
// DecodeConfig читает только начало, но мы используем файл, поэтому это безопасно.
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
return nil, err
}
cfg, _, err := image.DecodeConfig(tmpFile)
if err != nil {
return nil, ErrNotImage
}
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
return nil, ErrNotImage
}
// 5. Считаем SHA-256 и стримим файл в S3.
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
return nil, err
}
var hasher hash.Hash = sha256.New()
tee := io.TeeReader(tmpFile, hasher)
putCtx, cancelPut := context.WithTimeout(ctx, 5*time.Second)
defer cancelPut()
_, err = s.client.PutObject(putCtx, s.bucket, objectKey, tee, size,
minio.PutObjectOptions{ContentType: ct})
if err != nil {
return nil, err
}
sha := hex.EncodeToString(hasher.Sum(nil))
return &UploadResult{
ObjectKey: objectKey,
ContentType: ct,
SizeBytes: size,
SHA256: sha,
Width: cfg.Width,
Height: cfg.Height,
}, nil
}
func (s *S3Store) GetObject(ctx context.Context, objectKey string) (io.ReadCloser, string, int64, error) {
// Общий дедлайн на все попытки — 6 секунд.
overallCtx, overallCancel := context.WithTimeout(ctx, 6*time.Second)
defer overallCancel()
var lastErr error
for attempt := 0; attempt < 2; attempt++ {
if attempt > 0 {
time.Sleep(500 * time.Millisecond)
s.tr.CloseIdleConnections()
}
attemptCtx, cancel := context.WithTimeout(overallCtx, 3*time.Second)
obj, err := s.client.GetObject(attemptCtx, s.bucket, objectKey, minio.GetObjectOptions{})
if err != nil {
cancel()
lastErr = err
continue
}
info, err := obj.Stat()
if err != nil {
obj.Close()
cancel()
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
return nil, "", 0, ErrNotFound
}
lastErr = err
continue
}
data, err := io.ReadAll(obj)
obj.Close()
cancel()
if err != nil {
lastErr = err
continue
}
if int64(len(data)) != info.Size {
lastErr = fmt.Errorf("size mismatch: got %d, expected %d", len(data), info.Size)
continue
}
return io.NopCloser(bytes.NewReader(data)), info.ContentType, info.Size, nil
}
s.tr.CloseIdleConnections()
return nil, "", 0, fmt.Errorf("s3 get failed after retries: %w", lastErr)
}
func (s *S3Store) DeleteObject(ctx context.Context, objectKey string) error {
return s.client.RemoveObject(ctx, s.bucket, objectKey, minio.RemoveObjectOptions{})
}
+108
View File
@@ -0,0 +1,108 @@
package domain
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"time"
"github.com/jackc/pgx/v5"
)
type SessionStore struct {
store *Store
cache *SessionCache
ttl time.Duration
}
func NewSessionStore(store *Store, cache *SessionCache, ttl time.Duration) *SessionStore {
return &SessionStore{store: store, cache: cache, ttl: ttl}
}
func newToken() (string, error) {
b := make([]byte, 32) // 256 бит
if _, err := rand.Read(b); err != nil {
return "", classifyDBError(err)
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// Create — пишем сессию в БД (источник истины) и кэшируем публичные данные User.
func (s *SessionStore) Create(ctx context.Context, user User) (*Session, error) {
token, err := newToken()
if err != nil {
return nil, classifyDBError(err)
}
expires := time.Now().UTC().Add(s.ttl)
if _, err := s.store.pool.Exec(ctx,
`INSERT INTO sessions (token, user_id, expires_at) VALUES ($1,$2,$3)`,
token, user.ID, expires); err != nil {
return nil, classifyDBError(err)
}
if s.cache != nil {
s.cache.SetUser(ctx, user.ID, user, expires)
}
return &Session{
Token: token,
TokenType: "Bearer",
ExpiresAt: expires,
User: user,
}, nil
}
// Lookup ВСЕГДА обращается к PostgreSQL за фактом существования сессии.
// Кэш используется только для публичных данных User.
func (s *SessionStore) Lookup(ctx context.Context, token string) (*User, error) {
var (
userID string
expiresAt time.Time
)
err := s.store.pool.QueryRow(ctx,
`SELECT user_id, expires_at FROM sessions WHERE token=$1`, token,
).Scan(&userID, &expiresAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrUnauthorized
}
if err != nil {
return nil, classifyDBError(err)
}
if time.Now().UTC().After(expiresAt) {
_, _ = s.store.pool.Exec(ctx, `DELETE FROM sessions WHERE token=$1`, token)
return nil, ErrUnauthorized
}
if s.cache != nil {
if u, ok := s.cache.GetUser(ctx, userID); ok {
return &u, nil
}
}
u, err := s.store.GetUserByID(ctx, userID)
if err != nil {
return nil, ErrUnauthorized
}
if s.cache != nil {
s.cache.SetUser(ctx, userID, *u, expiresAt)
}
return u, nil
}
func (s *SessionStore) Revoke(ctx context.Context, token string) error {
var userID string
err := s.store.pool.QueryRow(ctx,
`DELETE FROM sessions WHERE token=$1 RETURNING user_id`, token,
).Scan(&userID)
if errors.Is(err, pgx.ErrNoRows) {
// Сессии уже нет — с точки зрения клиента токен отозван.
return nil
}
if err != nil {
return classifyDBError(err)
}
if s.cache != nil {
// Кэш User не критичен, но полезно сбросить.
_ = s.cache.DelUser(ctx, userID)
}
return nil
}