forked from mtusi2026/mtusi2026lab4
lab4 - оценка 4
This commit is contained in:
@@ -0,0 +1,718 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab4-fork/src/internal/model"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("invalid_request")
|
||||
ErrNotFound = errors.New("not_found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
const migrationAdvisoryLockID int64 = 7272727272727272
|
||||
|
||||
type Store interface {
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (*model.User, error)
|
||||
GetUserByID(ctx context.Context, id string) (*model.User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (*model.User, error)
|
||||
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error)
|
||||
GetChat(ctx context.Context, chatID, userID string) (*model.Chat, error)
|
||||
ListChats(ctx context.Context, userID string, limit int, cursor string) ([]*model.Chat, *string, error)
|
||||
|
||||
AddMessage(ctx context.Context, chatID, senderID, text string) (*model.Message, error)
|
||||
SendMessageIdempotent(ctx context.Context, chatID, senderID, text string, attachmentIDs []string, idemKey, path, requestHash string) (*model.Message, error)
|
||||
GetMessages(ctx context.Context, chatID, userID, cursor string, limit int) ([]*model.Message, *string, error)
|
||||
|
||||
CreateSession(ctx context.Context, userID, tokenHash string, expiresAt time.Time) (*model.Session, error)
|
||||
GetSession(ctx context.Context, tokenHash string) (*model.Session, error)
|
||||
DeleteSession(ctx context.Context, tokenHash string) error
|
||||
|
||||
CreateAttachmentUploading(ctx context.Context, chatID, ownerID, filename, objectKey, contentType string, sizeBytes int64, sha256Hex string) (*model.Attachment, error)
|
||||
MarkAttachmentReady(ctx context.Context, id string) (*model.Attachment, error)
|
||||
DeleteAttachmentUploading(ctx context.Context, id string) error
|
||||
GetAttachmentForUser(ctx context.Context, attachmentID, userID string) (*model.Attachment, error)
|
||||
ClaimStaleUploading(ctx context.Context, olderThan time.Time) ([]model.Attachment, error)
|
||||
DeleteFailedStaleAttachment(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
type PostgresStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewPostgres(connString string) (*PostgresStore, error) {
|
||||
config, err := pgxpool.ParseConfig(connString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
config.MaxConns = 25
|
||||
config.MinConns = 5
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
store := &PostgresStore{pool: pool}
|
||||
if err := store.applyMigrations(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("apply migrations: %w", err)
|
||||
}
|
||||
|
||||
return store, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
func (s *PostgresStore) applyMigrations(ctx context.Context) error {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("acquire conn for lock: %w", err)
|
||||
}
|
||||
defer conn.Release()
|
||||
|
||||
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, migrationAdvisoryLockID); err != nil {
|
||||
return fmt.Errorf("advisory lock: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, migrationAdvisoryLockID)
|
||||
}()
|
||||
|
||||
_, err = conn.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create migrations table: %w", err)
|
||||
}
|
||||
|
||||
var lastVersion int
|
||||
err = conn.QueryRow(ctx, `SELECT COALESCE(MAX(version), 0) FROM schema_migrations`).Scan(&lastVersion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get last version: %w", err)
|
||||
}
|
||||
|
||||
entries, err := migrationsFS.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migrations: %w", err)
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(entry.Name(), "%d_", &version); err != nil {
|
||||
continue
|
||||
}
|
||||
if version <= lastVersion {
|
||||
log.Printf("INFO: Skipping migration %s (already applied)", entry.Name())
|
||||
continue
|
||||
}
|
||||
content, err := migrationsFS.ReadFile("migrations/" + entry.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("read migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, string(content)); err != nil {
|
||||
return fmt.Errorf("execute migration %s: %w", entry.Name(), err)
|
||||
}
|
||||
if _, err := conn.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, version); err != nil {
|
||||
return fmt.Errorf("insert migration version: %w", err)
|
||||
}
|
||||
log.Printf("INFO: Applied migration %s", entry.Name())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (*model.User, error) {
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO users (username, display_name, password_hash) VALUES ($1, $2, $3) RETURNING id, username, display_name, created_at`, username, displayName, passwordHash).
|
||||
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
return nil, fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetUserByID(ctx context.Context, id string) (*model.User, error) {
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1`, id).
|
||||
Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &user.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetUserByUsername(ctx context.Context, username string) (*model.User, error) {
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1`, username).
|
||||
Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &user.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get user by username: %w", err)
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateChat(ctx context.Context, title string, memberIDs []string) (*model.Chat, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var chat model.Chat
|
||||
if err := tx.QueryRow(ctx, `INSERT INTO chats (title) VALUES ($1) RETURNING id, created_at`, title).Scan(&chat.ID, &chat.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
for _, userID := range memberIDs {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, chat.ID, userID); err != nil {
|
||||
return nil, fmt.Errorf("insert member %s: %w", userID, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
|
||||
chat.Title = title
|
||||
chat.MemberIDs = memberIDs
|
||||
if chat.MemberIDs == nil {
|
||||
chat.MemberIDs = []string{}
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return &chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetChat(ctx context.Context, chatID, userID string) (*model.Chat, error) {
|
||||
var isMember bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, chatID, userID).Scan(&isMember); err != nil {
|
||||
return nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
var chat model.Chat
|
||||
if err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID).Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
chat.MemberIDs = []string{}
|
||||
|
||||
rows, err := s.pool.Query(ctx, `SELECT user_id FROM chat_members WHERE chat_id = $1`, chatID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get members: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var m string
|
||||
if err := rows.Scan(&m); err != nil {
|
||||
return nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
chat.MemberIDs = append(chat.MemberIDs, m)
|
||||
}
|
||||
return &chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ListChats(ctx context.Context, userID string, limit int, cursor string) ([]*model.Chat, *string, error) {
|
||||
fetchLimit := limit + 1
|
||||
var query string
|
||||
var args []interface{}
|
||||
|
||||
if cursor == "" {
|
||||
query = `SELECT c.id, c.title, c.created_at FROM chats c INNER JOIN chat_members cm ON cm.chat_id = c.id WHERE cm.user_id = $1 ORDER BY c.created_at, c.id LIMIT $2`
|
||||
args = []interface{}{userID, fetchLimit}
|
||||
} else {
|
||||
// Используем подзапрос для точного сравнения кортежей без участия Go
|
||||
query = `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
INNER JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1
|
||||
AND (c.created_at, c.id) > (
|
||||
SELECT c2.created_at, c2.id FROM chats c2 WHERE c2.id = $2
|
||||
)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $3
|
||||
`
|
||||
args = []interface{}{userID, cursor, fetchLimit}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("query chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var chats []*model.Chat
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan chat: %w", err)
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
chat.MemberIDs = []string{}
|
||||
chats = append(chats, &chat)
|
||||
}
|
||||
|
||||
if len(chats) > 0 {
|
||||
ids := make([]string, len(chats))
|
||||
for i, c := range chats {
|
||||
ids[i] = c.ID
|
||||
}
|
||||
mrows, err := s.pool.Query(ctx, `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1::uuid[])`, ids)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("query members: %w", err)
|
||||
}
|
||||
defer mrows.Close()
|
||||
mm := make(map[string][]string)
|
||||
for mrows.Next() {
|
||||
var cid, mid string
|
||||
if err := mrows.Scan(&cid, &mid); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan member: %w", err)
|
||||
}
|
||||
mm[cid] = append(mm[cid], mid)
|
||||
}
|
||||
for _, c := range chats {
|
||||
if members, ok := mm[c.ID]; ok {
|
||||
c.MemberIDs = members
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if len(chats) > limit {
|
||||
chats = chats[:limit]
|
||||
lastID := chats[len(chats)-1].ID
|
||||
nextCursor = &lastID
|
||||
}
|
||||
if chats == nil {
|
||||
chats = []*model.Chat{}
|
||||
}
|
||||
return chats, nextCursor, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) AddMessage(ctx context.Context, chatID, senderID, text string) (*model.Message, error) {
|
||||
return s.insertMessage(ctx, chatID, senderID, text)
|
||||
}
|
||||
|
||||
func (s *PostgresStore) SendMessageIdempotent(ctx context.Context, chatID, senderID, text string, attachmentIDs []string, idemKey, path, requestHash string) (*model.Message, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
if len(attachmentIDs) > 10 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
if utf8.RuneCountInString(text) > 4000 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(attachmentIDs))
|
||||
for _, id := range attachmentIDs {
|
||||
if _, exists := seen[id]; exists {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
scope := fmt.Sprintf("%s|%s|%s|%s", senderID, "POST", path, idemKey)
|
||||
lockID := hashScope(scope)
|
||||
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockID); err != nil {
|
||||
return nil, fmt.Errorf("advisory xact lock: %w", err)
|
||||
}
|
||||
|
||||
var existingHash string
|
||||
var existingBody []byte
|
||||
err = tx.QueryRow(ctx, `SELECT request_hash, response_body FROM idempotency_keys WHERE user_id = $1 AND method = $2 AND path = $3 AND key = $4`, senderID, "POST", path, idemKey).Scan(&existingHash, &existingBody)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
if existingHash != requestHash {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
var msg model.Message
|
||||
if err := json.Unmarshal(existingBody, &msg); err != nil {
|
||||
return nil, fmt.Errorf("decode replay body: %w", err)
|
||||
}
|
||||
if msg.AttachmentIDs == nil {
|
||||
msg.AttachmentIDs = []string{}
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
return &msg, nil
|
||||
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
for _, attID := range attachmentIDs {
|
||||
var attChatID string
|
||||
var status string
|
||||
qerr := tx.QueryRow(ctx, `SELECT chat_id::text, status FROM attachments WHERE id = $1`, attID).Scan(&attChatID, &status)
|
||||
if qerr != nil {
|
||||
if errors.Is(qerr, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if isUUIDSyntaxError(qerr) {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
return nil, fmt.Errorf("select attachment: %w", qerr)
|
||||
}
|
||||
if attChatID != chatID {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if status != "ready" {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
}
|
||||
|
||||
msg, err := s.insertMessageTx(ctx, tx, chatID, senderID, text)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msg.AttachmentIDs = attachmentIDs
|
||||
|
||||
for i, attID := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1, $2, $3)`, msg.ID, attID, i); err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
return nil, fmt.Errorf("insert message attachment: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
body, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal message: %w", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, response_code, response_body) VALUES ($1, $2, $3, $4, $5, $6, $7)`, senderID, "POST", path, idemKey, requestHash, 201, body); err != nil {
|
||||
return nil, fmt.Errorf("insert idempotency key: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, fmt.Errorf("commit tx: %w", err)
|
||||
}
|
||||
return msg, nil
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("select idempotency key: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresStore) insertMessage(ctx context.Context, chatID, senderID, text string) (*model.Message, error) {
|
||||
var isMember bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, chatID, senderID).Scan(&isMember); err != nil {
|
||||
return nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
var msg model.Message
|
||||
if err := s.pool.QueryRow(ctx, `INSERT INTO messages (chat_id, sender_id, text) VALUES ($1, $2, $3) RETURNING id, chat_id, sender_id, text, created_at`, chatID, senderID, text).Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
msg.AttachmentIDs = []string{}
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) insertMessageTx(ctx context.Context, tx pgx.Tx, chatID, senderID, text string) (*model.Message, error) {
|
||||
var isMember bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, chatID, senderID).Scan(&isMember); err != nil {
|
||||
return nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
var msg model.Message
|
||||
if err := tx.QueryRow(ctx, `INSERT INTO messages (chat_id, sender_id, text) VALUES ($1, $2, $3) RETURNING id, chat_id, sender_id, text, created_at`, chatID, senderID, text).Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
msg.AttachmentIDs = []string{}
|
||||
return &msg, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetMessages(ctx context.Context, chatID, userID, cursor string, limit int) ([]*model.Message, *string, error) {
|
||||
var isMember bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, chatID, userID).Scan(&isMember); err != nil {
|
||||
return nil, nil, fmt.Errorf("check membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return nil, nil, ErrNotFound
|
||||
}
|
||||
|
||||
fetchLimit := limit + 1
|
||||
var query string
|
||||
var args []interface{}
|
||||
|
||||
if cursor == "" {
|
||||
query = `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ORDER BY created_at, id LIMIT $2`
|
||||
args = []interface{}{chatID, fetchLimit}
|
||||
} else {
|
||||
// Используем подзапрос, чтобы избежать потери точности времени при передаче через Go
|
||||
query = `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > (
|
||||
SELECT created_at, id FROM messages WHERE id = $2 AND chat_id = $1
|
||||
)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $3
|
||||
`
|
||||
args = []interface{}{chatID, cursor, fetchLimit}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("query messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var messages []*model.Message
|
||||
for rows.Next() {
|
||||
var msg model.Message
|
||||
if err := rows.Scan(&msg.ID, &msg.ChatID, &msg.SenderID, &msg.Text, &msg.CreatedAt); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan message: %w", err)
|
||||
}
|
||||
msg.CreatedAt = msg.CreatedAt.UTC()
|
||||
msg.AttachmentIDs = []string{}
|
||||
messages = append(messages, &msg)
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if len(messages) > limit {
|
||||
messages = messages[:limit]
|
||||
lastID := messages[len(messages)-1].ID
|
||||
nextCursor = &lastID
|
||||
}
|
||||
if messages == nil {
|
||||
messages = []*model.Message{}
|
||||
}
|
||||
|
||||
if len(messages) > 0 {
|
||||
ids := make([]string, len(messages))
|
||||
for i, m := range messages {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
arows, err := s.pool.Query(ctx, `SELECT message_id::text, attachment_id::text FROM message_attachments WHERE message_id = ANY($1::uuid[]) ORDER BY message_id, position`, ids)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("query message attachments: %w", err)
|
||||
}
|
||||
defer arows.Close()
|
||||
|
||||
byMessage := make(map[string][]string)
|
||||
for arows.Next() {
|
||||
var msgID, attID string
|
||||
if err := arows.Scan(&msgID, &attID); err != nil {
|
||||
return nil, nil, fmt.Errorf("scan message attachment: %w", err)
|
||||
}
|
||||
byMessage[msgID] = append(byMessage[msgID], attID)
|
||||
}
|
||||
if err := arows.Err(); err != nil {
|
||||
return nil, nil, fmt.Errorf("message attachments rows: %w", err)
|
||||
}
|
||||
for _, m := range messages {
|
||||
if atts, ok := byMessage[m.ID]; ok && len(atts) > 0 {
|
||||
m.AttachmentIDs = atts
|
||||
} else {
|
||||
m.AttachmentIDs = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
return messages, nextCursor, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateSession(ctx context.Context, userID, tokenHash string, expiresAt time.Time) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := s.pool.QueryRow(ctx, `INSERT INTO sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3) RETURNING id, user_id, token_hash, expires_at, created_at`, userID, tokenHash, expiresAt).Scan(&session.ID, &session.UserID, &session.TokenHash, &session.ExpiresAt, &session.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
session.ExpiresAt = session.ExpiresAt.UTC()
|
||||
session.CreatedAt = session.CreatedAt.UTC()
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetSession(ctx context.Context, tokenHash string) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := s.pool.QueryRow(ctx, `SELECT id, user_id, token_hash, expires_at, created_at FROM sessions WHERE token_hash = $1 AND expires_at > NOW()`, tokenHash).Scan(&session.ID, &session.UserID, &session.TokenHash, &session.ExpiresAt, &session.CreatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("get session: %w", err)
|
||||
}
|
||||
session.ExpiresAt = session.ExpiresAt.UTC()
|
||||
session.CreatedAt = session.CreatedAt.UTC()
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) DeleteSession(ctx context.Context, tokenHash string) error {
|
||||
if _, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash = $1`, tokenHash); err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateAttachmentUploading(ctx context.Context, chatID, ownerID, filename, objectKey, contentType string, sizeBytes int64, sha256Hex string) (*model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO attachments (chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, status) VALUES ($1, $2, $3, $4, $5, $6, $7, 'uploading') RETURNING id::text, chat_id::text, owner_id::text, filename, object_key, content_type, size_bytes, sha256, status, error_code, created_at, updated_at`, chatID, ownerID, filename, objectKey, contentType, sizeBytes, sha256Hex).
|
||||
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
if isForeignKeyViolation(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("insert attachment uploading: %w", err)
|
||||
}
|
||||
a.CreatedAt = a.CreatedAt.UTC()
|
||||
a.UpdatedAt = a.UpdatedAt.UTC()
|
||||
a.Variants = []any{}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) MarkAttachmentReady(ctx context.Context, id string) (*model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
err := s.pool.QueryRow(ctx, `UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = NOW() WHERE id = $1 AND status = 'uploading' RETURNING id::text, chat_id::text, owner_id::text, filename, object_key, content_type, size_bytes, sha256, status, error_code, created_at, updated_at`, id).
|
||||
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
a.CreatedAt = a.CreatedAt.UTC()
|
||||
a.UpdatedAt = a.UpdatedAt.UTC()
|
||||
a.Variants = []any{}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) DeleteAttachmentUploading(ctx context.Context, id string) error {
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1 AND status = 'uploading'`, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete attachment uploading: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) GetAttachmentForUser(ctx context.Context, attachmentID, userID string) (*model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
err := s.pool.QueryRow(ctx, `SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename, a.object_key, 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 cm ON cm.chat_id = a.chat_id WHERE a.id = $1 AND cm.user_id = $2 AND a.status = 'ready'`, attachmentID, userID).
|
||||
Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if isUUIDSyntaxError(err) {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
return nil, fmt.Errorf("get attachment for user: %w", err)
|
||||
}
|
||||
a.CreatedAt = a.CreatedAt.UTC()
|
||||
a.UpdatedAt = a.UpdatedAt.UTC()
|
||||
a.Variants = []any{}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ClaimStaleUploading(ctx context.Context, olderThan time.Time) ([]model.Attachment, error) {
|
||||
rows, err := s.pool.Query(ctx, `UPDATE attachments SET status = 'failed', error_code = 'stale_upload', updated_at = NOW() WHERE status = 'uploading' AND created_at < $1 RETURNING id::text, object_key`, olderThan)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("claim stale uploading: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []model.Attachment
|
||||
for rows.Next() {
|
||||
var a model.Attachment
|
||||
if err := rows.Scan(&a.ID, &a.ObjectKey); err != nil {
|
||||
return nil, fmt.Errorf("scan claimed attachment: %w", err)
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PostgresStore) DeleteFailedStaleAttachment(ctx context.Context, id string) error {
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1 AND status = 'failed' AND error_code = 'stale_upload'`, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete failed stale attachment: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hashScope(s string) int64 {
|
||||
h := sha256.Sum256([]byte(s))
|
||||
return int64(binary.BigEndian.Uint64(h[:8]))
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
return err != nil && (contains(err.Error(), "23505") || contains(err.Error(), "duplicate key") || contains(err.Error(), "unique constraint"))
|
||||
}
|
||||
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
return err != nil && (contains(err.Error(), "23503") || contains(err.Error(), "violates foreign key"))
|
||||
}
|
||||
|
||||
func isUUIDSyntaxError(err error) bool {
|
||||
return err != nil && contains(err.Error(), "invalid input syntax for type uuid")
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i+len(substr) <= len(s); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user