forked from mtusi2026/mtusi2026lab4
feat(app) implemented lab 4
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
|
||||
}
|
||||
+128
-23
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
|
||||
@@ -13,24 +14,29 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string) (model.Message, error) {
|
||||
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()
|
||||
|
||||
fingerprint := sha256.Sum256([]byte(text))
|
||||
// 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 {
|
||||
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(),
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: common.NowUTC(),
|
||||
AttachmentIDs: attachmentIDs,
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
@@ -39,20 +45,73 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
}
|
||||
defer rollback(tx)
|
||||
|
||||
tag, err := tx.Exec(ctx, `
|
||||
// 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)
|
||||
SELECT $1, $2, $3, $4, $5
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`,
|
||||
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)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return model.Message{}, common.NotFound("chat not found")
|
||||
|
||||
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, `
|
||||
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)
|
||||
@@ -62,7 +121,7 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
created_at = EXCLUDED.created_at,
|
||||
expires_at = EXCLUDED.expires_at
|
||||
WHERE message_idempotency.expires_at <= now()`,
|
||||
senderID, chatID, idempotencyKey, fingerprint[:], message.ID,
|
||||
senderID, chatID, idempotencyKey, fingerprint, message.ID,
|
||||
time.Time(message.CreatedAt), expiresAt)
|
||||
if err != nil {
|
||||
return model.Message{}, dbError(err)
|
||||
@@ -70,7 +129,7 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
|
||||
if tag.RowsAffected() == 0 {
|
||||
rollback(tx)
|
||||
stored, found, lookupErr := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint[:])
|
||||
stored, found, lookupErr := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint)
|
||||
if lookupErr != nil {
|
||||
return model.Message{}, lookupErr
|
||||
}
|
||||
@@ -87,13 +146,47 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
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, i.request_hash
|
||||
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
|
||||
@@ -102,7 +195,8 @@ func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid
|
||||
AND i.idempotency_key = $3
|
||||
AND i.expires_at > now()`,
|
||||
senderID, chatID, idempotencyKey).Scan(
|
||||
&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &storedHash)
|
||||
&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt,
|
||||
&message.AttachmentIDs, &storedHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, false, nil
|
||||
}
|
||||
@@ -112,6 +206,9 @@ func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid
|
||||
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
|
||||
@@ -136,10 +233,14 @@ func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limi
|
||||
|
||||
cursorTime, cursorID := cursorValues(cursor)
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
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)
|
||||
@@ -172,9 +273,13 @@ func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limi
|
||||
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); err != nil {
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user