forked from mtusi2026/mtusi2026lab4
lab 4 na 4
This commit is contained in:
+146
-26
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
@@ -21,10 +22,13 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username taken")
|
||||
ErrChatNotFound = errors.New("chat not found or not accessible")
|
||||
ErrValidation = errors.New("validation failed")
|
||||
ErrCapacityExceeded = errors.New("message capacity exceeded")
|
||||
ErrUsernameTaken = errors.New("username taken")
|
||||
ErrChatNotFound = errors.New("chat not found or not accessible")
|
||||
ErrValidation = errors.New("validation failed")
|
||||
ErrCapacityExceeded = errors.New("message capacity exceeded")
|
||||
ErrAttachmentNotFound = errors.New("attachment not found or not accessible")
|
||||
ErrUsernameNotFound = errors.New("username not found")
|
||||
ErrSessionNotFound = errors.New("session not found or expired")
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
@@ -33,10 +37,102 @@ type Store struct {
|
||||
chatSQLQueries atomic.Int64
|
||||
}
|
||||
|
||||
func (s *Store) ResetChatSQLQueries() {
|
||||
s.chatSQLQueries.Store(0)
|
||||
}
|
||||
|
||||
func (s *Store) ChatSQLQueries() int64 {
|
||||
return s.chatSQLQueries.Load()
|
||||
}
|
||||
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
|
||||
RETURNING status, created_at, updated_at`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey,
|
||||
).Scan(&a.Status, &a.CreatedAt, &a.UpdatedAt)
|
||||
a.Variants = []model.Variant{}
|
||||
return a, err
|
||||
}
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID string) (model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
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.object_key, a.status, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1`, id, userID,
|
||||
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
|
||||
&a.ObjectKey, &a.Status, &a.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
a.Variants = []model.Variant{}
|
||||
return a, err
|
||||
}
|
||||
|
||||
func (s *Store) loadAttachmentIDs(ctx context.Context, msgs []model.Message) error {
|
||||
if len(msgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, len(msgs))
|
||||
pos := make(map[string]int, len(msgs))
|
||||
for i := range msgs {
|
||||
ids[i] = msgs[i].ID
|
||||
pos[msgs[i].ID] = i
|
||||
msgs[i].AttachmentIDs = []string{}
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT message_id, attachment_id FROM message_attachments
|
||||
WHERE message_id IN (SELECT unnest($1::text[])::uuid)
|
||||
ORDER BY message_id, position`, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var mid, aid string
|
||||
if err := rows.Scan(&mid, &aid); err != nil {
|
||||
return err
|
||||
}
|
||||
if i, ok := pos[mid]; ok {
|
||||
msgs[i].AttachmentIDs = append(msgs[i].AttachmentIDs, aid)
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, limiter *Limiter) *Store {
|
||||
return &Store{pool: pool, Limiter: limiter}
|
||||
}
|
||||
|
||||
func txAttachmentIDs(ctx context.Context, tx pgx.Tx, messageID string) ([]string, error) {
|
||||
rows, err := tx.Query(ctx,
|
||||
`SELECT attachment_id FROM message_attachments WHERE message_id = $1 ORDER BY position`, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
var u model.User
|
||||
err := s.pool.QueryRow(ctx,
|
||||
@@ -238,12 +334,14 @@ func (s *Store) ListChatsForUser(ctx context.Context, userID, cursorStr string,
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key reused with different body")
|
||||
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, text string) (model.Message, error) {
|
||||
if !validMessageText(text) {
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, text string, attIDs []string) (model.Message, error) {
|
||||
if attIDs == nil {
|
||||
attIDs = []string{}
|
||||
}
|
||||
if !ValidMessageBody(text, len(attIDs) > 0) {
|
||||
return model.Message{}, ErrValidation
|
||||
}
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
hash := requestHash(text, attIDs)
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -261,6 +359,19 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, te
|
||||
return model.Message{}, ErrChatNotFound
|
||||
}
|
||||
|
||||
if len(attIDs) > 0 {
|
||||
var n int
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT count(*) FROM attachments
|
||||
WHERE chat_id = $1 AND id IN (SELECT unnest($2::text[])::uuid)`,
|
||||
chatID, attIDs).Scan(&n); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if n != len(attIDs) {
|
||||
return model.Message{}, ErrAttachmentNotFound
|
||||
}
|
||||
}
|
||||
|
||||
msgID := idgen.GenerateUUIDv4()
|
||||
tag, err := tx.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
@@ -274,18 +385,20 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, te
|
||||
if tag.RowsAffected() == 0 {
|
||||
var storedHash string
|
||||
var m model.Message
|
||||
err := tx.QueryRow(ctx,
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3`,
|
||||
senderID, chatID, idemKey,
|
||||
).Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||
if err != nil {
|
||||
).Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if storedHash != hash {
|
||||
return model.Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
if m.AttachmentIDs, err = txAttachmentIDs(ctx, tx, m.ID); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
@@ -302,9 +415,17 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, te
|
||||
}
|
||||
return model.Message{}, err
|
||||
}
|
||||
for i, id := range attIDs {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1,$2,$3)`,
|
||||
m.ID, id, i); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
m.AttachmentIDs = attIDs
|
||||
return m, nil
|
||||
}
|
||||
|
||||
@@ -368,6 +489,9 @@ func (s *Store) ListMessages(ctx context.Context, chatID, userID, cursorStr stri
|
||||
next = &nc
|
||||
page = page[:limit]
|
||||
}
|
||||
if err := s.loadAttachmentIDs(ctx, page); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
@@ -386,9 +510,8 @@ func isCheckViolation(err error) bool {
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23514"
|
||||
}
|
||||
|
||||
func validMessageText(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
if n == 0 || n > 4000 {
|
||||
func ValidMessageBody(s string, hasAttachments bool) bool {
|
||||
if utf8.RuneCountInString(s) > 4000 {
|
||||
return false
|
||||
}
|
||||
hasContent := false
|
||||
@@ -400,10 +523,17 @@ func validMessageText(s string) bool {
|
||||
hasContent = true
|
||||
}
|
||||
}
|
||||
return hasContent
|
||||
return hasAttachments || hasContent
|
||||
}
|
||||
|
||||
var ErrSessionNotFound = errors.New("session not found or expired")
|
||||
func requestHash(text string, ids []string) string {
|
||||
b, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{text, ids})
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
||||
var u model.User
|
||||
@@ -424,13 +554,3 @@ func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.U
|
||||
|
||||
return u, passwordHash, nil
|
||||
}
|
||||
|
||||
var ErrUsernameNotFound = errors.New("username not found")
|
||||
|
||||
func (s *Store) ResetChatSQLQueries() {
|
||||
s.chatSQLQueries.Store(0)
|
||||
}
|
||||
|
||||
func (s *Store) ChatSQLQueries() int64 {
|
||||
return s.chatSQLQueries.Load()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user