feat: add S3 attachments and reconciliation

This commit is contained in:
2026-10-02 19:55:52 +03:00
parent 7e60f099d3
commit efaeb593e8
21 changed files with 1623 additions and 85 deletions
+155
View File
@@ -0,0 +1,155 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
)
func (s *Store) CreateAttachment(ctx context.Context, attachment model.Attachment) (model.Attachment, error) {
const query = `
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key
)
SELECT $1, $2, $3, $4, $5, $6, $7, $8
WHERE EXISTS (
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3
)
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, created_at, updated_at`
err := s.pool.QueryRow(
ctx, query, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.Filename,
attachment.ContentType, attachment.SizeBytes, attachment.SHA256, attachment.ObjectKey,
).Scan(
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
&attachment.CreatedAt, &attachment.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Attachment{}, ErrNotFound
}
if err != nil {
return model.Attachment{}, fmt.Errorf("create attachment: %w", err)
}
return readyAttachment(attachment), nil
}
func (s *Store) AttachmentForUser(ctx context.Context, attachmentID, userID string) (model.Attachment, error) {
const query = `
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes,
a.sha256, a.object_key, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members member ON member.chat_id = a.chat_id AND member.user_id = $2
WHERE a.id = $1`
var attachment model.Attachment
err := s.pool.QueryRow(ctx, query, attachmentID, userID).Scan(
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
&attachment.CreatedAt, &attachment.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Attachment{}, ErrNotFound
}
if err != nil {
return model.Attachment{}, fmt.Errorf("get attachment for user: %w", err)
}
return readyAttachment(attachment), nil
}
func (s *Store) AttachmentByStorage(ctx context.Context, attachmentID, objectKey string) (model.Attachment, error) {
const query = `
SELECT id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, object_key, created_at, updated_at
FROM attachments
WHERE id = $1 AND object_key = $2`
var attachment model.Attachment
err := s.pool.QueryRow(ctx, query, attachmentID, objectKey).Scan(
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
&attachment.CreatedAt, &attachment.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Attachment{}, ErrNotFound
}
if err != nil {
return model.Attachment{}, fmt.Errorf("get attachment by storage: %w", err)
}
return readyAttachment(attachment), nil
}
func (s *Store) ListAttachments(ctx context.Context, afterObjectKey string, limit int) ([]model.Attachment, string, error) {
if limit < 1 || limit > 1000 {
return nil, "", fmt.Errorf("attachment list limit must be between 1 and 1000")
}
const query = `
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, created_at, updated_at
FROM attachments
WHERE object_key > $1
ORDER BY object_key
LIMIT $2`
rows, err := s.pool.Query(ctx, query, afterObjectKey, limit+1)
if err != nil {
return nil, "", fmt.Errorf("list attachments: %w", err)
}
defer rows.Close()
attachments, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Attachment](func(row pgx.CollectableRow) (model.Attachment, error) {
var attachment model.Attachment
err := row.Scan(
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
&attachment.CreatedAt, &attachment.UpdatedAt,
)
return readyAttachment(attachment), err
}))
if err != nil {
return nil, "", fmt.Errorf("scan attachments: %w", err)
}
var next string
if len(attachments) > limit {
attachments = attachments[:limit]
next = attachments[len(attachments)-1].ObjectKey
}
return attachments, next, nil
}
func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) {
const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`
var referenced bool
if err := s.pool.QueryRow(ctx, query, attachmentID).Scan(&referenced); err != nil {
return false, fmt.Errorf("check attachment references: %w", err)
}
return referenced, nil
}
func (s *Store) DeleteAttachmentIfUnreferencedBefore(
ctx context.Context,
attachmentID string,
createdBefore time.Time,
) (bool, error) {
const query = `
DELETE FROM attachments a
WHERE a.id = $1
AND a.created_at <= $2
AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`
result, err := s.pool.Exec(ctx, query, attachmentID, createdBefore)
if err != nil {
return false, fmt.Errorf("delete old unreferenced attachment: %w", err)
}
return result.RowsAffected() == 1, nil
}
func readyAttachment(attachment model.Attachment) model.Attachment {
attachment.Status = "ready"
attachment.Variants = []model.Variant{}
return attachment
}
+72 -6
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"time"
@@ -21,6 +22,7 @@ func (s *Store) CreateMessage(
chatID string,
senderID string,
text string,
attachmentIDs []string,
idempotencyKey string,
idempotencyTTL time.Duration,
) (model.Message, bool, error) {
@@ -46,13 +48,23 @@ func (s *Store) CreateMessage(
if !visible {
return model.Message{}, false, ErrNotFound
}
validAttachments, err := attachmentsBelongToChat(ctx, tx, chatID, attachmentIDs)
if err != nil {
return model.Message{}, false, err
}
if !validAttachments {
return model.Message{}, false, ErrNotFound
}
if err = deleteExpiredIdempotencyRecords(ctx, tx, expiredIdempotencyCleanupBatch); err != nil {
return model.Message{}, false, err
}
requestHash = sha256.Sum256([]byte(text))
requestHash, err = messageRequestHash(text, attachmentIDs)
if err != nil {
return model.Message{}, false, err
}
message, replay, err = createIdempotentMessage(
ctx, tx, chatID, senderID, text, idempotencyKey, requestHash[:], idempotencyTTL,
ctx, tx, chatID, senderID, text, attachmentIDs, idempotencyKey, requestHash[:], idempotencyTTL,
)
if err != nil {
return model.Message{}, false, err
@@ -63,6 +75,35 @@ func (s *Store) CreateMessage(
return message, replay, nil
}
func messageRequestHash(text string, attachmentIDs []string) ([sha256.Size]byte, error) {
if attachmentIDs == nil {
attachmentIDs = []string{}
}
payload, err := json.Marshal(struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}{text, attachmentIDs})
if err != nil {
return [sha256.Size]byte{}, fmt.Errorf("marshal message request: %w", err)
}
return sha256.Sum256(payload), nil
}
func attachmentsBelongToChat(ctx context.Context, tx pgx.Tx, chatID string, attachmentIDs []string) (bool, error) {
if len(attachmentIDs) == 0 {
return true, nil
}
const query = `
SELECT count(*)
FROM attachments
WHERE chat_id = $1 AND id::text = ANY($2)`
var count int
if err := tx.QueryRow(ctx, query, chatID, attachmentIDs).Scan(&count); err != nil {
return false, fmt.Errorf("validate message attachments: %w", err)
}
return count == len(attachmentIDs), nil
}
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
const query = `
SELECT EXISTS (
@@ -84,6 +125,7 @@ func createIdempotentMessage(
chatID string,
senderID string,
text string,
attachmentIDs []string,
idempotencyKey string,
requestHash []byte,
idempotencyTTL time.Duration,
@@ -126,7 +168,7 @@ func createIdempotentMessage(
continue
}
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text)
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text, attachmentIDs)
return message, false, err
}
}
@@ -235,6 +277,7 @@ func insertMessage(
chatID string,
senderID string,
text string,
attachmentIDs []string,
) (model.Message, error) {
const query = `
INSERT INTO messages (id, chat_id, sender_id, text)
@@ -255,14 +298,36 @@ func insertMessage(
if err != nil {
return model.Message{}, fmt.Errorf("insert message: %w", err)
}
if err := insertMessageAttachments(ctx, tx, messageID, chatID, attachmentIDs); err != nil {
return model.Message{}, err
}
message.AttachmentIDs = append([]string(nil), attachmentIDs...)
return message, nil
}
func insertMessageAttachments(ctx context.Context, tx pgx.Tx, messageID, chatID string, attachmentIDs []string) error {
const query = `
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
VALUES ($1, $2, $3, $4)`
for position, attachmentID := range attachmentIDs {
if _, err := tx.Exec(ctx, query, messageID, chatID, attachmentID, position); err != nil {
return fmt.Errorf("insert message attachment: %w", err)
}
}
return nil
}
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
const query = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE id = $1`
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id::text
FROM message_attachments ma
WHERE ma.message_id = m.id
ORDER BY ma.position
)
FROM messages m
WHERE m.id = $1`
var (
message model.Message
@@ -274,6 +339,7 @@ func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Messag
&message.SenderID,
&message.Text,
&message.CreatedAt,
&message.AttachmentIDs,
)
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, fmt.Errorf("idempotency result message not found")
+12 -5
View File
@@ -344,11 +344,17 @@ func (s *Store) ListMessages(
}
const query = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3::uuid))
ORDER BY created_at, id
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(
SELECT ma.attachment_id::text
FROM message_attachments ma
WHERE ma.message_id = m.id
ORDER BY ma.position
)
FROM messages m
WHERE m.chat_id = $1
AND ($2::timestamptz IS NULL OR (m.created_at, m.id) > ($2, $3::uuid))
ORDER BY m.created_at, m.id
LIMIT $4`
var afterTime any
@@ -372,6 +378,7 @@ func (s *Store) ListMessages(
&message.SenderID,
&message.Text,
&message.CreatedAt,
&message.AttachmentIDs,
)
return message, err
}))
+67 -13
View File
@@ -100,18 +100,16 @@ func (s *PostgresSuite) TestMessageIdempotencyReplayAndConflict() {
owner, chatID := createOwnerAndChat(t, store)
key := uuid.NewString()
first, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", key, 24*time.Hour)
first, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", nil, key, 24*time.Hour)
if err != nil || replay {
t.Fatalf("first CreateMessage() = (%v, %t, %v)", first, replay, err)
}
second, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", key, 24*time.Hour)
second, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", []string{}, key, 24*time.Hour)
if err != nil || !replay {
t.Fatalf("replay CreateMessage() = (%v, %t, %v)", second, replay, err)
}
if first != second {
t.Fatalf("replay message = %v, want %v", second, first)
}
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "different body", key, 24*time.Hour); !errors.Is(err, postgres.ErrIdempotencyConflict) {
s.Equal(first, second)
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "different body", nil, key, 24*time.Hour); !errors.Is(err, postgres.ErrIdempotencyConflict) {
t.Fatalf("conflicting CreateMessage() error = %v, want ErrIdempotencyConflict", err)
}
if count := messageCount(t, pool, chatID); count != 1 {
@@ -119,6 +117,62 @@ func (s *PostgresSuite) TestMessageIdempotencyReplayAndConflict() {
}
}
func (s *PostgresSuite) TestAttachmentAccessAndMessageLinking() {
owner, chatID := createOwnerAndChat(s.T(), s.store)
outsider, err := s.store.CreateUser(context.Background(), uniqueUsername(), "Outsider", "password-hash")
s.Require().NoError(err)
attachment := model.Attachment{
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "photo.png",
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("a", 64),
ObjectKey: "attachments/" + uuid.NewString() + "/original",
}
created, err := s.store.CreateAttachment(context.Background(), attachment)
s.Require().NoError(err)
s.Equal("ready", created.Status)
s.Empty(created.Variants)
s.Nil(created.ErrorCode)
visible, err := s.store.AttachmentForUser(context.Background(), created.ID, owner.ID)
s.Require().NoError(err)
s.Equal(created, visible)
_, err = s.store.AttachmentForUser(context.Background(), created.ID, outsider.ID)
s.ErrorIs(err, postgres.ErrNotFound)
message, replay, err := s.store.CreateMessage(
context.Background(), chatID, owner.ID, "", []string{created.ID}, uuid.NewString(), 24*time.Hour,
)
s.Require().NoError(err)
s.False(replay)
s.Equal([]string{created.ID}, message.AttachmentIDs)
messages, _, err := s.store.ListMessages(context.Background(), chatID, owner.ID, nil, 10)
s.Require().NoError(err)
s.Len(messages, 1)
s.Equal([]string{created.ID}, messages[0].AttachmentIDs)
referenced, err := s.store.AttachmentReferenced(context.Background(), created.ID)
s.Require().NoError(err)
s.True(referenced)
deleted, err := s.store.DeleteAttachmentIfUnreferencedBefore(context.Background(), created.ID, time.Now().Add(time.Hour))
s.Require().NoError(err)
s.False(deleted)
}
func (s *PostgresSuite) TestMessageRejectsAttachmentFromAnotherChat() {
owner, firstChatID := createOwnerAndChat(s.T(), s.store)
secondChat, err := s.store.CreateChat(context.Background(), "Second", []string{owner.ID}, owner.ID)
s.Require().NoError(err)
attachment, err := s.store.CreateAttachment(context.Background(), model.Attachment{
ID: uuid.NewString(), ChatID: firstChatID, OwnerID: owner.ID, Filename: "photo.png",
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("b", 64),
ObjectKey: "attachments/" + uuid.NewString() + "/original",
})
s.Require().NoError(err)
_, _, err = s.store.CreateMessage(
context.Background(), secondChat.ID, owner.ID, "wrong chat", []string{attachment.ID}, uuid.NewString(), 24*time.Hour,
)
s.ErrorIs(err, postgres.ErrNotFound)
}
func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
t := s.T()
pool := s.pool
@@ -139,7 +193,7 @@ func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
go func() {
defer group.Done()
message, replay, err := stores[worker%len(stores)].CreateMessage(
context.Background(), chatID, owner.ID, "concurrent body", key, 24*time.Hour,
context.Background(), chatID, owner.ID, "concurrent body", nil, key, 24*time.Hour,
)
results <- result{message: message, replay: replay, err: err}
}()
@@ -186,13 +240,13 @@ func (s *PostgresSuite) TestMessageIdempotencyScopeAndExpiry() {
}
key := uuid.NewString()
if _, _, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "owner", key, 24*time.Hour); err != nil {
if _, _, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "owner", nil, key, 24*time.Hour); err != nil {
t.Fatalf("owner CreateMessage() error = %v", err)
}
if _, _, err := store.CreateMessage(context.Background(), chat.ID, second.ID, "second", key, 24*time.Hour); err != nil {
if _, _, err := store.CreateMessage(context.Background(), chat.ID, second.ID, "second", nil, key, 24*time.Hour); err != nil {
t.Fatalf("second user CreateMessage() error = %v", err)
}
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "other chat", key, 24*time.Hour); err != nil {
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "other chat", nil, key, 24*time.Hour); err != nil {
t.Fatalf("other chat CreateMessage() error = %v", err)
}
if _, err := pool.Exec(context.Background(), `
@@ -202,7 +256,7 @@ func (s *PostgresSuite) TestMessageIdempotencyScopeAndExpiry() {
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chat.ID, key); err != nil {
t.Fatalf("expire idempotency key: %v", err)
}
message, replay, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "after expiry", key, 24*time.Hour)
message, replay, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "after expiry", nil, key, 24*time.Hour)
if err != nil || replay || message.Text != "after expiry" {
t.Fatalf("expired CreateMessage() = (%v, %t, %v)", message, replay, err)
}
@@ -212,7 +266,7 @@ func (s *PostgresSuite) TestExpiredIdempotencyRecordsAreCleanedOnNewMessages() {
t := s.T()
owner, chatID := createOwnerAndChat(t, s.store)
expiredKey := uuid.NewString()
if _, _, err := s.store.CreateMessage(context.Background(), chatID, owner.ID, "expired", expiredKey, 24*time.Hour); err != nil {
if _, _, err := s.store.CreateMessage(context.Background(), chatID, owner.ID, "expired", nil, expiredKey, 24*time.Hour); err != nil {
t.Fatalf("create expired message: %v", err)
}
if _, err := s.pool.Exec(context.Background(), `
@@ -223,7 +277,7 @@ func (s *PostgresSuite) TestExpiredIdempotencyRecordsAreCleanedOnNewMessages() {
t.Fatalf("expire idempotency key: %v", err)
}
if _, _, err := s.store.CreateMessage(
context.Background(), chatID, owner.ID, "new message", uuid.NewString(), 24*time.Hour,
context.Background(), chatID, owner.ID, "new message", nil, uuid.NewString(), 24*time.Hour,
); err != nil {
t.Fatalf("create new message: %v", err)
}