forked from mtusi2026/mtusi2026lab3
feat(app) lab 3 implemented
This commit is contained in:
@@ -5,15 +5,12 @@ import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
|
||||
"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"
|
||||
)
|
||||
|
||||
// CreateChat inserts the chat and every membership row in one transaction.
|
||||
// Any unknown member aborts the whole transaction, so a partially created chat
|
||||
// can never be observed.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
@@ -22,7 +19,7 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.U
|
||||
if err != nil {
|
||||
return model.Chat{}, dbError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
defer rollback(tx)
|
||||
|
||||
for _, memberID := range memberIDs {
|
||||
var exists int
|
||||
|
||||
@@ -5,25 +5,22 @@ import (
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
||||
pgErr, ok := errors.AsType[*pgconn.PgError](err)
|
||||
return ok && pgErr.Code == "23505"
|
||||
}
|
||||
|
||||
// dbError separates a drained dependency (503) from a real bug (500). SQL
|
||||
// details never reach the client; callers only emit the AppError message.
|
||||
func dbError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return common.Conflict("resource already exists")
|
||||
@@ -32,8 +29,7 @@ func dbError(err error) error {
|
||||
}
|
||||
}
|
||||
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) || errors.Is(err, context.DeadlineExceeded) ||
|
||||
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) {
|
||||
|
||||
@@ -1,21 +1,30 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
|
||||
"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"
|
||||
)
|
||||
|
||||
// CreateMessage uses INSERT ... SELECT so the membership check and the insert
|
||||
// are a single atomic statement: no window where the user is removed between
|
||||
// check and write. Zero affected rows means the chat is missing or foreign.
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (model.Message, error) {
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string) (model.Message, error) {
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
fingerprint := sha256.Sum256([]byte(text))
|
||||
|
||||
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,
|
||||
@@ -24,7 +33,13 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
CreatedAt: common.NowUTC(),
|
||||
}
|
||||
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`,
|
||||
@@ -36,9 +51,72 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
return model.Message{}, common.NotFound("chat not found")
|
||||
}
|
||||
|
||||
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 (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, 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, &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")
|
||||
}
|
||||
|
||||
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) {
|
||||
isMember, err := s.IsMember(ctx, userID, chatID)
|
||||
if err != nil {
|
||||
@@ -56,8 +134,6 @@ func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limi
|
||||
ctx, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
// AGENT: limit+1 is fetched so next_cursor is known to be non-null without a
|
||||
// second COUNT query; the extra row is never returned to the client.
|
||||
cursorTime, cursorID := cursorValues(cursor)
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
|
||||
@@ -3,7 +3,7 @@ package store
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
// parameterized SQL, one bounded pool and explicit transaction boundaries.
|
||||
// Contract errors are returned as common.AppError so HTTP status mapping stays
|
||||
// in one place.
|
||||
//
|
||||
// AGENT: Persistence was split from one large file by aggregate (users, chats,
|
||||
// messages). Queries, transaction boundaries and error mapping are unchanged;
|
||||
// only file organization and scan helpers changed.
|
||||
package store
|
||||
|
||||
import (
|
||||
@@ -16,12 +12,13 @@ import (
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
pool *pgxpool.Pool
|
||||
timeout time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, timeout time.Duration) *Store {
|
||||
return &Store{pool: pool, timeout: timeout}
|
||||
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) {
|
||||
@@ -34,7 +31,6 @@ func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.pool.Ping(pingCtx)
|
||||
}
|
||||
|
||||
// rowScanner is the common subset of pgx.Row and pgx.Rows used by scan helpers.
|
||||
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)
|
||||
}
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
|
||||
"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"
|
||||
)
|
||||
@@ -28,9 +28,6 @@ func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordH
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt))
|
||||
if err != nil {
|
||||
// AGENT: The unique index is the real guard. Two concurrent registrations
|
||||
// with the same username both reach INSERT; exactly one commits, the other
|
||||
// gets SQLSTATE 23505 and is mapped to 409 instead of a 500.
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, common.Conflict("username already taken")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user