Заменить lab4 на aws-sdk S3-вложения, уровень 4 и трек 2 reconciler.
Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5.
This commit is contained in:
+46
-76
@@ -8,10 +8,6 @@
|
||||
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||
//
|
||||
// Вложения (lab4) — файл attachments.go: метаданные в PostgreSQL, байты в S3. Сообщение
|
||||
// ссылается на вложения через message_attachments; ссылки пишутся в той же транзакции,
|
||||
// что и само сообщение и ключ идемпотентности.
|
||||
//
|
||||
// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики:
|
||||
// два параллельных POST с одним ключом через разные API-контейнеры видят один PK.
|
||||
package store
|
||||
@@ -66,14 +62,15 @@ type Chat struct {
|
||||
}
|
||||
|
||||
// Message — одно подтверждённое сообщение. sender_id назначает сервер.
|
||||
// AttachmentIDs всегда непустой срез нулевой длины, если вложений нет (JSON даёт []).
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
// AttachmentIDs — вложения в порядке, заданном клиентом. Никогда nil в ответах API
|
||||
// (контракт: attachment_ids обязателен, по умолчанию []).
|
||||
AttachmentIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api.
|
||||
@@ -318,11 +315,12 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
// Внутренний путь без вложений; поле не nil, чтобы JSON дал [], а не null.
|
||||
AttachmentIDs: []uuid.UUID{},
|
||||
}
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
@@ -346,20 +344,22 @@ type IdempotentMessage struct {
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение со вложениями и запоминает ответ по ключу.
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу.
|
||||
//
|
||||
// Алгоритм (общая БД, любые реплики):
|
||||
// 1. BEGIN;
|
||||
// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов
|
||||
// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message (с его вложениями);
|
||||
// 4. иначе проверить членство в чате и вложения: каждое должно существовать, лежать
|
||||
// в ЭТОМ чате и быть ready (чужое/неизвестное — ErrNotFound, не ready — ErrNotReady);
|
||||
// 5. INSERT message + message_attachments + idempotency_keys в той же транзакции;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message;
|
||||
// 4. иначе проверить членство, затем вложения (lab4): все принадлежат ЭТОМУ чату и ready,
|
||||
// строки блокируются FOR SHARE, чтобы удаление (reconciler) не вклинилось до COMMIT;
|
||||
// 5. INSERT message + INSERT message_attachments + INSERT idempotency_keys в той же
|
||||
// транзакции: сообщение либо видно целиком вместе со ссылками на вложения, либо нет;
|
||||
// 6. COMMIT (advisory lock снимается вместе с транзакцией).
|
||||
//
|
||||
// attachmentIDs уже без дубликатов (проверяет HTTP-слой), порядок сохраняется.
|
||||
// Пустой текст допустим только вместе с вложениями — это тоже проверяет HTTP-слой.
|
||||
// Чужое и неизвестное вложение (в т.ч. из другого чата) неразличимы: оба дают ErrNotFound
|
||||
// (HTTP 404), чтобы нельзя было перебором выяснить, существует ли чужой файл.
|
||||
//
|
||||
// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает:
|
||||
// запись ключа только после успешной подготовки 201.
|
||||
func (s *Store) CreateMessageIdempotent(
|
||||
@@ -371,9 +371,6 @@ func (s *Store) CreateMessageIdempotent(
|
||||
) (*IdempotentMessage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -405,7 +402,8 @@ func (s *Store) CreateMessageIdempotent(
|
||||
if storedHash != requestHash {
|
||||
return nil, ErrIdempotencyConflict
|
||||
}
|
||||
byMsg, err := attachmentIDsByMessage(ctx, tx, []uuid.UUID{msgID})
|
||||
// Replay обязан вернуть ТОТ ЖЕ набор вложений, что и первый ответ.
|
||||
replayIDs, err := loadMessageAttachmentIDs(ctx, tx, msgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -418,8 +416,8 @@ func (s *Store) CreateMessageIdempotent(
|
||||
ChatID: msgChat,
|
||||
SenderID: msgSender,
|
||||
Text: msgText,
|
||||
AttachmentIDs: byMsg[msgID],
|
||||
CreatedAt: msgCreated,
|
||||
AttachmentIDs: replayIDs,
|
||||
},
|
||||
Replayed: true,
|
||||
}, nil
|
||||
@@ -437,39 +435,10 @@ func (s *Store) CreateMessageIdempotent(
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
attStrs := make([]string, len(attachmentIDs))
|
||||
for i, id := range attachmentIDs {
|
||||
attStrs[i] = id.String()
|
||||
}
|
||||
if len(attStrs) > 0 {
|
||||
// chat_id = $2 — вложение другого чата неотличимо от несуществующего (404, не 403).
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT status FROM attachments WHERE id = ANY($1::uuid[]) AND chat_id = $2`, attStrs, chatID)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
found, notReady := 0, false
|
||||
for rows.Next() {
|
||||
var status string
|
||||
if err := rows.Scan(&status); err != nil {
|
||||
rows.Close()
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
found++
|
||||
if status != "ready" {
|
||||
notReady = true
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if found != len(attStrs) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if notReady {
|
||||
return nil, ErrNotReady
|
||||
}
|
||||
// Вложения проверяем ПОСЛЕ членства: посторонний в чат получает 404 по чату,
|
||||
// а не информацию о существовании файлов.
|
||||
if err := lockMessageAttachments(ctx, tx, chatID, attachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
@@ -477,8 +446,8 @@ func (s *Store) CreateMessageIdempotent(
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...),
|
||||
CreatedAt: nowUTC(),
|
||||
AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
@@ -486,25 +455,28 @@ func (s *Store) CreateMessageIdempotent(
|
||||
msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if len(attStrs) > 0 {
|
||||
// WITH ORDINALITY сохраняет порядок attachment_ids из запроса.
|
||||
// Порядок attachment_ids клиента сохраняется в position.
|
||||
for i, aid := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
SELECT $1, u.id, (u.ord - 1)::smallint
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord)`, msg.ID, attStrs); err != nil {
|
||||
VALUES ($1, $2, $3)`, msg.ID, aid, i); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
}
|
||||
|
||||
// response_body заполняем каноническим Message JSON уже здесь, чтобы replay
|
||||
// не зависел от повторной сериализации в HTTP-слое с другим порядком полей.
|
||||
attachmentStrs := make([]string, len(msg.AttachmentIDs))
|
||||
for i, aid := range msg.AttachmentIDs {
|
||||
attachmentStrs[i] = aid.String()
|
||||
}
|
||||
bodyJSON, err := json.Marshal(map[string]any{
|
||||
"id": msg.ID.String(),
|
||||
"chat_id": msg.ChatID.String(),
|
||||
"sender_id": msg.SenderID.String(),
|
||||
"text": msg.Text,
|
||||
"attachment_ids": attStrs,
|
||||
"created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"),
|
||||
"attachment_ids": attachmentStrs,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -576,18 +548,10 @@ func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limi
|
||||
hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) {
|
||||
return m.CreatedAt, m.ID
|
||||
})
|
||||
// Вложения страницы — одним запросом, а не по запросу на сообщение.
|
||||
ids := make([]uuid.UUID, len(items))
|
||||
for i := range items {
|
||||
ids[i] = items[i].ID
|
||||
}
|
||||
byMsg, err := attachmentIDsByMessage(ctx, s.pool, ids)
|
||||
if err != nil {
|
||||
// Вложения страницы одним запросом (а не N+1): WHERE message_id = ANY(id страницы).
|
||||
if err := s.attachMessageAttachments(ctx, items); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].AttachmentIDs = byMsg[items[i].ID]
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
@@ -608,6 +572,12 @@ func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// IsChatMember — проверка членства для HTTP-слоя (например, до чтения тела загрузки:
|
||||
// постороннему не нужно тратить на себя RAM и трафик). ErrNotFound — не участник.
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
return s.ensureMember(ctx, chatID, userID)
|
||||
}
|
||||
|
||||
func (s *Store) ensureMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
Reference in New Issue
Block a user