forked from mtusi2026/mtusi2026lab5
chore(migrate) moved codebase from lab4
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// CreatePendingAttachment records the intent to store an object before the S3
|
||||
// PUT happens. Committing this row first is what makes the reconciler able to
|
||||
// distinguish "never uploaded" from "uploaded but process died".
|
||||
func (s *Store) CreatePendingAttachment(ctx context.Context, att model.Attachment) error {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
hash, err := hex.DecodeString(att.SHA256)
|
||||
if err != nil {
|
||||
return common.BadRequest("invalid sha256")
|
||||
}
|
||||
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', NULL, $9, $9)`,
|
||||
att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType, att.SizeBytes,
|
||||
hash, att.ObjectKey, time.Time(att.CreatedAt))
|
||||
return dbError(err)
|
||||
}
|
||||
|
||||
// MarkAttachmentReady publishes metadata only after the object bytes are known
|
||||
// to be in S3. A 201 is therefore a promise about both stores.
|
||||
func (s *Store) MarkAttachmentReady(ctx context.Context, id uuid.UUID) (time.Time, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
updatedAt := time.Now().UTC()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = $2
|
||||
WHERE id = $1 AND status = 'pending'`, id, updatedAt)
|
||||
if err != nil {
|
||||
return time.Time{}, dbError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return time.Time{}, common.Conflict("attachment is not pending")
|
||||
}
|
||||
return updatedAt, nil
|
||||
}
|
||||
|
||||
// DeletePendingAttachment removes a row only while it is still pending. The
|
||||
// status guard is the safety property: if an upload completed concurrently, the
|
||||
// compensation or reconciler pass must not delete a ready attachment.
|
||||
func (s *Store) DeletePendingAttachment(ctx context.Context, id uuid.UUID) error {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM attachments WHERE id = $1 AND status = 'pending'`, id)
|
||||
return dbError(err)
|
||||
}
|
||||
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, userID, attachmentID uuid.UUID) (model.Attachment, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
att, err := scanAttachment(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, a.object_key
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1`, attachmentID, userID))
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
return att, nil
|
||||
}
|
||||
|
||||
// ListStalePendingAttachments is the entry point for crash recovery. cutoff is
|
||||
// an instant, not a duration: rows created before it are eligible. The caller
|
||||
// computes it as now - grace so the boundary can be tuned and tested.
|
||||
func (s *Store) ListStalePendingAttachments(ctx context.Context, cutoff time.Time, limit int) ([]model.Attachment, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(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, a.object_key
|
||||
FROM attachments a
|
||||
WHERE a.status = 'pending' AND a.created_at < $1
|
||||
ORDER BY a.created_at
|
||||
LIMIT $2`, cutoff, limit)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var result []model.Attachment
|
||||
for rows.Next() {
|
||||
att, scanErr := scanAttachment(rows)
|
||||
if scanErr != nil {
|
||||
return nil, dbError(scanErr)
|
||||
}
|
||||
result = append(result, att)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListAttachmentObjectKeys(ctx context.Context) (map[string]struct{}, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(ctx, `SELECT object_key FROM attachments`)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
keys := make(map[string]struct{})
|
||||
for rows.Next() {
|
||||
var key string
|
||||
if err = rows.Scan(&key); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
keys[key] = struct{}{}
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func scanAttachment(row rowScanner) (model.Attachment, error) {
|
||||
var (
|
||||
att model.Attachment
|
||||
hash []byte
|
||||
errCode *string
|
||||
createdAt time.Time
|
||||
updatedAt time.Time
|
||||
)
|
||||
|
||||
if err := row.Scan(
|
||||
&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType,
|
||||
&att.SizeBytes, &hash, &att.Status, &errCode,
|
||||
&createdAt, &updatedAt, &att.ObjectKey,
|
||||
); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, common.NotFound("attachment not found")
|
||||
}
|
||||
return model.Attachment{}, dbError(err)
|
||||
}
|
||||
|
||||
att.SHA256 = hex.EncodeToString(hash)
|
||||
att.ErrorCode = errCode
|
||||
att.Variants = []model.Variant{}
|
||||
att.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
att.UpdatedAt = common.RFCFormTime(updatedAt.UTC())
|
||||
return att, nil
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
var existing int
|
||||
if err = tx.QueryRow(ctx,
|
||||
`SELECT count(*) FROM users WHERE id = ANY($1::uuid[])`,
|
||||
memberIDs).Scan(&existing); err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
if existing != len(memberIDs) {
|
||||
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
if _, err = tx.Exec(ctx,
|
||||
`INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
|
||||
for _, memberID := range memberIDs {
|
||||
if _, err = tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
|
||||
chat.ID, memberID); err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return scanChat(s.pool.QueryRow(ctx, `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
|
||||
WHERE c.id = $1`, chatID, userID))
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
cursorTime, cursorID := cursorValues(cursor)
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
|
||||
WHERE (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats := make([]model.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
chat, scanErr := scanChat(rows)
|
||||
if scanErr != nil {
|
||||
return nil, scanErr
|
||||
}
|
||||
chats = append(chats, chat)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
|
||||
hasMore := len(chats) > limit
|
||||
if hasMore {
|
||||
chats = chats[:limit]
|
||||
}
|
||||
|
||||
return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil
|
||||
}
|
||||
|
||||
func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var exists int
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
|
||||
chatID, userID).Scan(&exists)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, dbError(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// scanChat owns the "row is missing" meaning for single-row lookups; list
|
||||
// queries never see ErrNoRows.
|
||||
func scanChat(row rowScanner) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, common.NotFound("chat not found")
|
||||
}
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
chat.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return chat, nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
pgErr, ok := errors.AsType[*pgconn.PgError](err)
|
||||
return ok && pgErr.Code == "23505"
|
||||
}
|
||||
|
||||
// dbError maps driver failures to contract errors. Unexpected failures are
|
||||
// logged with their cause so a 500 is never silent.
|
||||
func dbError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return common.Conflict("resource already exists")
|
||||
case "23503", "23514", "22P02":
|
||||
return common.BadRequest("request conflicts with stored data")
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := errors.AsType[net.Error](err); ok || errors.Is(err, context.DeadlineExceeded) ||
|
||||
errors.Is(err, context.Canceled) ||
|
||||
pgconn.SafeToRetry(err) ||
|
||||
errors.Is(err, pgx.ErrTxClosed) {
|
||||
return common.Unavailable("database unavailable")
|
||||
}
|
||||
|
||||
slog.Error("unhandled database error", "err", err)
|
||||
return common.Internal()
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string, attachmentIDs []uuid.UUID) (model.Message, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
// Sorting makes the idempotency fingerprint independent of the order
|
||||
// in which the client listed the same set of attachment IDs. The response
|
||||
// uses the same deterministic order.
|
||||
attachmentIDs = canonicalAttachmentIDs(attachmentIDs)
|
||||
fingerprint := messageFingerprint(text, attachmentIDs)
|
||||
|
||||
if message, found, err := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint); err != nil {
|
||||
return model.Message{}, err
|
||||
} else if found {
|
||||
return message, nil
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: common.NowUTC(),
|
||||
AttachmentIDs: attachmentIDs,
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
// Check membership and attachment ownership in the same transaction as the
|
||||
// insert. A foreign chat or a foreign attachment is intentionally the same
|
||||
// 404 as a missing object, so the API does not leak existence.
|
||||
var member int
|
||||
err = tx.QueryRow(ctx,
|
||||
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
|
||||
chatID, senderID).Scan(&member)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, common.NotFound("chat not found")
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
|
||||
if len(attachmentIDs) > 0 {
|
||||
rows, queryErr := tx.Query(ctx, `
|
||||
SELECT id, status FROM attachments
|
||||
WHERE chat_id = $1 AND id = ANY($2::uuid[])`, chatID, attachmentIDs)
|
||||
if queryErr != nil {
|
||||
return model.Message{}, dbError(queryErr)
|
||||
}
|
||||
|
||||
found := 0
|
||||
for rows.Next() {
|
||||
var (
|
||||
id uuid.UUID
|
||||
status string
|
||||
)
|
||||
if scanErr := rows.Scan(&id, &status); scanErr != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, dbError(scanErr)
|
||||
}
|
||||
found++
|
||||
if status != "ready" {
|
||||
rows.Close()
|
||||
return model.Message{}, common.Conflict("attachment is not ready")
|
||||
}
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
if found != len(attachmentIDs) {
|
||||
return model.Message{}, common.NotFound("attachment not found")
|
||||
}
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
message.ID, message.ChatID, message.SenderID, message.Text, time.Time(message.CreatedAt))
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
|
||||
for position, attachmentID := range attachmentIDs {
|
||||
if _, err = tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3)`, message.ID, attachmentID, position); err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
}
|
||||
|
||||
expiresAt := time.Time(message.CreatedAt).Add(s.idempotencyTTL)
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(sender_id, chat_id, idempotency_key, request_hash, message_id, created_at, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (sender_id, chat_id, idempotency_key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
message_id = EXCLUDED.message_id,
|
||||
created_at = EXCLUDED.created_at,
|
||||
expires_at = EXCLUDED.expires_at
|
||||
WHERE message_idempotency.expires_at <= now()`,
|
||||
senderID, chatID, idempotencyKey, fingerprint, message.ID,
|
||||
time.Time(message.CreatedAt), expiresAt)
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
|
||||
if tag.RowsAffected() == 0 {
|
||||
rollback(tx)
|
||||
stored, found, lookupErr := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint)
|
||||
if lookupErr != nil {
|
||||
return model.Message{}, lookupErr
|
||||
}
|
||||
if !found {
|
||||
return model.Message{}, common.Internal()
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func canonicalAttachmentIDs(ids []uuid.UUID) []uuid.UUID {
|
||||
result := append([]uuid.UUID(nil), ids...)
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return bytes.Compare(result[i][:], result[j][:]) < 0
|
||||
})
|
||||
if result == nil {
|
||||
return []uuid.UUID{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// messageFingerprint keeps the lab3 hash for messages without attachments, so
|
||||
// an idempotency key stored before this migration still replays correctly. For
|
||||
// messages with attachments the sorted IDs are part of the canonical body.
|
||||
func messageFingerprint(text string, attachmentIDs []uuid.UUID) []byte {
|
||||
if len(attachmentIDs) == 0 {
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
hash := sha256.New()
|
||||
hash.Write([]byte(text))
|
||||
hash.Write([]byte{0})
|
||||
for _, id := range attachmentIDs {
|
||||
hash.Write(id[:])
|
||||
}
|
||||
return hash.Sum(nil)
|
||||
}
|
||||
|
||||
func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid.UUID, idempotencyKey string, expectedHash []byte) (model.Message, bool, error) {
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
var storedHash []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
ORDER BY ma.position),
|
||||
i.request_hash
|
||||
FROM message_idempotency i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
JOIN chat_members cm ON cm.chat_id = i.chat_id AND cm.user_id = i.sender_id
|
||||
WHERE i.sender_id = $1
|
||||
AND i.chat_id = $2
|
||||
AND i.idempotency_key = $3
|
||||
AND i.expires_at > now()`,
|
||||
senderID, chatID, idempotencyKey).Scan(
|
||||
&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt,
|
||||
&message.AttachmentIDs, &storedHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, false, dbError(err)
|
||||
}
|
||||
if !bytes.Equal(storedHash, expectedHash) {
|
||||
return model.Message{}, false, common.Conflict("idempotency key reused with a different message")
|
||||
}
|
||||
if message.AttachmentIDs == nil {
|
||||
message.AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
|
||||
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return message, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
isMember, err := s.IsMember(ctx, userID, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !isMember {
|
||||
return nil, common.NotFound("chat not found")
|
||||
}
|
||||
// AGENT: Cursor context is checked only after membership, so a foreign
|
||||
// caller gets 404 and cannot probe cursor validity against someone else's chat.
|
||||
if cursor != nil && cursor.ContextID != chatID {
|
||||
return nil, common.BadRequest("bad cursor value")
|
||||
}
|
||||
|
||||
cursorTime, cursorID := cursorValues(cursor)
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
ORDER BY ma.position)
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4`, chatID, cursorTime, cursorID, limit+1)
|
||||
if err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages := make([]model.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
message, scanErr := scanMessage(rows)
|
||||
if scanErr != nil {
|
||||
return nil, dbError(scanErr)
|
||||
}
|
||||
messages = append(messages, message)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, dbError(err)
|
||||
}
|
||||
|
||||
hasMore := len(messages) > limit
|
||||
if hasMore {
|
||||
messages = messages[:limit]
|
||||
}
|
||||
|
||||
return &common.Page[model.Message]{
|
||||
Items: messages,
|
||||
NextCursor: common.NextCursor(messages, hasMore, chatID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func scanMessage(row rowScanner) (model.Message, error) {
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text,
|
||||
&createdAt, &message.AttachmentIDs); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if message.AttachmentIDs == nil {
|
||||
message.AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return message, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCanonicalAttachmentIDsSortsAndCopies(t *testing.T) {
|
||||
first, second, third := uuid.MustParse("00000000-0000-0000-0000-000000000003"),
|
||||
uuid.MustParse("00000000-0000-0000-0000-000000000001"),
|
||||
uuid.MustParse("00000000-0000-0000-0000-000000000002")
|
||||
|
||||
input := []uuid.UUID{first, second, third}
|
||||
got := canonicalAttachmentIDs(input)
|
||||
|
||||
want := []uuid.UUID{second, third, first}
|
||||
if !equalIDs(got, want) {
|
||||
t.Fatalf("canonicalAttachmentIDs = %v, want %v", got, want)
|
||||
}
|
||||
if !equalIDs(input, []uuid.UUID{first, second, third}) {
|
||||
t.Fatalf("canonicalAttachmentIDs mutated its input: %v", input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalAttachmentIDsReturnsEmptySliceForNil(t *testing.T) {
|
||||
got := canonicalAttachmentIDs(nil)
|
||||
if got == nil {
|
||||
t.Fatal("canonicalAttachmentIDs(nil) = nil, want empty slice")
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("canonicalAttachmentIDs(nil) = %v, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessageFingerprintWithoutAttachmentsPreservesLab3Hash is the
|
||||
// compatibility guard: idempotency rows written before attachments existed
|
||||
// must still match on replay.
|
||||
func TestMessageFingerprintWithoutAttachmentsPreservesLab3Hash(t *testing.T) {
|
||||
expected := sha256.Sum256([]byte("hello"))
|
||||
if got := messageFingerprint("hello", nil); !bytes.Equal(got, expected[:]) {
|
||||
t.Fatalf("fingerprint = %x, want %x", got, expected)
|
||||
}
|
||||
if got := messageFingerprint("hello", []uuid.UUID{}); !bytes.Equal(got, expected[:]) {
|
||||
t.Fatalf("empty slice fingerprint = %x, want %x", got, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageFingerprintDependsOnSortedAttachments(t *testing.T) {
|
||||
first := uuid.MustParse("00000000-0000-0000-0000-000000000001")
|
||||
second := uuid.MustParse("00000000-0000-0000-0000-000000000002")
|
||||
|
||||
// CreateMessage canonicalizes before hashing; the pair must therefore be
|
||||
// order independent even though messageFingerprint itself takes the list
|
||||
// as given.
|
||||
one := messageFingerprint("hello", canonicalAttachmentIDs([]uuid.UUID{first, second}))
|
||||
reordered := messageFingerprint("hello", canonicalAttachmentIDs([]uuid.UUID{second, first}))
|
||||
if !bytes.Equal(one, reordered) {
|
||||
t.Fatal("fingerprint depends on attachment order")
|
||||
}
|
||||
|
||||
other := messageFingerprint("hello", canonicalAttachmentIDs([]uuid.UUID{first}))
|
||||
if bytes.Equal(one, other) {
|
||||
t.Fatal("fingerprint ignores attachment identity")
|
||||
}
|
||||
}
|
||||
|
||||
func equalIDs(a, b []uuid.UUID) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for index := range a {
|
||||
if a[index] != b[index] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// cursorValues converts an optional page cursor to the two keyset columns used
|
||||
// by every paginated query. A nil cursor means "start from the beginning".
|
||||
func cursorValues(cursor *common.CursorKeyCtx) (time.Time, uuid.UUID) {
|
||||
if cursor == nil {
|
||||
return time.Time{}, uuid.Nil
|
||||
}
|
||||
return cursor.Time, cursor.ID
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Package store contains the PostgreSQL persistence layer. It uses plain
|
||||
// parameterized SQL, one bounded pool and explicit transaction boundaries.
|
||||
// Contract errors are returned as common.AppError so HTTP status mapping stays
|
||||
// in one place.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, timeout, idempotencyTTL time.Duration) *Store {
|
||||
return &Store{pool: pool, timeout: timeout, idempotencyTTL: idempotencyTTL}
|
||||
}
|
||||
|
||||
func (s *Store) withTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.timeout)
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
return s.pool.Ping(pingCtx)
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const rollbackTimeout = 5 * time.Second
|
||||
|
||||
func rollback(tx pgx.Tx) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), rollbackTimeout)
|
||||
defer cancel()
|
||||
_ = tx.Rollback(ctx)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := model.User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
PasswordHash: passwordHash,
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt))
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, common.Conflict("username already taken")
|
||||
}
|
||||
return model.User{}, dbError(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.scanUser(s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.scanUser(s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users WHERE username = $1`, username))
|
||||
}
|
||||
|
||||
func (s *Store) scanUser(row rowScanner) (model.User, error) {
|
||||
var user model.User
|
||||
var createdAt time.Time
|
||||
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, common.NotFound("user not found")
|
||||
}
|
||||
return model.User{}, dbError(err)
|
||||
}
|
||||
user.CreatedAt = common.RFCFormTime(createdAt.UTC())
|
||||
return user, nil
|
||||
}
|
||||
Reference in New Issue
Block a user