forked from mtusi2026/mtusi2026lab6
192 lines
5.5 KiB
Go
192 lines
5.5 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"highload/internal/database/sqlc"
|
|
"highload/internal/model"
|
|
"highload/internal/repository"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type MessageRepository struct {
|
|
queries *sqlc.Queries
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewMessageRepository(queries *sqlc.Queries, pool *pgxpool.Pool) *MessageRepository {
|
|
return &MessageRepository{
|
|
queries: queries,
|
|
pool: pool,
|
|
}
|
|
}
|
|
|
|
func (r *MessageRepository) CreateMessage(ctx context.Context, chatID, senderID, text, key string, attachmentIDs []string) (*model.Message, error) {
|
|
chat, err := getUUIDFromString(chatID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sender, err := getUUIDFromString(senderID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ids := make([]pgtype.UUID, 0, len(attachmentIDs))
|
|
canonical := make([]string, 0, len(attachmentIDs))
|
|
for _, attachmentID := range attachmentIDs {
|
|
id, err := getUUIDFromString(attachmentID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ids = append(ids, *id)
|
|
canonical = append(canonical, id.String())
|
|
}
|
|
|
|
txCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
tx, err := r.pool.Begin(txCtx)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
defer rollbackTx(ctx, tx)
|
|
q := r.queries.WithTx(tx)
|
|
|
|
if err := q.LockMessageRequest(txCtx, sqlc.LockMessageRequestParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key}); err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
if err := q.DeleteExpiredMessageIdempotency(txCtx, sqlc.DeleteExpiredMessageIdempotencyParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key}); err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
message, err := q.GetIdempotentMessage(txCtx, sqlc.GetIdempotentMessageParams{UserID: *sender, ChatID: *chat, IdempotencyKey: key})
|
|
switch {
|
|
case err == nil:
|
|
rows, err := q.GetMessagesAttachments(txCtx, message.ID)
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
saved := make([]string, 0, len(rows))
|
|
for _, row := range rows {
|
|
saved = append(saved, row.AttachmentID.String())
|
|
}
|
|
if message.Text != text || !slices.Equal(saved, canonical) {
|
|
return nil, repository.ErrConflict
|
|
}
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
if len(ids) > 0 {
|
|
rows, err := q.LockAttachmentsForMessage(txCtx, sqlc.LockAttachmentsForMessageParams{ChatID: *chat, AttachmentIds: ids})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
if len(rows) != len(ids) {
|
|
return nil, repository.ErrNotFound
|
|
}
|
|
for _, row := range rows {
|
|
if row.Status == "failed" {
|
|
return nil, repository.ErrConflict
|
|
}
|
|
}
|
|
}
|
|
message, err = q.CreateMessage(txCtx, sqlc.CreateMessageParams{ChatID: *chat, SenderID: *sender, Text: text})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
for i, id := range ids {
|
|
n, err := q.CreateMessagesAttachments(txCtx, sqlc.CreateMessagesAttachmentsParams{
|
|
MessageID: message.ID, AttachmentID: id, ChatID: *chat, Position: int16(i),
|
|
})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
if n != 1 {
|
|
return nil, repository.ErrNotFound
|
|
}
|
|
}
|
|
n, err := q.InsertMessageIdempotency(txCtx, sqlc.InsertMessageIdempotencyParams{
|
|
UserID: *sender, ChatID: *chat, IdempotencyKey: key, MessageID: message.ID,
|
|
})
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
if n != 1 {
|
|
return nil, repository.ErrConflict
|
|
}
|
|
default:
|
|
return nil, convertDBError(err)
|
|
}
|
|
if err := tx.Commit(txCtx); err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
return &model.Message{
|
|
ID: message.ID.String(), ChatID: message.ChatID.String(), SenderID: message.SenderID.String(),
|
|
Text: message.Text, CreatedAt: message.CreatedAt.Time, AttachmentIDs: canonical,
|
|
}, nil
|
|
}
|
|
|
|
func (r *MessageRepository) GetMessagesByChatID(ctx context.Context, chatID string, limit int, after *repository.MessagePosition) ([]*model.Message, error) {
|
|
dbCtx, cancel := context.WithTimeout(ctx, time.Second)
|
|
defer cancel()
|
|
uuidChatID, err := getUUIDFromString(chatID)
|
|
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
afterCreatedAt := pgtype.Timestamptz{Valid: false}
|
|
afterID := pgtype.UUID{Valid: false}
|
|
|
|
if after != nil {
|
|
afterCreatedAt = pgtype.Timestamptz{Time: after.CreatedAt, Valid: true}
|
|
if uuidFromString, err := getUUIDFromString(after.ID); err == nil {
|
|
afterID = *uuidFromString
|
|
} else {
|
|
return nil, convertDBError(err)
|
|
}
|
|
}
|
|
|
|
sqlcMessages, err := r.queries.GetMessagesByChatID(dbCtx, sqlc.GetMessagesByChatIDParams{ChatID: *uuidChatID, AfterID: afterID, AfterCreatedAt: afterCreatedAt, LimitCount: int32(limit)})
|
|
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
messageIDs := make([]pgtype.UUID, len(sqlcMessages))
|
|
for index, _ := range sqlcMessages {
|
|
messageIDs[index] = sqlcMessages[index].ID
|
|
}
|
|
|
|
messageRow, err := r.queries.GetAttachmentsForMessages(dbCtx, messageIDs)
|
|
|
|
if err != nil {
|
|
return nil, convertDBError(err)
|
|
}
|
|
|
|
mapMessagesAtt := make(map[string][]string)
|
|
for index, _ := range messageRow {
|
|
messageID := messageRow[index].MessageID.String()
|
|
attachmentID := messageRow[index].AttachmentID.String()
|
|
|
|
mapMessagesAtt[messageID] = append(mapMessagesAtt[messageID], attachmentID)
|
|
|
|
}
|
|
|
|
messages := make([]*model.Message, len(sqlcMessages))
|
|
|
|
for index, sqlcMessage := range sqlcMessages {
|
|
messages[index] = &model.Message{
|
|
ID: sqlcMessage.ID.String(),
|
|
ChatID: sqlcMessage.ChatID.String(),
|
|
SenderID: sqlcMessage.SenderID.String(),
|
|
Text: sqlcMessage.Text,
|
|
AttachmentIDs: mapMessagesAtt[sqlcMessage.ID.String()],
|
|
CreatedAt: sqlcMessage.CreatedAt.Time}
|
|
}
|
|
|
|
return messages, nil
|
|
|
|
}
|