forked from mtusi2026/mtusi2026lab4
ЛР4 на 4: MinIO-вложения поверх LB, идемпотентности и failover.
PNG/JPEG через API, student-tests, REPORT и DEFENSE.
This commit is contained in:
@@ -0,0 +1,391 @@
|
||||
package api
|
||||
|
||||
// HTTP-слой вложений lab4.
|
||||
//
|
||||
// Модель согласованности двух хранилищ (S3 + PostgreSQL), т.к. общей транзакции у них нет:
|
||||
//
|
||||
// 1. проверяем всё, что можно, ДО записи (доступ, имя, тип, размер, содержимое);
|
||||
// 2. PUT оригинала в S3 по ключу attachments/{chat}/{id};
|
||||
// 3. INSERT метаданных в PostgreSQL;
|
||||
// 4. только после этого — 201 ready.
|
||||
//
|
||||
// Что если процесс/сеть упали между 2 и 3, или INSERT вернул ошибку?
|
||||
// - Остаётся лишний ОБЪЕКТ без строки (orphan). Строки без файла не бывает —
|
||||
// ради этого PUT делается ПЕРВЫМ. Пользователь не увидит «битое» вложение,
|
||||
// а лишний объект безвреден: на него никто не ссылается.
|
||||
// - При ошибке INSERT мы сразу пытаемся удалить объект (компенсация, compensateOrphan).
|
||||
// - Если и удаление не удалось (процесс убит, S3 моргнул) — объект подберёт reconciler
|
||||
// (`/server -reconcile`): он удаляет объекты без строки старше S3_ORPHAN_GRACE_SECONDS.
|
||||
// Grace нужен, чтобы не снести объект, у которого INSERT ещё «в полёте».
|
||||
// - Обрыв соединения клиентом во время передачи тела: до PUT мы ничего не пишем,
|
||||
// а PUT/INSERT привязаны к контексту запроса и отменяются.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gavrilenko-sxdees/lab4/internal/objectstore"
|
||||
"gavrilenko-sxdees/lab4/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
// drainLimit — сколько байт «лишнего» тела дочитываем при раннем отказе (413/415/400).
|
||||
// Если сервер ответил и закрыл соединение, пока клиент ещё пишет, клиент получит
|
||||
// RST вместо читаемого 413. Дочитывание ограничено, чтобы это не стало каналом
|
||||
// для бесплатной траты трафика.
|
||||
drainLimit = 16 << 20
|
||||
// slotWait — сколько загрузка ждёт свободный слот буферизации, прежде чем получить 429.
|
||||
// Меньше таймаутов HAProxy (15 с), чтобы клиент получил осмысленный ответ.
|
||||
slotWait = 8 * time.Second
|
||||
)
|
||||
|
||||
// WithUploadConcurrency задаёт, сколько загрузок реплика обрабатывает одновременно.
|
||||
//
|
||||
// Зачем: тело загрузки целиком буферизуется в RAM (оно нужно для проверки содержимого и
|
||||
// SHA-256 ДО записи в S3, иначе мусор попадал бы в bucket). Без ограничения N клиентов
|
||||
// заняли бы N*10 MiB. Со слотами пик ≈ n*10 MiB (+ декод маленьких картинок),
|
||||
// остальные загрузки ждут в очереди, не читая тело.
|
||||
func (s *Server) WithUploadConcurrency(n int) *Server {
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
s.uploadSlots = make(chan struct{}, n)
|
||||
return s
|
||||
}
|
||||
|
||||
// handleUploadAttachment — POST /api/v1/chats/{chat_id}/attachments?filename=...
|
||||
func (s *Server) handleUploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
uid := userFrom(r)
|
||||
|
||||
// 1. Сначала доступ к ресурсу (контракт: аутентификация → доступ → остальное).
|
||||
// Посторонний получает 404 до того, как мы потратим на него RAM и трафик.
|
||||
if err := s.Store.IsChatMember(r.Context(), chatID, uid); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
s.rejectUpload(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
|
||||
// 2. filename — только для отображения. Опасные символы отклоняем сразу (400):
|
||||
// даже зная, что в путь/ключ он не попадает, не храним то, что опасно показывать.
|
||||
filename, ok := validFilename(r.URL.Query().Get("filename"))
|
||||
if !ok {
|
||||
s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid filename")
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Заголовок Content-Type должен быть image/png или image/jpeg. Это лишь заявка
|
||||
// клиента: настоящий тип определяется по содержимому (шаг 6) и должен с ней совпасть.
|
||||
declared, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || (declared != "image/png" && declared != "image/jpeg") {
|
||||
s.rejectUpload(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "content type must be image/png or image/jpeg")
|
||||
return
|
||||
}
|
||||
|
||||
// 4. Лимит размера до чтения тела: честный Content-Length > 10 MiB отвергаем сразу.
|
||||
if r.ContentLength > maxUploadBytes {
|
||||
s.rejectUpload(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
return
|
||||
}
|
||||
|
||||
// 5. Слот буферизации. Ждём не дольше slotWait, иначе 429 (контракт его допускает).
|
||||
release, ok := s.acquireUploadSlot(r.Context())
|
||||
if !ok {
|
||||
if r.Context().Err() != nil {
|
||||
return // клиент ушёл
|
||||
}
|
||||
w.Header().Set("Retry-After", "1")
|
||||
s.rejectUpload(w, r, http.StatusTooManyRequests, "rate_limited", "too many concurrent uploads")
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
|
||||
// 6. Ограниченное чтение тела. MaxBytesReader гарантирует, что и при chunked-запросе
|
||||
// без Content-Length (где честную длину проверить нельзя) мы не прочитаем больше 10 MiB.
|
||||
origBody := r.Body
|
||||
data, err := readLimitedBody(w, r, maxUploadBytes)
|
||||
if err != nil {
|
||||
var tooBig *http.MaxBytesError
|
||||
if errors.As(err, &tooBig) {
|
||||
// Дочитываем (ограниченно) ИСХОДНОЕ тело: обёртка MaxBytesReader после
|
||||
// превышения лимита читать уже не даёт.
|
||||
r.Body = origBody
|
||||
s.rejectUpload(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
return
|
||||
}
|
||||
// Обрыв загрузки клиентом/таймаут чтения: ничего ещё не записано ни в S3, ни в БД.
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "upload interrupted")
|
||||
return
|
||||
}
|
||||
|
||||
// 7. Проверка СОДЕРЖИМОГО: формат, пиксели, целостность. Пользовательская ошибка
|
||||
// здесь — всегда 4xx, никогда 500.
|
||||
info, err := inspectImage(data)
|
||||
switch {
|
||||
case errors.Is(err, errTooManyPixels):
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels")
|
||||
return
|
||||
case err != nil:
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "file is not a valid png/jpeg image")
|
||||
return
|
||||
case info.ContentType != declared:
|
||||
// «Подмена MIME»: заголовок говорит jpeg, а внутри png (или наоборот).
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "content does not match declared content type")
|
||||
return
|
||||
}
|
||||
|
||||
// 8. SHA-256 и ключ. Ключ полностью серверный: filename в нём не участвует.
|
||||
sum := sha256.Sum256(data)
|
||||
attID := uuid.New()
|
||||
key := store.AttachmentObjectKey(chatID, attID)
|
||||
|
||||
// 9. Оригинал в S3. Ошибка хранилища — 503 без подробностей.
|
||||
if err := s.Objects.Put(r.Context(), key, bytes.NewReader(data), int64(len(data)), info.ContentType); err != nil {
|
||||
log.Printf("request_id=%s attachment_put_failed err=%v", requestID(r), err)
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
// Точка отказа «между S3 и PG» — для тестов компенсации. В проде hook == nil.
|
||||
if s.AfterObjectPut != nil {
|
||||
s.AfterObjectPut(key)
|
||||
}
|
||||
|
||||
// 10. Метаданные в PostgreSQL. Дальше data больше не нужна — освобождаем RAM как можно раньше.
|
||||
att := &store.Attachment{
|
||||
ID: attID,
|
||||
ChatID: chatID,
|
||||
OwnerID: uid,
|
||||
Filename: filename,
|
||||
ContentType: info.ContentType,
|
||||
SizeBytes: int64(len(data)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
ObjectKey: key,
|
||||
Status: store.StatusReady,
|
||||
Width: info.Width,
|
||||
Height: info.Height,
|
||||
}
|
||||
data = nil
|
||||
if err := s.Store.CreateAttachment(r.Context(), att); err != nil {
|
||||
// Компенсация: строки нет → объект бесполезен. Удаляем сразу и независимо от
|
||||
// контекста запроса (он мог быть отменён — как раз из-за этого INSERT и упал).
|
||||
s.compensateOrphan(r, key)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
|
||||
// 11. Теперь честно: и байты, и метаданные сохранены.
|
||||
writeJSON(w, http.StatusCreated, attachmentDTO(att))
|
||||
}
|
||||
|
||||
// compensateOrphan убирает объект, для которого не удалось записать метаданные.
|
||||
// Контекст новый и короткий. Если удаление не прошло — это не ошибка запроса:
|
||||
// объект станет orphan и будет удалён reconciler'ом после grace-периода.
|
||||
func (s *Server) compensateOrphan(r *http.Request, key string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := s.Objects.Delete(ctx, key); err != nil {
|
||||
log.Printf("request_id=%s attachment_compensation_failed key=%s (reconciler удалит orphan после grace) err=%v",
|
||||
requestID(r), key, err)
|
||||
return
|
||||
}
|
||||
log.Printf("request_id=%s attachment_compensated key=%s (PG insert не удался, объект удалён)", requestID(r), key)
|
||||
}
|
||||
|
||||
// handleGetAttachment — GET /api/v1/attachments/{id}: метаданные участнику чата.
|
||||
func (s *Server) handleGetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
att, ok := s.loadAttachmentForRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, attachmentDTO(att))
|
||||
}
|
||||
|
||||
// handleDownloadAttachment — GET /api/v1/attachments/{id}/content: байты через API, без redirect.
|
||||
// Прямой доступ к bucket не нужен ни клиенту, ни другой реплике: любая реплика читает
|
||||
// из общего S3, поэтому остановка загрузившей реплики ничего не ломает.
|
||||
func (s *Server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
att, ok := s.loadAttachmentForRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// variant: в lab4 есть только original. Известные имена вариантов lab5+ у ready-объекта
|
||||
// отсутствуют → 404, неизвестное имя → 400.
|
||||
switch v := r.URL.Query().Get("variant"); v {
|
||||
case "", "original":
|
||||
case "thumbnail", "crop", "optimized":
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
default:
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid variant")
|
||||
return
|
||||
}
|
||||
if att.Status != store.StatusReady {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready")
|
||||
return
|
||||
}
|
||||
|
||||
body, _, err := s.Objects.Get(r.Context(), att.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, objectstore.ErrNotFound) {
|
||||
// Строка есть, объекта нет — расхождение БД/S3 (его ловит reconciler).
|
||||
// Это не ошибка пользователя; наружу — общий 500 без деталей.
|
||||
log.Printf("request_id=%s attachment_object_missing attachment_id=%s", requestID(r), att.ID)
|
||||
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
log.Printf("request_id=%s attachment_get_failed err=%v", requestID(r), err)
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
h := w.Header()
|
||||
// Тип берём из БД (определён по содержимому при загрузке), а не из S3 и не из имени.
|
||||
h.Set("Content-Type", att.ContentType)
|
||||
h.Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10))
|
||||
// nosniff: браузер не должен «угадывать» иной тип у отданных байт.
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Cache-Control", "private, no-store")
|
||||
h.Set("ETag", `"`+att.SHA256+`"`)
|
||||
// filename показываем только в заголовке, закодированным по RFC 5987 (FormatMediaType).
|
||||
if cd := mime.FormatMediaType("inline", map[string]string{"filename": att.Filename}); cd != "" {
|
||||
h.Set("Content-Disposition", cd)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
// Потоково: в памяти реплики лежит только буфер копирования, не весь файл.
|
||||
if _, err := io.Copy(w, body); err != nil {
|
||||
// Заголовки уже отправлены, статус не изменить; клиент увидит обрыв.
|
||||
log.Printf("request_id=%s attachment_stream_interrupted", requestID(r))
|
||||
}
|
||||
}
|
||||
|
||||
// loadAttachmentForRequest разбирает {attachment_id} и проверяет доступ участника.
|
||||
// Невалидный UUID — 400; чужое/несуществующее — 404.
|
||||
func (s *Server) loadAttachmentForRequest(w http.ResponseWriter, r *http.Request) (*store.Attachment, bool) {
|
||||
id, err := uuid.Parse(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id")
|
||||
return nil, false
|
||||
}
|
||||
att, err := s.Store.GetAttachmentForUser(r.Context(), id, userFrom(r))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return nil, false
|
||||
}
|
||||
return att, true
|
||||
}
|
||||
|
||||
// attachmentDTO — публичное представление. object_key и bucket НЕ раскрываются.
|
||||
func attachmentDTO(a *store.Attachment) map[string]any {
|
||||
return map[string]any{
|
||||
"id": a.ID.String(),
|
||||
"chat_id": a.ChatID.String(),
|
||||
"owner_id": a.OwnerID.String(),
|
||||
"filename": a.Filename,
|
||||
"content_type": a.ContentType,
|
||||
"size_bytes": a.SizeBytes,
|
||||
"sha256": a.SHA256,
|
||||
"status": a.Status,
|
||||
// lab4: производных вариантов нет (они появятся с воркером в lab5+).
|
||||
"variants": []any{},
|
||||
"error_code": a.ErrorCode,
|
||||
"created_at": formatTime(a.CreatedAt),
|
||||
"updated_at": formatTime(a.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
// acquireUploadSlot занимает место в очереди буферизации. Возвращает функцию освобождения.
|
||||
func (s *Server) acquireUploadSlot(ctx context.Context) (func(), bool) {
|
||||
timer := time.NewTimer(slotWait)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case s.uploadSlots <- struct{}{}:
|
||||
return func() { <-s.uploadSlots }, true
|
||||
case <-ctx.Done():
|
||||
return nil, false
|
||||
case <-timer.C:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// rejectUpload отвечает ошибкой на запрос с ещё не прочитанным телом.
|
||||
// Перед ответом ограниченно дочитываем тело (см. drainLimit): иначе клиент, который
|
||||
// ещё пишет большой файл, получит сброс соединения вместо понятного статуса.
|
||||
func (s *Server) rejectUpload(w http.ResponseWriter, r *http.Request, status int, code, msg string) {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(r.Body, drainLimit))
|
||||
writeError(w, r, status, code, msg)
|
||||
}
|
||||
|
||||
// readLimitedBody читает тело не больше limit байт.
|
||||
//
|
||||
// Если клиент заявил Content-Length, буфер выделяется ОДИН раз нужного размера
|
||||
// (+MinRead, чтобы bytes.Buffer не удваивал ёмкость перед самым EOF и не копировал
|
||||
// 10 MiB в 20 MiB). Для chunked-тела размер неизвестен — буфер растёт, но лимит
|
||||
// MaxBytesReader всё равно ограничивает его сверху.
|
||||
func readLimitedBody(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, error) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
var buf bytes.Buffer
|
||||
if cl := r.ContentLength; cl > 0 && cl <= limit {
|
||||
buf.Grow(int(cl) + bytes.MinRead)
|
||||
}
|
||||
if _, err := buf.ReadFrom(r.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// validFilename проверяет отображаемое имя: 1–255 code points, валидный UTF-8,
|
||||
// не пустое/не пробельное, без '/', '\', NUL и управляющих символов.
|
||||
// Дополнительно отвергаем разделители строк и bidi-переопределения (U+202A–202E,
|
||||
// U+2066–2069): через них имя «photognp.exe» выглядит иначе, чем записано.
|
||||
func validFilename(raw string) (string, bool) {
|
||||
if raw == "" || !utf8.ValidString(raw) {
|
||||
return "", false
|
||||
}
|
||||
if n := utf8.RuneCountInString(raw); n < 1 || n > 255 {
|
||||
return "", false
|
||||
}
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return "", false
|
||||
}
|
||||
for _, c := range raw {
|
||||
switch {
|
||||
case c == '/', c == '\\', c == 0, unicode.IsControl(c):
|
||||
return "", false
|
||||
case c == 0x2028, c == 0x2029:
|
||||
return "", false
|
||||
case c >= 0x202A && c <= 0x202E, c >= 0x2066 && c <= 0x2069:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
return raw, true
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
_ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig / image.Decode
|
||||
_ "image/png" // регистрирует декодер PNG
|
||||
)
|
||||
|
||||
// Лимиты контракта lab4.
|
||||
const (
|
||||
// maxUploadBytes = 10 MiB = 10 485 760 байт. Превышение — 413.
|
||||
maxUploadBytes = 10 << 20
|
||||
// maxImagePixels — 40 млн декодированных пикселей. Превышение — 413.
|
||||
// Проверяется по заголовку (image.DecodeConfig) ДО любой распаковки: PNG размером
|
||||
// в несколько КБ может «раскрыться» в гигабайты (decompression bomb).
|
||||
maxImagePixels = 40_000_000
|
||||
// fullDecodeMaxPixels — до этого размера дополнительно делаем ПОЛНЫЙ декод, чтобы
|
||||
// поймать повреждённые данные внутри потока (битый zlib/Huffman при целых заголовках).
|
||||
// Для больших картинок полный декод стоил бы сотни МБ RAM на одну загрузку
|
||||
// (40 Мпикс * 4–8 байт) — это ровно то, что запрещает требование про ограниченную RAM,
|
||||
// поэтому там остаются дешёвые структурные проверки (CRC всех чанков PNG, маркеры/EOI JPEG).
|
||||
fullDecodeMaxPixels = 2_000_000
|
||||
)
|
||||
|
||||
var (
|
||||
// errNotImage — не PNG/JPEG или файл повреждён → 415.
|
||||
errNotImage = errors.New("not a valid png/jpeg image")
|
||||
// errTooManyPixels — больше 40 млн пикселей → 413.
|
||||
errTooManyPixels = errors.New("too many pixels")
|
||||
)
|
||||
|
||||
// imageInfo — результат проверки содержимого.
|
||||
type imageInfo struct {
|
||||
ContentType string // image/png | image/jpeg — по СОДЕРЖИМОМУ, не по заголовку запроса
|
||||
Width, Height int
|
||||
}
|
||||
|
||||
// inspectImage определяет формат и размеры и отвергает повреждённые файлы.
|
||||
//
|
||||
// Порядок важен:
|
||||
// 1. image.DecodeConfig читает только заголовок: формат + width/height без выделения
|
||||
// пиксельного буфера. Не PNG/JPEG (в т.ч. GIF, WebP, текст, нули) → errNotImage.
|
||||
// 2. Лимит пикселей проверяется сразу и ДО структурной проверки и декода.
|
||||
// 3. Структурная проверка (дёшево, O(n) по байтам, без распаковки).
|
||||
// 4. Полный декод только для небольших изображений (см. fullDecodeMaxPixels).
|
||||
func inspectImage(data []byte) (imageInfo, error) {
|
||||
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
var info imageInfo
|
||||
switch format {
|
||||
case "png":
|
||||
info.ContentType = "image/png"
|
||||
case "jpeg":
|
||||
info.ContentType = "image/jpeg"
|
||||
default:
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
info.Width, info.Height = cfg.Width, cfg.Height
|
||||
|
||||
pixels := int64(cfg.Width) * int64(cfg.Height)
|
||||
if pixels > maxImagePixels {
|
||||
return imageInfo{}, errTooManyPixels
|
||||
}
|
||||
|
||||
switch format {
|
||||
case "png":
|
||||
if !validPNGStructure(data) {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
case "jpeg":
|
||||
if !validJPEGStructure(data) {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
}
|
||||
|
||||
if pixels <= fullDecodeMaxPixels {
|
||||
if _, _, err := image.Decode(bytes.NewReader(data)); err != nil {
|
||||
return imageInfo{}, errNotImage
|
||||
}
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// validPNGStructure обходит чанки PNG, не распаковывая данные:
|
||||
// сигнатура, первым IHDR (13 байт), у каждого чанка верный CRC-32, есть хотя бы один IDAT,
|
||||
// последний чанк — пустой IEND, после него ничего нет. Усечённый или «склеенный»
|
||||
// файл этой проверки не проходит.
|
||||
func validPNGStructure(data []byte) bool {
|
||||
const signature = "\x89PNG\r\n\x1a\n"
|
||||
if len(data) < len(signature)+12 || string(data[:len(signature)]) != signature {
|
||||
return false
|
||||
}
|
||||
pos := len(signature)
|
||||
first, sawIDAT := true, false
|
||||
for {
|
||||
if pos+8 > len(data) {
|
||||
return false // обрыв внутри заголовка чанка
|
||||
}
|
||||
length := int64(binary.BigEndian.Uint32(data[pos:]))
|
||||
if length > 0x7fffffff {
|
||||
return false // по спецификации длина < 2^31
|
||||
}
|
||||
end := int64(pos) + 8 + length + 4 // длина + тип + данные + CRC
|
||||
if end > int64(len(data)) {
|
||||
return false // обрыв внутри данных/CRC
|
||||
}
|
||||
chunkType := string(data[pos+4 : pos+8])
|
||||
// CRC считается по типу и данным, без поля длины.
|
||||
if crc32.ChecksumIEEE(data[pos+4:end-4]) != binary.BigEndian.Uint32(data[end-4:end]) {
|
||||
return false
|
||||
}
|
||||
if first {
|
||||
if chunkType != "IHDR" || length != 13 {
|
||||
return false
|
||||
}
|
||||
first = false
|
||||
}
|
||||
switch chunkType {
|
||||
case "IDAT":
|
||||
sawIDAT = true
|
||||
case "IEND":
|
||||
return sawIDAT && length == 0 && end == int64(len(data))
|
||||
}
|
||||
pos = int(end)
|
||||
}
|
||||
}
|
||||
|
||||
// validJPEGStructure — дешёвая проверка целостности JPEG без декода:
|
||||
// файл начинается с SOI (FFD8), заканчивается EOI (FFD9; нулевой «паддинг» в хвосте
|
||||
// допускается), и до SOS (начало данных скана) все сегменты имеют корректную длину.
|
||||
// Усечённый JPEG (потерян хвост) не проходит из-за отсутствия EOI.
|
||||
func validJPEGStructure(data []byte) bool {
|
||||
if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 {
|
||||
return false
|
||||
}
|
||||
end := len(data)
|
||||
for end > 0 && data[end-1] == 0x00 {
|
||||
end--
|
||||
}
|
||||
if end < 2 || data[end-2] != 0xFF || data[end-1] != 0xD9 {
|
||||
return false
|
||||
}
|
||||
i := 2
|
||||
for i < len(data) {
|
||||
if data[i] != 0xFF {
|
||||
return false
|
||||
}
|
||||
for i < len(data) && data[i] == 0xFF { // fill-байты 0xFF перед маркером
|
||||
i++
|
||||
}
|
||||
if i >= len(data) {
|
||||
return false
|
||||
}
|
||||
marker := data[i]
|
||||
i++
|
||||
switch {
|
||||
case marker == 0xDA: // SOS: дальше энтропийно-кодированные данные, маркеры не идут подряд
|
||||
return true
|
||||
case marker == 0xD9: // EOI до SOS — в файле нет изображения
|
||||
return false
|
||||
case marker == 0x01 || (marker >= 0xD0 && marker <= 0xD8): // маркеры без длины
|
||||
continue
|
||||
default:
|
||||
if i+2 > len(data) {
|
||||
return false
|
||||
}
|
||||
segLen := int(binary.BigEndian.Uint16(data[i:]))
|
||||
if segLen < 2 || i+segLen > len(data) {
|
||||
return false
|
||||
}
|
||||
i += segLen
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,767 @@
|
||||
// Package api — HTTP-слой lab4 (lab3 + вложения в S3).
|
||||
//
|
||||
// Порядок обработки запроса:
|
||||
// 1. X-Request-Id и X-Instance-Id на каждый ответ, включая ошибки;
|
||||
// 2. журнал method/path/status без текста сообщений и без токена;
|
||||
// 3. маршрут;
|
||||
// 4. для защищённых маршрутов — только Bearer. Basic и X-User-Id доступ не дают.
|
||||
//
|
||||
// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL, Redis
|
||||
// и S3: без них нельзя честно принять запись, узнать, кто делает запрос, или принять/отдать
|
||||
// вложение (lab4: недоступный S3 → 503, балансировщик снимает реплику).
|
||||
//
|
||||
// POST сообщения требует Idempotency-Key; результат хранится в общей БД, а не в памяти реплики.
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gavrilenko-sxdees/lab4/internal/objectstore"
|
||||
"gavrilenko-sxdees/lab4/internal/session"
|
||||
"gavrilenko-sxdees/lab4/internal/store"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
userKey ctxKey = iota
|
||||
tokenKey
|
||||
requestIDKey
|
||||
)
|
||||
|
||||
const (
|
||||
challengeBasic = `Basic realm="messenger", charset="UTF-8"`
|
||||
challengeBearer = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
// Server связывает HTTP с PostgreSQL и Redis.
|
||||
type Server struct {
|
||||
Store *store.Store
|
||||
Sessions *session.Store
|
||||
Objects *objectstore.Store // приватный S3-bucket с оригиналами вложений
|
||||
InstanceID string
|
||||
ready atomic.Bool
|
||||
|
||||
// uploadSlots — семафор одновременных загрузок (ограничивает пик RAM, см. attachments.go).
|
||||
uploadSlots chan struct{}
|
||||
|
||||
// AfterObjectPut — тестовый hook: вызывается после успешного PUT в S3 и до INSERT в PG.
|
||||
// Позволяет в тестах смоделировать отказ «между S3 и БД». В проде всегда nil.
|
||||
AfterObjectPut func(key string)
|
||||
}
|
||||
|
||||
// New помечает процесс готовым. Реальная зависимость всё равно проверяется в /health/ready.
|
||||
// instanceID попадает в X-Instance-Id каждого ответа и стабилен на жизнь процесса.
|
||||
func New(st *store.Store, sessions *session.Store, objects *objectstore.Store, instanceID string) *Server {
|
||||
s := &Server{Store: st, Sessions: sessions, Objects: objects, InstanceID: instanceID}
|
||||
s.uploadSlots = make(chan struct{}, 4) // значение по умолчанию; main задаёт UPLOAD_MAX_CONCURRENCY
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
}
|
||||
|
||||
// BeginDrain вызывается на SIGTERM: новые клиенты видят 503 на /health/ready.
|
||||
// HAProxy/Traefik с httpchk на /health/ready перестаёт слать трафик на эту реплику.
|
||||
func (s *Server) BeginDrain() { s.ready.Store(false) }
|
||||
|
||||
// Handler собирает маршруты lab4.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /health/live", s.handleLive)
|
||||
mux.HandleFunc("GET /health/ready", s.handleReady)
|
||||
mux.HandleFunc("POST /api/v1/users", s.handleCreateUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", s.handleCreateSession)
|
||||
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", s.requireUser(s.handleRevokeSession))
|
||||
mux.HandleFunc("GET /api/v1/users/me", s.requireUser(s.handleMe))
|
||||
mux.HandleFunc("POST /api/v1/chats", s.requireUser(s.handleCreateChat))
|
||||
mux.HandleFunc("GET /api/v1/chats", s.requireUser(s.handleListChats))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", s.requireUser(s.handleGetChat))
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleCreateMessage))
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleListMessages))
|
||||
// lab4: вложения. Загрузка — сырой binary (не multipart), метаданные и байты — через API.
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", s.requireUser(s.handleUploadAttachment))
|
||||
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}", s.requireUser(s.handleGetAttachment))
|
||||
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", s.requireUser(s.handleDownloadAttachment))
|
||||
return s.withInstanceID(s.withRequestID(s.withAccessLog(mux)))
|
||||
}
|
||||
|
||||
func (s *Server) handleLive(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.ready.Load() {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down")
|
||||
return
|
||||
}
|
||||
// lab4: S3 — критичная зависимость обязательного синхронного пути (загрузка/скачивание).
|
||||
// Недоступное хранилище → 503, чтобы LB не слал трафик на реплику, которая не может
|
||||
// выполнить контракт; сообщения без вложений при этом тоже временно недоступны
|
||||
// (осознанное упрощение: readiness один на реплику, см. REPORT).
|
||||
if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil || s.Objects.Ping(r.Context()) != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeStrict(r, &body); err != nil {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
if !validUsername(body.Username) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid username")
|
||||
return
|
||||
}
|
||||
display := strings.TrimSpace(body.DisplayName)
|
||||
if display == "" || utf8.RuneCountInString(display) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name")
|
||||
return
|
||||
}
|
||||
if n := utf8.RuneCountInString(body.Password); n < 12 || n > 128 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid password")
|
||||
return
|
||||
}
|
||||
u, err := s.Store.CreateUser(r.Context(), body.Username, display, body.Password)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusConflict, "conflict", "username already taken")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, userDTO(u))
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
// Контракт: только Basic, без JSON body. Любые байты в теле — 400, не тихий игнор.
|
||||
rawBody, err := io.ReadAll(io.LimitReader(r.Body, 4096))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid body")
|
||||
return
|
||||
}
|
||||
if len(bytes.TrimSpace(rawBody)) != 0 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "session create must not have a body")
|
||||
return
|
||||
}
|
||||
username, password, ok := parseBasic(r.Header.Get("Authorization"))
|
||||
if !ok || !validUsername(username) {
|
||||
writeAuthError(w, r, challengeBasic)
|
||||
return
|
||||
}
|
||||
if n := utf8.RuneCountInString(password); n < 12 || n > 128 {
|
||||
writeAuthError(w, r, challengeBasic)
|
||||
return
|
||||
}
|
||||
u, err := s.Store.Authenticate(r.Context(), username, password)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeAuthError(w, r, challengeBasic)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
token, exp, err := s.Sessions.Issue(r.Context(), u.ID)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": formatTime(exp),
|
||||
"user": userDTO(u),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleRevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token, _ := r.Context().Value(tokenKey).(string)
|
||||
if err := s.Sessions.Revoke(r.Context(), token); err != nil {
|
||||
if errors.Is(err, session.ErrUnauthorized) {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.Store.GetUser(r.Context(), userFrom(r))
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, userDTO(u))
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := decodeStrict(r, &body); err != nil {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
title := strings.TrimSpace(body.Title)
|
||||
if title == "" || utf8.RuneCountInString(title) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid title")
|
||||
return
|
||||
}
|
||||
if len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids")
|
||||
return
|
||||
}
|
||||
uid := userFrom(r)
|
||||
seen := make(map[uuid.UUID]struct{}, len(body.MemberIDs))
|
||||
ids := make([]uuid.UUID, 0, len(body.MemberIDs))
|
||||
callerPresent := false
|
||||
for _, raw := range body.MemberIDs {
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member id")
|
||||
return
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "duplicate member id")
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == uid {
|
||||
callerPresent = true
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if !callerPresent {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "caller must be a member")
|
||||
return
|
||||
}
|
||||
chat, err := s.Store.CreateChat(r.Context(), title, ids)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "unknown member")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chatDTO(chat))
|
||||
}
|
||||
|
||||
func (s *Server) handleListChats(w http.ResponseWriter, r *http.Request) {
|
||||
uid := userFrom(r)
|
||||
limit, after, err := parsePage(r, "chats:"+uid.String())
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
items, next, err := s.Store.ListChats(r.Context(), uid, limit, after)
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
out := make([]any, len(items))
|
||||
for i := range items {
|
||||
out[i] = chatDTO(&items[i])
|
||||
}
|
||||
var cursor *store.PageCursor
|
||||
if next != nil {
|
||||
cursor = &store.PageCursor{Scope: "chats:" + uid.String(), CreatedAt: next.CreatedAt, ID: next.ID}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, pageDTO(out, cursor))
|
||||
}
|
||||
|
||||
func (s *Server) handleGetChat(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
chat, err := s.Store.GetChat(r.Context(), chatID, userFrom(r))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatDTO(chat))
|
||||
}
|
||||
|
||||
func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
idemKey := r.Header.Get("Idempotency-Key")
|
||||
if !validIdempotencyKey(idemKey) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid or missing Idempotency-Key")
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
if err := decodeStrict(r, &body); err != nil {
|
||||
writeDecodeErr(w, r, err)
|
||||
return
|
||||
}
|
||||
// attachment_ids: 0–10 уникальных UUID, по умолчанию []. Отсутствующий ключ, null и []
|
||||
// равны. UUID нормализуем (нижний регистр, канонический вид): иначе «ABC…» и «abc…»
|
||||
// давали бы разные хэши идемпотентности и дубль в uniqueItems.
|
||||
if len(body.AttachmentIDs) > 10 {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "too many attachment_ids")
|
||||
return
|
||||
}
|
||||
attachmentIDs := make([]uuid.UUID, 0, len(body.AttachmentIDs))
|
||||
canonicalIDs := make([]string, 0, len(body.AttachmentIDs))
|
||||
seenAtt := make(map[uuid.UUID]struct{}, len(body.AttachmentIDs))
|
||||
for _, raw := range body.AttachmentIDs {
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id")
|
||||
return
|
||||
}
|
||||
if _, dup := seenAtt[id]; dup {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "duplicate attachment id")
|
||||
return
|
||||
}
|
||||
seenAtt[id] = struct{}{}
|
||||
attachmentIDs = append(attachmentIDs, id)
|
||||
canonicalIDs = append(canonicalIDs, id.String())
|
||||
}
|
||||
// Непустота — по TrimSpace; длина и сохранение — по исходному тексту.
|
||||
// Иначе пробелы по краям пропадают, а строка «пробел + 4000 букв» проходит как 4000.
|
||||
// lab4: пустой текст допустим, если есть хотя бы одно вложение (сообщение «только файл»).
|
||||
if utf8.RuneCountInString(body.Text) > 4000 ||
|
||||
(strings.TrimSpace(body.Text) == "" && len(attachmentIDs) == 0) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid text")
|
||||
return
|
||||
}
|
||||
path := "/api/v1/chats/" + chatID.String() + "/messages"
|
||||
reqHash := idempotencyRequestHash(body.Text, canonicalIDs)
|
||||
result, err := s.Store.CreateMessageIdempotent(
|
||||
r.Context(), chatID, userFrom(r), body.Text, attachmentIDs,
|
||||
http.MethodPost, path, idemKey, reqHash,
|
||||
)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, store.ErrIdempotencyConflict) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, store.ErrAttachmentNotReady) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, 0, "", "")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, messageDTO(result.Message))
|
||||
}
|
||||
|
||||
func (s *Server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
chatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
|
||||
return
|
||||
}
|
||||
scope := "chat:" + chatID.String()
|
||||
limit, after, err := parsePage(r, scope)
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
items, next, err := s.Store.ListMessages(r.Context(), chatID, userFrom(r), limit, after)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
return
|
||||
}
|
||||
out := make([]any, len(items))
|
||||
for i := range items {
|
||||
out[i] = messageDTO(&items[i])
|
||||
}
|
||||
var cursor *store.PageCursor
|
||||
if next != nil {
|
||||
cursor = &store.PageCursor{Scope: scope, CreatedAt: next.CreatedAt, ID: next.ID}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, pageDTO(out, cursor))
|
||||
}
|
||||
|
||||
// requireUser принимает только Authorization: Bearer. X-User-Id не читается.
|
||||
// Basic на бизнес-методе — тот же 401, но с Bearer-challenge, не с Basic.
|
||||
func (s *Server) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if strings.HasPrefix(strings.ToLower(header), "basic ") {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
token, ok := parseBearer(header)
|
||||
if !ok {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
uid, err := s.Sessions.Lookup(r.Context(), token)
|
||||
if errors.Is(err, session.ErrUnauthorized) {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userKey, uid)
|
||||
ctx = context.WithValue(ctx, tokenKey, token)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func userFrom(r *http.Request) uuid.UUID {
|
||||
id, _ := r.Context().Value(userKey).(uuid.UUID)
|
||||
return id
|
||||
}
|
||||
|
||||
func (s *Server) withRequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
rid := r.Header.Get("X-Request-Id")
|
||||
if rid == "" {
|
||||
rid = uuid.NewString()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", rid)
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, rid)))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) withInstanceID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", s.InstanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// validIdempotencyKey — ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
func validIdempotencyKey(key string) bool {
|
||||
if len(key) < 1 || len(key) > 128 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(key); i++ {
|
||||
c := key[i]
|
||||
switch {
|
||||
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9':
|
||||
case c == '.', c == '_', c == ':', c == '-':
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// idempotencyRequestHash канонизирует тело: порядок ключей JSON не важен,
|
||||
// отсутствующий attachment_ids равен []. Хэш — SHA-256 hex.
|
||||
func idempotencyRequestHash(text string, attachmentIDs []string) string {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
payload, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{Text: text, AttachmentIDs: attachmentIDs})
|
||||
sum := sha256.Sum256(payload)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *Server) withAccessLog(next http.Handler) http.Handler {
|
||||
quiet := strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "0") || strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "false")
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
if quiet && rec.status < 400 {
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(r.URL.Path, "/health/") && rec.status == http.StatusOK {
|
||||
return
|
||||
}
|
||||
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||
// path без query: в cursor нет секрета, но и текста сообщения в логе быть не должно.
|
||||
log.Printf("method=%s path=%s status=%d request_id=%s duration_ms=%d",
|
||||
r.Method, r.URL.Path, rec.status, rid, time.Since(start).Milliseconds())
|
||||
})
|
||||
}
|
||||
|
||||
func parsePage(r *http.Request, expectedScope string) (int, *store.PageCursor, error) {
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 {
|
||||
return 0, nil, fmt.Errorf("invalid limit")
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
rawCursor := r.URL.Query().Get("cursor")
|
||||
if rawCursor == "" {
|
||||
return limit, nil, nil
|
||||
}
|
||||
cur, err := decodeCursor(rawCursor)
|
||||
if err != nil || cur.Scope != expectedScope {
|
||||
return 0, nil, fmt.Errorf("invalid cursor")
|
||||
}
|
||||
return limit, cur, nil
|
||||
}
|
||||
|
||||
func encodeCursor(c *store.PageCursor) string {
|
||||
payload := fmt.Sprintf("%s|%s|%s", c.Scope, c.CreatedAt.UTC().Format(time.RFC3339Nano), c.ID.String())
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(payload))
|
||||
}
|
||||
|
||||
func decodeCursor(raw string) (*store.PageCursor, error) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.SplitN(string(b), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil, fmt.Errorf("bad cursor")
|
||||
}
|
||||
ts, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &store.PageCursor{Scope: parts[0], CreatedAt: ts.UTC(), ID: id}, nil
|
||||
}
|
||||
|
||||
func validUsername(s string) bool {
|
||||
if len(s) < 3 || len(s) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, c := range s {
|
||||
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func decodeStrict(r *http.Request, dst any) error {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ct)), "application/json") {
|
||||
return errUnsupported
|
||||
}
|
||||
// Читаем тело целиком: Decoder.More() не ловит хвост вида {"text":"x"}} —
|
||||
// после одного объекта More()=false, а лишняя скобка всё равно остаётся.
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
rest := bytes.TrimSpace(raw[dec.InputOffset():])
|
||||
if len(rest) != 0 {
|
||||
return errMalformed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
errUnsupported = errors.New("unsupported media type")
|
||||
errMalformed = errors.New("malformed json")
|
||||
)
|
||||
|
||||
func writeDecodeErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, errUnsupported) {
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type")
|
||||
return
|
||||
}
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed json")
|
||||
}
|
||||
|
||||
func parseBasic(header string) (string, string, bool) {
|
||||
const prefix = "basic "
|
||||
if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(header[len(prefix):]))
|
||||
if err != nil || !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
user, pass, ok := strings.Cut(string(raw), ":")
|
||||
if !ok || user == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return user, pass, true
|
||||
}
|
||||
|
||||
func parseBearer(header string) (string, bool) {
|
||||
const prefix = "bearer "
|
||||
if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(header[len(prefix):])
|
||||
if token == "" || strings.Contains(token, " ") {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func userDTO(u *store.User) map[string]any {
|
||||
return map[string]any{
|
||||
"id": u.ID.String(),
|
||||
"username": u.Username,
|
||||
"display_name": u.DisplayName,
|
||||
"created_at": formatTime(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func chatDTO(c *store.Chat) map[string]any {
|
||||
ids := make([]string, len(c.MemberIDs))
|
||||
for i, id := range c.MemberIDs {
|
||||
ids[i] = id.String()
|
||||
}
|
||||
return map[string]any{
|
||||
"id": c.ID.String(),
|
||||
"title": c.Title,
|
||||
"member_ids": ids,
|
||||
"created_at": formatTime(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func messageDTO(m *store.Message) map[string]any {
|
||||
// attachment_ids обязателен в ответе (контракт 1.4.0): всегда массив, не null.
|
||||
ids := make([]string, len(m.AttachmentIDs))
|
||||
for i, id := range m.AttachmentIDs {
|
||||
ids[i] = id.String()
|
||||
}
|
||||
return map[string]any{
|
||||
"id": m.ID.String(),
|
||||
"chat_id": m.ChatID.String(),
|
||||
"sender_id": m.SenderID.String(),
|
||||
"text": m.Text,
|
||||
"created_at": formatTime(m.CreatedAt),
|
||||
"attachment_ids": ids,
|
||||
}
|
||||
}
|
||||
|
||||
func pageDTO(items []any, next *store.PageCursor) map[string]any {
|
||||
var cursor any
|
||||
if next != nil {
|
||||
cursor = encodeCursor(next)
|
||||
}
|
||||
if items == nil {
|
||||
items = []any{}
|
||||
}
|
||||
return map[string]any{"items": items, "next_cursor": cursor}
|
||||
}
|
||||
|
||||
func formatTime(t time.Time) string {
|
||||
return t.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z")
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(v)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
|
||||
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||
if rid == "" {
|
||||
rid = w.Header().Get("X-Request-Id")
|
||||
}
|
||||
writeJSON(w, status, map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": rid,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func writeAuthError(w http.ResponseWriter, r *http.Request, challenge string) {
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
writeError(w, r, http.StatusUnauthorized, "unauthorized", "authentication required")
|
||||
}
|
||||
|
||||
// writeStoreErr прячет текст драйвера. fallbackStatus используется для ожидаемой доменной ошибки.
|
||||
func (s *Server) writeStoreErr(w http.ResponseWriter, r *http.Request, err error, fallbackStatus int, fallbackCode, fallbackMessage string) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body")
|
||||
case errors.Is(err, store.ErrConflict) && fallbackStatus != 0:
|
||||
writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage)
|
||||
case errors.Is(err, store.ErrNotFound) && fallbackStatus != 0:
|
||||
if fallbackCode == "unauthorized" {
|
||||
writeAuthError(w, r, challengeBearer)
|
||||
return
|
||||
}
|
||||
writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage)
|
||||
case errors.Is(err, store.ErrInvalidCursor):
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor")
|
||||
default:
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
writeError(w, r, http.StatusConflict, "conflict", "username already taken")
|
||||
return
|
||||
}
|
||||
// В лог — только тип, без SQL и без текста, который драйвер мог вложить в ошибку.
|
||||
log.Printf("request_id=%s store_error_type=%T", requestID(r), err)
|
||||
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
}
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
rid, _ := r.Context().Value(requestIDKey).(string)
|
||||
return rid
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Package auth хранит пароли через Argon2id.
|
||||
//
|
||||
// bcrypt отвергнут: библиотека молча режет пароль на 72 байта, а контракт
|
||||
// разрешает до 128 Unicode code points, включая символы вне ASCII.
|
||||
// Argon2id принимает пароль целиком. Параметры — интерактивные, не «серверные»
|
||||
// на сотни миллисекунд: smoke создаёт несколько пользователей подряд.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 2
|
||||
argonMemory = 19 * 1024 // KiB, около 19 MiB
|
||||
argonThreads = 1
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
// Hasher умеет хешировать и проверять. dummy — хеш случайного пароля,
|
||||
// чтобы отсутствующий username занимал примерно столько же CPU, сколько неверный пароль.
|
||||
type Hasher struct {
|
||||
dummy string
|
||||
}
|
||||
|
||||
// NewHasher готовит dummy-хеш один раз на процесс.
|
||||
func NewHasher() (*Hasher, error) {
|
||||
dummy, err := Hash(randomPassword())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Hasher{dummy: dummy}, nil
|
||||
}
|
||||
|
||||
// Hash возвращает PHC-строку. Её пишем в users.password_hash.
|
||||
func Hash(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
|
||||
argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(sum),
|
||||
), nil
|
||||
}
|
||||
|
||||
// Verify сравнивает пароль с PHC-строкой. При битой строке возвращает false, не панику.
|
||||
func (h *Hasher) Verify(encoded, password string) bool {
|
||||
if encoded == "" {
|
||||
encoded = h.dummy
|
||||
}
|
||||
ok, err := verify(encoded, password)
|
||||
if err != nil {
|
||||
// Всё равно тратим время dummy-проверки, чтобы ветка ошибки не была мгновенной.
|
||||
_, _ = verify(h.dummy, password)
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// Burn тратит время проверки, когда пользователя нет. Результат всегда false.
|
||||
func (h *Hasher) Burn(password string) {
|
||||
_, _ = verify(h.dummy, password)
|
||||
}
|
||||
|
||||
func verify(encoded, password string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
// ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash]
|
||||
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||
return false, fmt.Errorf("bad hash")
|
||||
}
|
||||
var memory uint32
|
||||
var timeCost uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if memory != argonMemory || timeCost != argonTime || threads != argonThreads {
|
||||
return false, fmt.Errorf("unexpected argon2 parameters")
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, uint32(len(want)))
|
||||
// ConstantTimeCompare не даёт выйти на первом несовпавшем байте.
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func randomPassword() string {
|
||||
buf := make([]byte, 24)
|
||||
_, _ = rand.Read(buf)
|
||||
return base64.RawStdEncoding.EncodeToString(buf)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// Package config читает настройки процесса из окружения.
|
||||
//
|
||||
// Прямые URL (DATABASE_URL, REDIS_URL) удобны в Compose.
|
||||
// Вариант *_FILE из .env.example нужен, если секрет смонтирован файлом:
|
||||
// тогда в переменной лежит путь, а не сам секрет.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config — всё, что процесс обязан знать до открытия соединений.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
DatabaseURL string
|
||||
RedisURL string
|
||||
SessionTTL time.Duration
|
||||
InstanceID string
|
||||
MaxConns int32
|
||||
RunMigrations bool
|
||||
IdempotencyTTL time.Duration
|
||||
|
||||
// --- lab4: объектное хранилище (S3-совместимое, MinIO) ---
|
||||
|
||||
// S3Endpoint — URL S3 API внутри сети Compose (http://minio:9000).
|
||||
S3Endpoint string
|
||||
// S3Region — для SigV4 нужен любой регион; у MinIO по умолчанию us-east-1.
|
||||
S3Region string
|
||||
// S3Bucket — приватный bucket с оригиналами вложений.
|
||||
S3Bucket string
|
||||
// S3AccessKey/S3SecretKey — НЕ root MinIO, а отдельный пользователь messenger-api
|
||||
// с политикой только на этот bucket (создаётся сервисом minio-init).
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
// S3ForcePathStyle — path-style адресация (http://minio:9000/bucket/key).
|
||||
// У MinIO в Compose нет wildcard-DNS для bucket.minio, поэтому virtual-hosted не работает.
|
||||
S3ForcePathStyle bool
|
||||
// S3OrphanGrace — «льготный период» reconciler: объект без строки в БД младше этого
|
||||
// возраста считается ещё загружаемым (PUT уже был, INSERT ещё не успел) и не трогается.
|
||||
S3OrphanGrace time.Duration
|
||||
// UploadMaxConcurrency — сколько загрузок одна реплика буферизует в RAM одновременно.
|
||||
// Остальные ждут в очереди (см. api.Server.uploadSlots), поэтому пик памяти ограничен
|
||||
// сверху UploadMaxConcurrency * 10 MiB, а не числом клиентов.
|
||||
UploadMaxConcurrency int
|
||||
}
|
||||
|
||||
// Load собирает Config. Пустой URL без файла — ошибка запуска, а не тихий дефолт на чужой хост.
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Env: getenv("APP_ENV", "lab"),
|
||||
}
|
||||
port, err := strconv.Atoi(getenv("APP_PORT", "8080"))
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return cfg, fmt.Errorf("invalid APP_PORT")
|
||||
}
|
||||
cfg.Port = port
|
||||
|
||||
ttlSec, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
if err != nil || ttlSec < 1 || ttlSec > 7*24*3600 {
|
||||
return cfg, fmt.Errorf("invalid SESSION_TTL_SECONDS")
|
||||
}
|
||||
cfg.SessionTTL = time.Duration(ttlSec) * time.Second
|
||||
|
||||
idemTTL, err := strconv.Atoi(getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
if err != nil || idemTTL < 60 || idemTTL > 7*24*3600 {
|
||||
return cfg, fmt.Errorf("invalid IDEMPOTENCY_TTL_SECONDS")
|
||||
}
|
||||
cfg.IdempotencyTTL = time.Duration(idemTTL) * time.Second
|
||||
|
||||
maxConns, err := strconv.Atoi(getenv("DB_MAX_CONNS", "5"))
|
||||
if err != nil || maxConns < 1 || maxConns > 50 {
|
||||
return cfg, fmt.Errorf("invalid DB_MAX_CONNS")
|
||||
}
|
||||
cfg.MaxConns = int32(maxConns)
|
||||
|
||||
cfg.DatabaseURL, err = getenvOrFile("DATABASE_URL", "DATABASE_URL_FILE")
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.RedisURL, err = getenvOrFile("REDIS_URL", "CACHE_URL_FILE")
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
if err := loadS3(&cfg); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
// X-Instance-Id стабилен на жизнь процесса. В Compose hostname = id контейнера,
|
||||
// поэтому stop-one.sh сопоставляет TARGET_INSTANCE_ID с Config.Hostname.
|
||||
cfg.InstanceID = strings.TrimSpace(os.Getenv("INSTANCE_ID"))
|
||||
if cfg.InstanceID == "" {
|
||||
host, herr := os.Hostname()
|
||||
if herr != nil || strings.TrimSpace(host) == "" {
|
||||
return cfg, fmt.Errorf("set INSTANCE_ID or ensure hostname is available")
|
||||
}
|
||||
cfg.InstanceID = host
|
||||
}
|
||||
|
||||
// Миграции по умолчанию выключены у API-реплик: их гоняет одноразовый сервис migrate.
|
||||
// Для локальных тестов и -migrate флага включается явно.
|
||||
cfg.RunMigrations = truthy(os.Getenv("RUN_MIGRATIONS"))
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// loadS3 читает S3_* переменные. Ключи, как и DATABASE_URL, можно передать файлом
|
||||
// (S3_ACCESS_KEY_FILE / S3_SECRET_KEY_FILE): так секрет не попадает в `docker inspect`.
|
||||
// Пустой endpoint/ключ — ошибка запуска: тихий дефолт на «какой-нибудь» S3 опаснее падения.
|
||||
func loadS3(cfg *Config) error {
|
||||
var err error
|
||||
cfg.S3Endpoint = strings.TrimSpace(os.Getenv("S3_ENDPOINT"))
|
||||
if cfg.S3Endpoint == "" {
|
||||
return fmt.Errorf("set S3_ENDPOINT")
|
||||
}
|
||||
cfg.S3Region = getenv("S3_REGION", "us-east-1")
|
||||
cfg.S3Bucket = getenv("S3_BUCKET", "messenger")
|
||||
cfg.S3AccessKey, err = getenvOrFile("S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.S3SecretKey, err = getenvOrFile("S3_SECRET_KEY", "S3_SECRET_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// По умолчанию path-style включён: для MinIO в Compose это единственный рабочий вариант.
|
||||
cfg.S3ForcePathStyle = truthy(getenv("S3_FORCE_PATH_STYLE", "1"))
|
||||
|
||||
// Grace по умолчанию 300 с: с запасом больше любой реальной загрузки (таймаут PUT 10 с)
|
||||
// и задержки между PUT и COMMIT. 0 допустим (удалять сразу) — нужен только тестам.
|
||||
graceSec, err := strconv.Atoi(getenv("S3_ORPHAN_GRACE_SECONDS", "300"))
|
||||
if err != nil || graceSec < 0 || graceSec > 7*24*3600 {
|
||||
return fmt.Errorf("invalid S3_ORPHAN_GRACE_SECONDS")
|
||||
}
|
||||
cfg.S3OrphanGrace = time.Duration(graceSec) * time.Second
|
||||
|
||||
cfg.UploadMaxConcurrency, err = strconv.Atoi(getenv("UPLOAD_MAX_CONCURRENCY", "4"))
|
||||
if err != nil || cfg.UploadMaxConcurrency < 1 || cfg.UploadMaxConcurrency > 64 {
|
||||
return fmt.Errorf("invalid UPLOAD_MAX_CONCURRENCY")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Addr — адрес Listen, обычно 0.0.0.0:8080 внутри контейнера.
|
||||
func (c Config) Addr() string {
|
||||
return fmt.Sprintf("%s:%d", c.Host, c.Port)
|
||||
}
|
||||
|
||||
func getenv(key, fallback string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getenvOrFile(directKey, fileKey string) (string, error) {
|
||||
if v := strings.TrimSpace(os.Getenv(directKey)); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv(fileKey))
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("set %s or %s", directKey, fileKey)
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", fileKey, err)
|
||||
}
|
||||
v := strings.TrimSpace(string(b))
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("%s is empty", fileKey)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func truthy(v string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
// Package objectstore — тонкая обёртка над aws-sdk-go-v2 для приватного S3-bucket (MinIO).
|
||||
//
|
||||
// Зачем отдельный пакет:
|
||||
// - HTTP-слой и reconciler работают с узким набором операций (Put/Get/Delete/Head/List/
|
||||
// EnsureBucket/Ping) и с двумя доменными ошибками, а не с типами SDK;
|
||||
// - все таймауты и настройки «совместимости с MinIO» собраны в одном месте;
|
||||
// - наружу (в ответ клиенту, в лог) не уходят тексты ошибок SDK: в них бывают
|
||||
// endpoint, имя bucket и фрагменты запроса.
|
||||
//
|
||||
// Байты вложений живут ТОЛЬКО здесь. Ни локальный диск API-реплики, ни PostgreSQL
|
||||
// оригиналов не хранят: любая реплика после остановки соседней отдаёт тот же файл.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/aws/smithy-go"
|
||||
)
|
||||
|
||||
// Доменные ошибки. HTTP-слой различает «нет объекта» и «хранилище недоступно».
|
||||
var (
|
||||
// ErrNotFound — объекта (или bucket) нет.
|
||||
ErrNotFound = errors.New("object not found")
|
||||
// ErrUnavailable — S3 недоступен, таймаут, отказ в доступе или любая иная ошибка
|
||||
// транспорта. Клиенту это всегда 503: он не должен видеть подробности.
|
||||
ErrUnavailable = errors.New("object store unavailable")
|
||||
)
|
||||
|
||||
// Таймауты операций. Подобраны под HAProxy (timeout server 15s): S3-запрос обязан
|
||||
// закончиться раньше, чем балансировщик оборвёт клиента, иначе получим 504 вместо
|
||||
// управляемого 503.
|
||||
const (
|
||||
pingTimeout = 700 * time.Millisecond // /health/ready опрашивается раз в секунду
|
||||
putTimeout = 10 * time.Second // до 10 MiB по локальной сети
|
||||
smallOpTimeout = 3 * time.Second // Head/Delete
|
||||
listTimeout = 10 * time.Second // страница List до 1000 ключей
|
||||
)
|
||||
|
||||
// Config — параметры подключения. Секреты приходят из окружения, в лог не пишутся.
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
ForcePathStyle bool
|
||||
}
|
||||
|
||||
// Store — клиент одного bucket. Безопасен для конкурентного использования.
|
||||
type Store struct {
|
||||
client *s3.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
// ObjectInfo — метаданные объекта (из Head или List).
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
ContentType string // пусто для List: он тип не возвращает
|
||||
LastModified time.Time
|
||||
ETag string
|
||||
}
|
||||
|
||||
// ListPage — одна страница List. NextToken пуст, когда страниц больше нет.
|
||||
type ListPage struct {
|
||||
Objects []ObjectInfo
|
||||
NextToken string
|
||||
}
|
||||
|
||||
// New создаёт клиента. Сетевых вызовов не делает: доступность проверяют Ping/EnsureBucket.
|
||||
func New(cfg Config) (*Store, error) {
|
||||
if cfg.Endpoint == "" || cfg.Bucket == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
|
||||
return nil, fmt.Errorf("objectstore: endpoint, bucket and credentials are required")
|
||||
}
|
||||
region := cfg.Region
|
||||
if region == "" {
|
||||
region = "us-east-1"
|
||||
}
|
||||
|
||||
// Собственный HTTP-клиент: короткий dial-таймаут нужен, чтобы остановленный MinIO
|
||||
// давал отказ за ~2 с, а не за системные минуты. ResponseHeaderTimeout защищает от
|
||||
// «подвисшего» сервера, который принял соединение, но не отвечает.
|
||||
httpClient := awshttp.NewBuildableClient().
|
||||
WithDialerOptions(func(d *net.Dialer) {
|
||||
d.Timeout = 2 * time.Second
|
||||
d.KeepAlive = 30 * time.Second
|
||||
}).
|
||||
WithTransportOptions(func(tr *http.Transport) {
|
||||
tr.ResponseHeaderTimeout = 8 * time.Second
|
||||
tr.MaxIdleConnsPerHost = 16
|
||||
tr.IdleConnTimeout = 60 * time.Second
|
||||
})
|
||||
|
||||
awsCfg := aws.Config{
|
||||
Region: region,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
HTTPClient: httpClient,
|
||||
// Две попытки вместо трёх по умолчанию: повтор нужен для редких обрывов,
|
||||
// но при лежащем S3 мы хотим быстро ответить 503, а не копить backoff.
|
||||
RetryMaxAttempts: 2,
|
||||
}
|
||||
client := s3.NewFromConfig(awsCfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(cfg.Endpoint)
|
||||
// MinIO в Compose доступен только по имени хоста minio — bucket в имени хоста
|
||||
// (virtual-hosted) невозможен, поэтому path-style.
|
||||
o.UsePathStyle = cfg.ForcePathStyle
|
||||
// Свежие версии SDK по умолчанию добавляют CRC32-trailer ко всем PUT. Для
|
||||
// не-AWS бэкендов это источник несовместимостей; нам достаточно обычной SigV4
|
||||
// подписи полезной нагрузки (тело — seekable bytes.Reader).
|
||||
o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired
|
||||
o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired
|
||||
})
|
||||
return &Store{client: client, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
// Bucket возвращает имя bucket (для логов bootstrap; клиенту не отдаётся).
|
||||
func (s *Store) Bucket() string { return s.bucket }
|
||||
|
||||
// Ping — проверка для /health/ready: HeadBucket. Требует s3:ListBucket, которое
|
||||
// есть в политике messenger-api. Короткий таймаут: readiness не должен висеть.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, pingTimeout)
|
||||
defer cancel()
|
||||
if _, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(s.bucket)}); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EnsureBucket идемпотентно гарантирует существование bucket.
|
||||
//
|
||||
// Основной путь создания — сервис minio-init (root-учётка). API-пользователь по политике
|
||||
// НЕ может создавать buckets, поэтому здесь: HeadBucket → если нет, пробуем CreateBucket
|
||||
// (сработает на S3-бэкендах с более широкими правами, например в локальном dev) и
|
||||
// «уже существует/уже наш» считаем успехом. Повторный вызов безопасен.
|
||||
func (s *Store) EnsureBucket(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, smallOpTimeout)
|
||||
defer cancel()
|
||||
_, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(s.bucket)})
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !isNotFound(err) {
|
||||
return fmt.Errorf("head bucket: %w", classify(err))
|
||||
}
|
||||
_, err = s.client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(s.bucket)})
|
||||
if err != nil {
|
||||
var owned *types.BucketAlreadyOwnedByYou
|
||||
var exists *types.BucketAlreadyExists
|
||||
if errors.As(err, &owned) || errors.As(err, &exists) {
|
||||
return nil // гонка с другой репликой/minio-init: bucket уже есть
|
||||
}
|
||||
return fmt.Errorf("create bucket (запустите minio-init): %w", classify(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Put кладёт объект целиком. body должен быть seekable (bytes.Reader): SDK тогда сам
|
||||
// считает хеш полезной нагрузки для SigV4 и умеет перечитать тело при retry.
|
||||
// Объект без ACL: bucket приватный, анонимный доступ запрещён политикой.
|
||||
func (s *Store) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, putTimeout)
|
||||
defer cancel()
|
||||
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
ContentLength: aws.Int64(size),
|
||||
ContentType: aws.String(contentType),
|
||||
})
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// Get открывает поток объекта. Вызывающий ОБЯЗАН закрыть ReadCloser.
|
||||
// Таймаут здесь не навешиваем: контекст живёт, пока тело стримится клиенту
|
||||
// (его ограничивает ctx запроса и WriteTimeout HTTP-сервера).
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) {
|
||||
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, ObjectInfo{}, classify(err)
|
||||
}
|
||||
info := ObjectInfo{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(out.ContentLength),
|
||||
ContentType: aws.ToString(out.ContentType),
|
||||
LastModified: aws.ToTime(out.LastModified),
|
||||
ETag: aws.ToString(out.ETag),
|
||||
}
|
||||
return out.Body, info, nil
|
||||
}
|
||||
|
||||
// Head возвращает метаданные без тела. ErrNotFound — объекта нет.
|
||||
func (s *Store) Head(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, smallOpTimeout)
|
||||
defer cancel()
|
||||
out, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return ObjectInfo{}, classify(err)
|
||||
}
|
||||
return ObjectInfo{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(out.ContentLength),
|
||||
ContentType: aws.ToString(out.ContentType),
|
||||
LastModified: aws.ToTime(out.LastModified),
|
||||
ETag: aws.ToString(out.ETag),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Delete удаляет объект. Отсутствующий объект — не ошибка (S3 DeleteObject идемпотентен),
|
||||
// что важно и для компенсации после сбоя PG, и для повторных запусков reconciler.
|
||||
func (s *Store) Delete(ctx context.Context, key string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, smallOpTimeout)
|
||||
defer cancel()
|
||||
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil && isNotFound(err) {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// List возвращает одну страницу ключей с префиксом prefix в лексикографическом порядке
|
||||
// (так S3 отдаёт ListObjectsV2). token — из предыдущей страницы, пустой для первой.
|
||||
// Именно порядок позволяет reconciler сливать листинг с отсортированной выборкой из БД
|
||||
// (merge-join) без загрузки всех ключей в память.
|
||||
func (s *Store) List(ctx context.Context, prefix, token string, maxKeys int32) (ListPage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, listTimeout)
|
||||
defer cancel()
|
||||
in := &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
MaxKeys: aws.Int32(maxKeys),
|
||||
}
|
||||
if token != "" {
|
||||
in.ContinuationToken = aws.String(token)
|
||||
}
|
||||
out, err := s.client.ListObjectsV2(ctx, in)
|
||||
if err != nil {
|
||||
return ListPage{}, classify(err)
|
||||
}
|
||||
page := ListPage{Objects: make([]ObjectInfo, 0, len(out.Contents))}
|
||||
for _, o := range out.Contents {
|
||||
page.Objects = append(page.Objects, ObjectInfo{
|
||||
Key: aws.ToString(o.Key),
|
||||
Size: aws.ToInt64(o.Size),
|
||||
LastModified: aws.ToTime(o.LastModified),
|
||||
ETag: aws.ToString(o.ETag),
|
||||
})
|
||||
}
|
||||
if aws.ToBool(out.IsTruncated) {
|
||||
page.NextToken = aws.ToString(out.NextContinuationToken)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// classify сводит ошибки SDK к двум доменным. Исходный текст не пробрасываем.
|
||||
func classify(err error) error {
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case isNotFound(err):
|
||||
return ErrNotFound
|
||||
default:
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
// isNotFound распознаёт «нет объекта/bucket» по типам и кодам ответа S3.
|
||||
// HeadObject отдаёт безымянный 404 (types.NotFound), GetObject — NoSuchKey.
|
||||
func isNotFound(err error) bool {
|
||||
var noKey *types.NoSuchKey
|
||||
var notFound *types.NotFound
|
||||
var noBucket *types.NoSuchBucket
|
||||
if errors.As(err, &noKey) || errors.As(err, ¬Found) || errors.As(err, &noBucket) {
|
||||
return true
|
||||
}
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NoSuchKey", "NotFound", "NoSuchBucket":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
// Package reconcile — сверка двух хранилищ вложений: S3 (байты) и PostgreSQL (метаданные).
|
||||
//
|
||||
// Почему сверка нужна вообще. Общей транзакции у S3 и PostgreSQL нет. Загрузка делает
|
||||
// PUT в S3, затем INSERT в БД (см. internal/api/attachments.go). Между шагами процесс может
|
||||
// умереть, а компенсирующее удаление — не сработать. Получаются два вида расхождений:
|
||||
//
|
||||
// orphan — объект в S3 есть, строки в БД нет. Безвредно для пользователя, но это вечный
|
||||
// мусор и расход места. Лечение: удалить объект, НО только старше grace-периода
|
||||
// (иначе можно снести объект, у которого INSERT ещё «в полёте»).
|
||||
// missing — строка в БД есть, объекта в S3 нет (удалён руками, потерян, сбой диска).
|
||||
// Пользователь получит ошибку при скачивании. Автоматически данные не вернуть,
|
||||
// поэтому по умолчанию только ОТЧЁТ. Опционально (PruneMissing) удаляется строка,
|
||||
// которая одновременно старая И неиспользуемая; «свежие» и «используемые»
|
||||
// сообщениями вложения не удаляются никогда.
|
||||
//
|
||||
// Алгоритм — merge-join двух ОТСОРТИРОВАННЫХ потоков (ключи S3 в лексикографическом порядке
|
||||
// и attachments.object_key COLLATE "C" в БД). Обе стороны читаются страницами, поэтому память
|
||||
// O(размер страницы), а не O(число объектов), а стоимость — O(n) по числу объектов
|
||||
// плюс HEAD только для редких кандидатов в missing.
|
||||
//
|
||||
// Безопасность:
|
||||
// - dry-run (DryRun) ничего не удаляет и не изменяет: только лог и отчёт;
|
||||
// - повторный запуск идемпотентен (после исправления расхождений находит 0);
|
||||
// - ключи вне схемы attachments/{uuid}/{uuid} никогда не удаляются;
|
||||
// - перед удалением orphan — повторная проверка строки в БД (сужает окно гонки);
|
||||
// - строки, на которые ссылаются сообщения, защищены ещё и внешним ключом PostgreSQL.
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gavrilenko-sxdees/lab4/internal/objectstore"
|
||||
"gavrilenko-sxdees/lab4/internal/store"
|
||||
)
|
||||
|
||||
// KeyPrefix — единственный префикс, который обходит reconciler.
|
||||
const KeyPrefix = "attachments/"
|
||||
|
||||
// pageSize — размер страницы и для S3 (максимум ListObjectsV2 — 1000), и для БД.
|
||||
const defaultPageSize = 1000
|
||||
|
||||
// maxSamples ограничивает число ключей-примеров в отчёте, чтобы вывод не разрастался.
|
||||
const maxSamples = 50
|
||||
|
||||
// Options — параметры запуска.
|
||||
type Options struct {
|
||||
// DryRun — ничего не менять, только сообщить, что было бы сделано.
|
||||
DryRun bool
|
||||
// Grace — минимальный возраст orphan-объекта (по LastModified в S3) и «неиспользуемой»
|
||||
// строки (по created_at), после которого их можно трогать. Берётся из S3_ORPHAN_GRACE_SECONDS.
|
||||
Grace time.Duration
|
||||
// PruneMissing — удалять строки без объекта, если они старше Grace и не прикреплены
|
||||
// ни к одному сообщению. Без флага missing только отчётность.
|
||||
PruneMissing bool
|
||||
// PageSize — для тестов; по умолчанию 1000.
|
||||
PageSize int
|
||||
// Now — для тестов; по умолчанию time.Now.
|
||||
Now func() time.Time
|
||||
// Logf — построчный лог (по умолчанию молчит). В main — log.Printf.
|
||||
Logf func(format string, args ...any)
|
||||
}
|
||||
|
||||
// Report — итог запуска. Печатается в JSON и годится как evidence.
|
||||
type Report struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
GraceSeconds float64 `json:"grace_seconds"`
|
||||
PruneMissing bool `json:"prune_missing"`
|
||||
|
||||
// Стоимость обхода.
|
||||
S3ObjectsScanned int `json:"s3_objects_scanned"`
|
||||
DBRowsScanned int `json:"db_rows_scanned"`
|
||||
S3ListCalls int `json:"s3_list_calls"`
|
||||
DBPages int `json:"db_pages"`
|
||||
HeadCalls int `json:"s3_head_calls"`
|
||||
DeleteCalls int `json:"s3_delete_calls"`
|
||||
DurationMs int64 `json:"duration_ms"`
|
||||
|
||||
Matched int `json:"matched"` // и объект, и строка
|
||||
|
||||
// Orphan: объект без строки.
|
||||
OrphansFound int `json:"orphans_found"` // старше grace, подлежат удалению
|
||||
OrphansDeleted int `json:"orphans_deleted"` // реально удалено (0 в dry-run)
|
||||
OrphansFresh int `json:"orphans_fresh"` // моложе grace — не тронуты
|
||||
OrphansRaced int `json:"orphans_raced"` // перед удалением строка появилась — не тронуты
|
||||
UnknownKeys int `json:"unknown_keys"` // ключ вне схемы attachments/{uuid}/{uuid} — не тронуты
|
||||
OrphanSampleKey []string `json:"orphan_sample_keys,omitempty"`
|
||||
|
||||
// Missing: строка без объекта.
|
||||
MissingFound int `json:"missing_found"` // подтверждено HEAD
|
||||
MissingUsed int `json:"missing_used"` // прикреплено к сообщению — ТРЕБУЕТ внимания, не удаляется
|
||||
MissingFresh int `json:"missing_fresh"` // моложе grace — не тронуты
|
||||
MissingStale int `json:"missing_stale"` // старые и неиспользуемые — кандидаты на prune
|
||||
MissingPruned int `json:"missing_pruned"` // строк удалено (0 в dry-run и без PruneMissing)
|
||||
MissingRaced int `json:"missing_raced"` // HEAD нашёл объект — ложная тревога из-за гонки
|
||||
MissingSample []string `json:"missing_sample_keys,omitempty"`
|
||||
|
||||
Errors int `json:"errors"`
|
||||
}
|
||||
|
||||
// Reconciler — зависимости.
|
||||
type Reconciler struct {
|
||||
DB *store.Store
|
||||
Objects *objectstore.Store
|
||||
Opts Options
|
||||
}
|
||||
|
||||
// Run выполняет один проход. Ошибка хранилища (S3/PG недоступны) прерывает проход:
|
||||
// частичный результат без явной причины хуже честной остановки; отчёт возвращается всегда.
|
||||
func (rc *Reconciler) Run(ctx context.Context) (*Report, error) {
|
||||
opts := rc.Opts
|
||||
if opts.PageSize <= 0 || opts.PageSize > defaultPageSize {
|
||||
opts.PageSize = defaultPageSize
|
||||
}
|
||||
if opts.Now == nil {
|
||||
opts.Now = time.Now
|
||||
}
|
||||
if opts.Logf == nil {
|
||||
opts.Logf = func(string, ...any) {}
|
||||
}
|
||||
rep := &Report{
|
||||
DryRun: opts.DryRun,
|
||||
GraceSeconds: opts.Grace.Seconds(),
|
||||
PruneMissing: opts.PruneMissing,
|
||||
}
|
||||
start := time.Now()
|
||||
defer func() { rep.DurationMs = time.Since(start).Milliseconds() }()
|
||||
|
||||
run := &run{rc: rc, opts: opts, rep: rep}
|
||||
err := run.mergeJoin(ctx)
|
||||
return rep, err
|
||||
}
|
||||
|
||||
type run struct {
|
||||
rc *Reconciler
|
||||
opts Options
|
||||
rep *Report
|
||||
}
|
||||
|
||||
// s3Cursor / dbCursor — «ленивые» итераторы по страницам с peek/advance.
|
||||
type s3Cursor struct {
|
||||
page []objectstore.ObjectInfo
|
||||
idx int
|
||||
token string
|
||||
begun bool
|
||||
done bool
|
||||
}
|
||||
|
||||
type dbCursor struct {
|
||||
page []store.AttachmentRef
|
||||
idx int
|
||||
after string
|
||||
done bool
|
||||
}
|
||||
|
||||
func (r *run) peekS3(ctx context.Context, c *s3Cursor) (*objectstore.ObjectInfo, error) {
|
||||
for c.idx >= len(c.page) {
|
||||
if c.done {
|
||||
return nil, nil
|
||||
}
|
||||
if c.begun && c.token == "" {
|
||||
c.done = true
|
||||
return nil, nil
|
||||
}
|
||||
p, err := r.rc.Objects.List(ctx, KeyPrefix, c.token, int32(r.opts.PageSize))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list s3: %w", err)
|
||||
}
|
||||
r.rep.S3ListCalls++
|
||||
c.begun, c.page, c.idx, c.token = true, p.Objects, 0, p.NextToken
|
||||
if len(p.Objects) == 0 && p.NextToken == "" {
|
||||
c.done = true
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
return &c.page[c.idx], nil
|
||||
}
|
||||
|
||||
func (r *run) peekDB(ctx context.Context, c *dbCursor) (*store.AttachmentRef, error) {
|
||||
for c.idx >= len(c.page) {
|
||||
if c.done {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := r.rc.DB.ListAttachmentRefsAfter(ctx, c.after, r.opts.PageSize)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list db: %w", err)
|
||||
}
|
||||
r.rep.DBPages++
|
||||
if len(rows) == 0 {
|
||||
c.done = true
|
||||
return nil, nil
|
||||
}
|
||||
c.page, c.idx = rows, 0
|
||||
c.after = rows[len(rows)-1].ObjectKey
|
||||
}
|
||||
return &c.page[c.idx], nil
|
||||
}
|
||||
|
||||
func (r *run) mergeJoin(ctx context.Context) error {
|
||||
s3c, dbc := &s3Cursor{}, &dbCursor{}
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
o, err := r.peekS3(ctx, s3c)
|
||||
if err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
d, err := r.peekDB(ctx, dbc)
|
||||
if err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
if o == nil && d == nil {
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case d == nil || (o != nil && o.Key < d.ObjectKey):
|
||||
// Ключ есть в S3, а в БД его нет → кандидат в orphan.
|
||||
r.rep.S3ObjectsScanned++
|
||||
if err := r.handleOrphanCandidate(ctx, *o); err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
s3c.idx++
|
||||
case o == nil || d.ObjectKey < o.Key:
|
||||
// Строка есть, объекта нет → кандидат в missing.
|
||||
r.rep.DBRowsScanned++
|
||||
if err := r.handleMissingCandidate(ctx, *d); err != nil {
|
||||
r.rep.Errors++
|
||||
return err
|
||||
}
|
||||
dbc.idx++
|
||||
default:
|
||||
// Ключи равны: всё согласовано.
|
||||
r.rep.S3ObjectsScanned++
|
||||
r.rep.DBRowsScanned++
|
||||
r.rep.Matched++
|
||||
s3c.idx++
|
||||
dbc.idx++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *run) handleOrphanCandidate(ctx context.Context, o objectstore.ObjectInfo) error {
|
||||
// Чужие/неожиданные ключи не трогаем вообще: reconciler знает только свою схему ключей.
|
||||
if !validAttachmentKey(o.Key) {
|
||||
r.rep.UnknownKeys++
|
||||
r.opts.Logf("SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): %s", o.Key)
|
||||
return nil
|
||||
}
|
||||
age := r.opts.Now().Sub(o.LastModified)
|
||||
if age < r.opts.Grace {
|
||||
// PUT был недавно: INSERT мог ещё не закоммититься. Не трогаем.
|
||||
r.rep.OrphansFresh++
|
||||
r.opts.Logf("SKIP fresh orphan (age=%s < grace=%s): %s", age.Round(time.Second), r.opts.Grace, o.Key)
|
||||
return nil
|
||||
}
|
||||
// Повторная проверка непосредственно перед удалением: за время прохода строка
|
||||
// могла появиться (долгая загрузка, медленный INSERT).
|
||||
exists, err := r.rc.DB.AttachmentKeyExists(ctx, o.Key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("recheck db: %w", err)
|
||||
}
|
||||
if exists {
|
||||
r.rep.OrphansRaced++
|
||||
return nil
|
||||
}
|
||||
r.rep.OrphansFound++
|
||||
r.sample(&r.rep.OrphanSampleKey, o.Key)
|
||||
if r.opts.DryRun {
|
||||
r.opts.Logf("DRY-RUN would delete orphan (age=%s, size=%d): %s", age.Round(time.Second), o.Size, o.Key)
|
||||
return nil
|
||||
}
|
||||
r.rep.DeleteCalls++
|
||||
if err := r.rc.Objects.Delete(ctx, o.Key); err != nil {
|
||||
return fmt.Errorf("delete orphan: %w", err)
|
||||
}
|
||||
r.rep.OrphansDeleted++
|
||||
r.opts.Logf("DELETED orphan (age=%s, size=%d): %s", age.Round(time.Second), o.Size, o.Key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *run) handleMissingCandidate(ctx context.Context, d store.AttachmentRef) error {
|
||||
// Подтверждаем HEAD: листинг S3 и страница БД читались в разные моменты, поэтому
|
||||
// «нет в листинге» ещё не значит «нет в S3» (загрузка могла завершиться между ними).
|
||||
r.rep.HeadCalls++
|
||||
_, err := r.rc.Objects.Head(ctx, d.ObjectKey)
|
||||
switch {
|
||||
case err == nil:
|
||||
r.rep.MissingRaced++
|
||||
return nil
|
||||
case errors.Is(err, objectstore.ErrNotFound):
|
||||
// действительно отсутствует — идём дальше
|
||||
default:
|
||||
return fmt.Errorf("head: %w", err)
|
||||
}
|
||||
|
||||
r.rep.MissingFound++
|
||||
r.sample(&r.rep.MissingSample, d.ObjectKey)
|
||||
age := r.opts.Now().Sub(d.CreatedAt)
|
||||
switch {
|
||||
case d.Used:
|
||||
// Вложение прикреплено к сообщению, а байт нет: потеря данных. Автоматически не чиним
|
||||
// и не удаляем строку (иначе сообщение осталось бы со ссылкой в никуда).
|
||||
r.rep.MissingUsed++
|
||||
r.opts.Logf("ALERT used attachment lost its object (id=%s, не удаляется): %s", d.ID, d.ObjectKey)
|
||||
case age < r.opts.Grace:
|
||||
r.rep.MissingFresh++
|
||||
r.opts.Logf("SKIP fresh missing (age=%s < grace=%s): %s", age.Round(time.Second), r.opts.Grace, d.ObjectKey)
|
||||
default:
|
||||
r.rep.MissingStale++
|
||||
switch {
|
||||
case r.opts.DryRun:
|
||||
r.opts.Logf("DRY-RUN missing object, unused stale row (id=%s)%s: %s", d.ID, pruneHint(r.opts.PruneMissing), d.ObjectKey)
|
||||
case !r.opts.PruneMissing:
|
||||
r.opts.Logf("REPORT missing object, unused stale row (id=%s), prune выключен: %s", d.ID, d.ObjectKey)
|
||||
default:
|
||||
// Удаление защищено условиями created_at < cutoff и NOT EXISTS ссылок в SQL.
|
||||
deleted, err := r.rc.DB.DeleteUnusedAttachment(ctx, d.ID, r.opts.Now().Add(-r.opts.Grace))
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune row: %w", err)
|
||||
}
|
||||
if deleted {
|
||||
r.rep.MissingPruned++
|
||||
r.opts.Logf("PRUNED row without object (id=%s): %s", d.ID, d.ObjectKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pruneHint(prune bool) string {
|
||||
if prune {
|
||||
return " would be pruned"
|
||||
}
|
||||
return " (prune off, report only)"
|
||||
}
|
||||
|
||||
func (r *run) sample(dst *[]string, key string) {
|
||||
if len(*dst) < maxSamples {
|
||||
*dst = append(*dst, key)
|
||||
}
|
||||
}
|
||||
|
||||
// validAttachmentKey — ключ строго вида attachments/{uuid}/{uuid} в каноническом написании.
|
||||
func validAttachmentKey(key string) bool {
|
||||
rest, ok := cutPrefix(key, KeyPrefix)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
var chat, att string
|
||||
for i := 0; i < len(rest); i++ {
|
||||
if rest[i] == '/' {
|
||||
chat, att = rest[:i], rest[i+1:]
|
||||
break
|
||||
}
|
||||
}
|
||||
if chat == "" || att == "" {
|
||||
return false
|
||||
}
|
||||
c, err1 := uuid.Parse(chat)
|
||||
a, err2 := uuid.Parse(att)
|
||||
return err1 == nil && err2 == nil && c.String() == chat && a.String() == att
|
||||
}
|
||||
|
||||
func cutPrefix(s, prefix string) (string, bool) {
|
||||
if len(s) >= len(prefix) && s[:len(prefix)] == prefix {
|
||||
return s[len(prefix):], true
|
||||
}
|
||||
return s, false
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Package session хранит opaque Bearer-сессии в Redis.
|
||||
//
|
||||
// PostgreSQL остаётся источником истины для пользователей и сообщений.
|
||||
// Сессия — отдельная роль: случайный токен, срок жизни SESSION_TTL_SECONDS и отзыв.
|
||||
// В Redis лежит не сам токен, а его SHA-256: дамп AOF не содержит значение,
|
||||
// которое клиент предъявляет в Authorization.
|
||||
//
|
||||
// TTL ключа равен оставшемуся сроку сессии. Рестарт API его не продлевает.
|
||||
// Рестарт Redis сессию сохраняет только потому, что включён AOF на volume.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
|
||||
// Store — клиент Redis с короткими таймаутами.
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// Open разбирает redis:// URL. Пароль в лог не пишется.
|
||||
func Open(redisURL string, ttl time.Duration) (*Store, error) {
|
||||
opt, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
opt.DialTimeout = 500 * time.Millisecond
|
||||
opt.ReadTimeout = 500 * time.Millisecond
|
||||
opt.WriteTimeout = 500 * time.Millisecond
|
||||
opt.PoolSize = 20
|
||||
client := redis.NewClient(opt)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{client: client, ttl: ttl}, nil
|
||||
}
|
||||
|
||||
// Close закрывает пул при остановке процесса.
|
||||
func (s *Store) Close() error {
|
||||
return s.client.Close()
|
||||
}
|
||||
|
||||
// Ping — готовность кэша сессий. Недоступный Redis не означает «анонимный доступ».
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Issue выпускает 256 бит случайности (32 байта) и кладёт сессию с TTL.
|
||||
// Наружу уходит hex (64 символа). В Redis — только хеш.
|
||||
func (s *Store) Issue(ctx context.Context, userID uuid.UUID) (token string, expiresAt time.Time, err error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err = rand.Read(buf); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token = hex.EncodeToString(buf)
|
||||
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Millisecond)
|
||||
value := userID.String() + "|" + expiresAt.Format(time.RFC3339Nano)
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
if err = s.client.Set(ctx, key(token), value, time.Until(expiresAt)).Err(); err != nil {
|
||||
return "", time.Time{}, ErrUnavailable
|
||||
}
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// Lookup возвращает владельца живой сессии.
|
||||
// Промах и истёкший срок — ErrUnauthorized. Сбой Redis — ErrUnavailable (HTTP 503).
|
||||
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
raw, err := s.client.Get(ctx, key(token)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrUnavailable
|
||||
}
|
||||
userPart, expPart, ok := strings.Cut(raw, "|")
|
||||
if !ok {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
exp, err := time.Parse(time.RFC3339Nano, expPart)
|
||||
if err != nil || !exp.After(time.Now()) {
|
||||
_ = s.client.Del(ctx, key(token)).Err()
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
id, err := uuid.Parse(userPart)
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// Revoke удаляет текущую сессию. Повторный отзыв — это уже отсутствие ключа.
|
||||
func (s *Store) Revoke(ctx context.Context, token string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
n, err := s.client.Del(ctx, key(token)).Result()
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "sess:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
// Метаданные вложений (lab4): таблицы attachments и message_attachments.
|
||||
//
|
||||
// Разделение ответственности:
|
||||
// - байты оригинала лежат в приватном S3-bucket по ключу attachments/{chat}/{id};
|
||||
// - здесь — всё остальное: чат, владелец, имя для показа, тип, размер, sha256, ключ.
|
||||
//
|
||||
// Порядок «PUT в S3, потом INSERT здесь» выбран намеренно (см. api/attachments.go):
|
||||
// при сбое между шагами остаётся лишний ОБЪЕКТ (его безопасно убирает reconciler),
|
||||
// а не строка без файла (она бы отдавала пользователю ошибку при скачивании).
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// StatusReady — единственный статус lab4: 201 возвращается только после сохранения
|
||||
// и оригинала в S3, и метаданных в PostgreSQL.
|
||||
const StatusReady = "ready"
|
||||
|
||||
// Attachment — строка таблицы attachments.
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string // image/png | image/jpeg, определён по содержимому
|
||||
SizeBytes int64
|
||||
SHA256 string // lowercase hex
|
||||
ObjectKey string // внутренний, клиенту не отдаётся
|
||||
Status string
|
||||
ErrorCode *string
|
||||
Width int
|
||||
Height int
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// AttachmentObjectKey строит ключ объекта. Ключ целиком определяется сервером:
|
||||
// имя файла клиента в нём не участвует (нет path traversal и коллизий имён),
|
||||
// а префикс chat-id группирует объекты чата для будущей очистки.
|
||||
func AttachmentObjectKey(chatID, attachmentID uuid.UUID) string {
|
||||
return "attachments/" + chatID.String() + "/" + attachmentID.String()
|
||||
}
|
||||
|
||||
// CreateAttachment вставляет метаданные уже загруженного в S3 объекта.
|
||||
//
|
||||
// INSERT ... SELECT ... WHERE EXISTS проверяет членство атомарно с вставкой:
|
||||
// между «проверили участие» в HTTP-слое и записью строки состав чата мог бы измениться,
|
||||
// а так условие и запись — один оператор. 0 строк → ErrNotFound (404).
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error {
|
||||
if a.CreatedAt.IsZero() {
|
||||
// Миллисекундная точность — та же, что печатается в JSON.
|
||||
a.CreatedAt = nowUTC()
|
||||
}
|
||||
if a.Status == "" {
|
||||
a.Status = StatusReady
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, width, height, created_at, updated_at)
|
||||
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $11, $12, $12
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256,
|
||||
a.ObjectKey, a.Status, a.Width, a.Height, a.CreatedAt)
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
a.UpdatedAt = a.CreatedAt
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAttachmentForUser возвращает вложение ТОЛЬКО участнику его чата.
|
||||
// Чужое и несуществующее неразличимы (ErrNotFound → 404, не 403): иначе можно было
|
||||
// бы по коду ответа проверять, существует ли чужой файл.
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID uuid.UUID) (*Attachment, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var a 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.error_code, a.width, a.height,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.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.ErrorCode, &a.Width, &a.Height,
|
||||
&a.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// CountAttachmentsInChat нужен тестам: после отказа S3/PG в чате не должно оставаться
|
||||
// «полуфабрикатов» (строк метаданных без успешной загрузки).
|
||||
func (s *Store) CountAttachmentsInChat(ctx context.Context, chatID uuid.UUID) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var n int
|
||||
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM attachments WHERE chat_id = $1`, chatID).Scan(&n); err != nil {
|
||||
return 0, mapWriteErr(err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// querier — общая часть pgx.Tx и pgxpool.Pool: так одни и те же функции читают
|
||||
// связи сообщений и внутри транзакции (идемпотентный replay), и вне её (история).
|
||||
type querier interface {
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
// lockMessageAttachments проверяет вложения будущего сообщения внутри его транзакции.
|
||||
//
|
||||
// - WHERE id = ANY($1) AND chat_id = $2: вложение другого чата и несуществующее
|
||||
// одинаково «не находятся» → ErrNotFound (404). Это и есть привязка файла к чату.
|
||||
// - FOR SHARE блокирует найденные строки до COMMIT: параллельное удаление
|
||||
// (reconciler) подождёт и затем упрётся в внешний ключ message_attachments.
|
||||
// - Если нашлось меньше строк, чем запрошено, — хотя бы одно чужое/неизвестное.
|
||||
// - Любой статус, кроме ready, → ErrAttachmentNotReady (409).
|
||||
//
|
||||
// ids уже проверены HTTP-слоем на уникальность и количество (≤10).
|
||||
func lockMessageAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT id, status FROM attachments
|
||||
WHERE id = ANY($1) AND chat_id = $2
|
||||
ORDER BY id
|
||||
FOR SHARE`, ids, chatID)
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
found, notReady := 0, false
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
var status string
|
||||
if err := rows.Scan(&id, &status); err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
found++
|
||||
if status != StatusReady {
|
||||
notReady = true
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
rows.Close()
|
||||
if found != len(ids) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if notReady {
|
||||
return ErrAttachmentNotReady
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadMessageAttachmentIDs — вложения одного сообщения в исходном порядке (position).
|
||||
// Никогда не возвращает nil: пустой срез сериализуется в [], а не в null.
|
||||
func loadMessageAttachmentIDs(ctx context.Context, q querier, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
byMsg, err := attachmentIDsByMessage(ctx, q, []uuid.UUID{messageID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return byMsg[messageID], nil
|
||||
}
|
||||
|
||||
// attachmentIDsByMessage одним запросом читает связи для набора сообщений.
|
||||
// Для сообщений без вложений вернётся пустой (не nil) срез.
|
||||
func attachmentIDsByMessage(ctx context.Context, q querier, messageIDs []uuid.UUID) (map[uuid.UUID][]uuid.UUID, error) {
|
||||
out := make(map[uuid.UUID][]uuid.UUID, len(messageIDs))
|
||||
for _, id := range messageIDs {
|
||||
out[id] = []uuid.UUID{}
|
||||
}
|
||||
if len(messageIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1)
|
||||
ORDER BY message_id, position`, messageIDs)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var mid, aid uuid.UUID
|
||||
if err := rows.Scan(&mid, &aid); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
out[mid] = append(out[mid], aid)
|
||||
}
|
||||
return out, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
// attachMessageAttachments дозаполняет AttachmentIDs у страницы сообщений (ListMessages).
|
||||
func (s *Store) attachMessageAttachments(ctx context.Context, items []Message) error {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].AttachmentIDs = byMsg[items[i].ID]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Методы для reconciler (internal/reconcile). Они здесь, а не в reconcile, потому
|
||||
// что SQL и работа с пулом принадлежат пакету store.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// AttachmentRef — минимальная информация о строке для сверки с S3.
|
||||
type AttachmentRef struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
// Used — на вложение ссылается хотя бы одно сообщение. Такое вложение удалять нельзя.
|
||||
Used bool
|
||||
}
|
||||
|
||||
// ListAttachmentRefsAfter — keyset-страница строк в байтовом порядке object_key
|
||||
// (колонка COLLATE "C" — порядок совпадает с листингом S3). afterKey="" — с начала.
|
||||
func (s *Store) ListAttachmentRefsAfter(ctx context.Context, afterKey string, limit int) ([]AttachmentRef, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT a.id, a.object_key, a.created_at,
|
||||
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)
|
||||
FROM attachments a
|
||||
WHERE a.object_key > $1
|
||||
ORDER BY a.object_key
|
||||
LIMIT $2`, afterKey, limit)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []AttachmentRef
|
||||
for rows.Next() {
|
||||
var r AttachmentRef
|
||||
if err := rows.Scan(&r.ID, &r.ObjectKey, &r.CreatedAt, &r.Used); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
// AttachmentKeyExists — повторная проверка непосредственно перед удалением orphan-объекта:
|
||||
// сужает окно гонки «reconciler решил, что строки нет, а загрузка как раз сделала INSERT».
|
||||
func (s *Store) AttachmentKeyExists(ctx context.Context, key string) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok)
|
||||
return ok, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// DeleteUnusedAttachment удаляет строку вложения, только если выполнены ОБА условия:
|
||||
// она старше olderThan (не «свежая») и на неё нет ссылок из сообщений (не «используемая»).
|
||||
// Возвращает true, если строка удалена. Внешний ключ message_attachments страхует
|
||||
// от гонки с параллельной отправкой сообщения: такой DELETE упадёт, а не потеряет данные.
|
||||
func (s *Store) DeleteUnusedAttachment(ctx context.Context, id uuid.UUID, olderThan time.Time) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
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)`,
|
||||
id, olderThan)
|
||||
if err != nil {
|
||||
return false, mapWriteErr(err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFS embed.FS
|
||||
|
||||
// Migrate применяет встроенные SQL-файлы по одному разу.
|
||||
// Повторный старт процесса не создаёт вторую копию строк: версия пишется в schema_migrations.
|
||||
func (s *Store) Migrate(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
if _, err := s.pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`); err != nil {
|
||||
return fmt.Errorf("schema_migrations: %w", err)
|
||||
}
|
||||
entries, err := migrationFS.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
continue
|
||||
}
|
||||
body, err := migrationFS.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// pgx в extended protocol не выполняет несколько команд одним Exec.
|
||||
for _, stmt := range splitSQL(string(body)) {
|
||||
if _, err := tx.Exec(ctx, stmt); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("migrate %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// splitSQL делит файл миграции по ';'. В этих файлах нет строк с точкой с запятой внутри литералов.
|
||||
func splitSQL(body string) []string {
|
||||
parts := strings.Split(body, ";")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
stmt := strings.TrimSpace(part)
|
||||
if stmt == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, stmt)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Схема lab2. PostgreSQL — источник истины для пользователей, чатов и сообщений.
|
||||
-- Сессии здесь намеренно нет: их держит Redis с AOF, TTL не продлевается рестартом API.
|
||||
-- Повторный запуск безопасен: все объекты создаются через IF NOT EXISTS.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
-- Argon2id PHC-строка. Не SHA-256 и не plaintext. Наружу не отдаётся.
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT users_username_unique UNIQUE (username)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
-- Составной первичный ключ не даёт вставить участника дважды.
|
||||
-- Внешние ключи не дают сослаться на несуществующего пользователя или чат.
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
-- Список чатов пользователя начинается с фильтра «где я участник».
|
||||
CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
sender_id uuid NOT NULL REFERENCES users (id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
-- Keyset истории: WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id.
|
||||
-- Составной индекс покрывает и фильтр, и порядок. Слабый индекс только по chat_id
|
||||
-- заставил бы сортировать историю чата. Его нет в продовой схеме, он появляется
|
||||
-- лишь на время эксперимента трека 2.
|
||||
CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Идемпотентность POST сообщения (lab3).
|
||||
-- Область ключа: (user_id, method, path, key).
|
||||
-- Разные пользователи и чаты могут независимо использовать одну строку Idempotency-Key.
|
||||
-- request_hash — SHA-256 канонического тела.
|
||||
-- Другой body при том же ключе даёт HTTP 409.
|
||||
-- response_* фиксируются только для успешного 201 в той же транзакции, что и INSERT messages.
|
||||
-- Транзиентный 5xx не сохраняется как окончательный результат.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
method text NOT NULL,
|
||||
path text NOT NULL,
|
||||
key text NOT NULL,
|
||||
request_hash text NOT NULL,
|
||||
response_status integer NOT NULL,
|
||||
response_body jsonb NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages (id),
|
||||
created_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, method, path, key)
|
||||
);
|
||||
|
||||
-- Индекс по времени — для будущей очистки хвоста старше 24 часов.
|
||||
CREATE INDEX IF NOT EXISTS idempotency_keys_created_idx ON idempotency_keys (created_at);
|
||||
@@ -0,0 +1,47 @@
|
||||
-- Вложения lab4. Метаданные - в PostgreSQL, байты - в приватном S3-bucket (MinIO).
|
||||
-- Ключ объекта назначает сервер: attachments/{chat_id}/{attachment_id}.
|
||||
-- filename - только отображаемое имя, в ключ и в путь не попадает.
|
||||
--
|
||||
-- ВНИМАНИЕ: файл режется по символу точки с запятой (см. splitSQL в migrate.go),
|
||||
-- поэтому в комментариях и литералах здесь нет этого символа.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
-- Файл заранее привязан к чату: доступ к нему определяется членством в этом чате.
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
owner_id uuid NOT NULL REFERENCES users (id),
|
||||
filename text NOT NULL,
|
||||
-- Тип определён по СОДЕРЖИМОМУ файла, а не по заголовку запроса.
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
-- lowercase hex SHA-256 оригинала.
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
-- COLLATE "C": байтовый порядок совпадает с лексикографическим порядком ListObjectsV2.
|
||||
-- Reconciler сливает два отсортированных потока (S3 и эта колонка) без загрузки в память.
|
||||
object_key text COLLATE "C" NOT NULL,
|
||||
-- lab4 знает только ready (201 после сохранения байтов и метаданных).
|
||||
-- Состояния queued/processing/failed появятся в lab5+ расширением CHECK.
|
||||
status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready')),
|
||||
error_code text,
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT attachments_object_key_unique UNIQUE (object_key)
|
||||
);
|
||||
|
||||
-- Проверка вложений сообщения идёт по PK, индекс по чату нужен списку и будущей очистке.
|
||||
CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments (chat_id);
|
||||
|
||||
-- Связь сообщение - вложение. position хранит порядок attachment_ids из запроса.
|
||||
-- Одно вложение можно прикрепить к нескольким сообщениям своего чата (контракт не запрещает).
|
||||
-- Внешние ключи не дают удалить вложение, на которое ссылается сообщение: reconciler
|
||||
-- физически не может снести «используемое» вложение даже при ошибке в его логике.
|
||||
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id),
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
position smallint NOT NULL CHECK (position >= 0),
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id)
|
||||
@@ -0,0 +1,301 @@
|
||||
// Метаданные вложений (lab4): таблицы attachments и message_attachments.
|
||||
//
|
||||
// Разделение ответственности:
|
||||
// - байты оригинала лежат в приватном S3-bucket по ключу attachments/{chat}/{id};
|
||||
// - здесь — всё остальное: чат, владелец, имя для показа, тип, размер, sha256, ключ.
|
||||
//
|
||||
// Порядок «PUT в S3, потом INSERT здесь» выбран намеренно (см. api/attachments.go):
|
||||
// при сбое между шагами остаётся лишний ОБЪЕКТ (его безопасно убирает reconciler),
|
||||
// а не строка без файла (она бы отдавала пользователю ошибку при скачивании).
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// StatusReady — единственный статус lab4: 201 возвращается только после сохранения
|
||||
// и оригинала в S3, и метаданных в PostgreSQL.
|
||||
const StatusReady = "ready"
|
||||
|
||||
// Attachment — строка таблицы attachments.
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string // image/png | image/jpeg, определён по содержимому
|
||||
SizeBytes int64
|
||||
SHA256 string // lowercase hex
|
||||
ObjectKey string // внутренний, клиенту не отдаётся
|
||||
Status string
|
||||
ErrorCode *string
|
||||
Width int
|
||||
Height int
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// AttachmentObjectKey строит ключ объекта. Ключ целиком определяется сервером:
|
||||
// имя файла клиента в нём не участвует (нет path traversal и коллизий имён),
|
||||
// а префикс chat-id группирует объекты чата для будущей очистки.
|
||||
func AttachmentObjectKey(chatID, attachmentID uuid.UUID) string {
|
||||
return "attachments/" + chatID.String() + "/" + attachmentID.String()
|
||||
}
|
||||
|
||||
// CreateAttachment вставляет метаданные уже загруженного в S3 объекта.
|
||||
//
|
||||
// INSERT ... SELECT ... WHERE EXISTS проверяет членство атомарно с вставкой:
|
||||
// между «проверили участие» в HTTP-слое и записью строки состав чата мог бы измениться,
|
||||
// а так условие и запись — один оператор. 0 строк → ErrNotFound (404).
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error {
|
||||
if a.CreatedAt.IsZero() {
|
||||
// Миллисекундная точность — та же, что печатается в JSON.
|
||||
a.CreatedAt = nowUTC()
|
||||
}
|
||||
if a.Status == "" {
|
||||
a.Status = StatusReady
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, width, height, created_at, updated_at)
|
||||
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $11, $12, $12
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256,
|
||||
a.ObjectKey, a.Status, a.Width, a.Height, a.CreatedAt)
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
a.UpdatedAt = a.CreatedAt
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAttachmentForUser возвращает вложение ТОЛЬКО участнику его чата.
|
||||
// Чужое и несуществующее неразличимы (ErrNotFound → 404, не 403): иначе можно было
|
||||
// бы по коду ответа проверять, существует ли чужой файл.
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID uuid.UUID) (*Attachment, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var a 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.error_code, a.width, a.height,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.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.ErrorCode, &a.Width, &a.Height,
|
||||
&a.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// CountAttachmentsInChat нужен тестам: после отказа S3/PG в чате не должно оставаться
|
||||
// «полуфабрикатов» (строк метаданных без успешной загрузки).
|
||||
func (s *Store) CountAttachmentsInChat(ctx context.Context, chatID uuid.UUID) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var n int
|
||||
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM attachments WHERE chat_id = $1`, chatID).Scan(&n); err != nil {
|
||||
return 0, mapWriteErr(err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// querier — общая часть pgx.Tx и pgxpool.Pool: так одни и те же функции читают
|
||||
// связи сообщений и внутри транзакции (идемпотентный replay), и вне её (история).
|
||||
type querier interface {
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
// lockMessageAttachments проверяет вложения будущего сообщения внутри его транзакции.
|
||||
//
|
||||
// - WHERE id = ANY($1) AND chat_id = $2: вложение другого чата и несуществующее
|
||||
// одинаково «не находятся» → ErrNotFound (404). Это и есть привязка файла к чату.
|
||||
// - FOR SHARE блокирует найденные строки до COMMIT: параллельное удаление
|
||||
// (reconciler) подождёт и затем упрётся в внешний ключ message_attachments.
|
||||
// - Если нашлось меньше строк, чем запрошено, — хотя бы одно чужое/неизвестное.
|
||||
// - Любой статус, кроме ready, → ErrAttachmentNotReady (409).
|
||||
//
|
||||
// ids уже проверены HTTP-слоем на уникальность и количество (≤10).
|
||||
func lockMessageAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT id, status FROM attachments
|
||||
WHERE id = ANY($1) AND chat_id = $2
|
||||
ORDER BY id
|
||||
FOR SHARE`, ids, chatID)
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
found, notReady := 0, false
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
var status string
|
||||
if err := rows.Scan(&id, &status); err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
found++
|
||||
if status != StatusReady {
|
||||
notReady = true
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
rows.Close()
|
||||
if found != len(ids) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if notReady {
|
||||
return ErrAttachmentNotReady
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadMessageAttachmentIDs — вложения одного сообщения в исходном порядке (position).
|
||||
// Никогда не возвращает nil: пустой срез сериализуется в [], а не в null.
|
||||
func loadMessageAttachmentIDs(ctx context.Context, q querier, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
byMsg, err := attachmentIDsByMessage(ctx, q, []uuid.UUID{messageID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return byMsg[messageID], nil
|
||||
}
|
||||
|
||||
// attachmentIDsByMessage одним запросом читает связи для набора сообщений.
|
||||
// Для сообщений без вложений вернётся пустой (не nil) срез.
|
||||
func attachmentIDsByMessage(ctx context.Context, q querier, messageIDs []uuid.UUID) (map[uuid.UUID][]uuid.UUID, error) {
|
||||
out := make(map[uuid.UUID][]uuid.UUID, len(messageIDs))
|
||||
for _, id := range messageIDs {
|
||||
out[id] = []uuid.UUID{}
|
||||
}
|
||||
if len(messageIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1)
|
||||
ORDER BY message_id, position`, messageIDs)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var mid, aid uuid.UUID
|
||||
if err := rows.Scan(&mid, &aid); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
out[mid] = append(out[mid], aid)
|
||||
}
|
||||
return out, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
// attachMessageAttachments дозаполняет AttachmentIDs у страницы сообщений (ListMessages).
|
||||
func (s *Store) attachMessageAttachments(ctx context.Context, items []Message) error {
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].AttachmentIDs = byMsg[items[i].ID]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Методы для reconciler (internal/reconcile). Они здесь, а не в reconcile, потому
|
||||
// что SQL и работа с пулом принадлежат пакету store.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// AttachmentRef — минимальная информация о строке для сверки с S3.
|
||||
type AttachmentRef struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
// Used — на вложение ссылается хотя бы одно сообщение. Такое вложение удалять нельзя.
|
||||
Used bool
|
||||
}
|
||||
|
||||
// ListAttachmentRefsAfter — keyset-страница строк в байтовом порядке object_key
|
||||
// (колонка COLLATE "C" — порядок совпадает с листингом S3). afterKey="" — с начала.
|
||||
func (s *Store) ListAttachmentRefsAfter(ctx context.Context, afterKey string, limit int) ([]AttachmentRef, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT a.id, a.object_key, a.created_at,
|
||||
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)
|
||||
FROM attachments a
|
||||
WHERE a.object_key > $1
|
||||
ORDER BY a.object_key
|
||||
LIMIT $2`, afterKey, limit)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []AttachmentRef
|
||||
for rows.Next() {
|
||||
var r AttachmentRef
|
||||
if err := rows.Scan(&r.ID, &r.ObjectKey, &r.CreatedAt, &r.Used); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
// AttachmentKeyExists — повторная проверка непосредственно перед удалением orphan-объекта:
|
||||
// сужает окно гонки «reconciler решил, что строки нет, а загрузка как раз сделала INSERT».
|
||||
func (s *Store) AttachmentKeyExists(ctx context.Context, key string) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok)
|
||||
return ok, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// DeleteUnusedAttachment удаляет строку вложения, только если выполнены ОБА условия:
|
||||
// она старше olderThan (не «свежая») и на неё нет ссылок из сообщений (не «используемая»).
|
||||
// Возвращает true, если строка удалена. Внешний ключ message_attachments страхует
|
||||
// от гонки с параллельной отправкой сообщения: такой DELETE упадёт, а не потеряет данные.
|
||||
func (s *Store) DeleteUnusedAttachment(ctx context.Context, id uuid.UUID, olderThan time.Time) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
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)`,
|
||||
id, olderThan)
|
||||
if err != nil {
|
||||
return false, mapWriteErr(err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL.
|
||||
//
|
||||
// Источник истины — только эти таблицы. Память процесса после рестарта пуста,
|
||||
// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2):
|
||||
// текст сообщения не склеивается в SQL.
|
||||
//
|
||||
// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе
|
||||
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||
//
|
||||
// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики:
|
||||
// два параллельных POST с одним ключом через разные API-контейнеры видят один PK.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gavrilenko-sxdees/lab4/internal/auth"
|
||||
)
|
||||
|
||||
const queryTimeout = 3 * time.Second
|
||||
|
||||
// Ошибки домена. HTTP-слой переводит их в коды контракта и не показывает SQL.
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
// ErrIdempotencyConflict — тот же ключ, но другое тело запроса.
|
||||
ErrIdempotencyConflict = errors.New("idempotency conflict")
|
||||
// ErrAttachmentNotReady — вложение существует, но ещё не ready (409 по контракту).
|
||||
// В lab4 все вложения создаются сразу ready; проверка нужна для lab5+ и защищает
|
||||
// от прикрепления недообработанного файла.
|
||||
ErrAttachmentNotReady = errors.New("attachment not ready")
|
||||
)
|
||||
|
||||
// User — публичные поля пользователя. Hash пароля в эту структуру не попадает.
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Chat — чат и явный состав участников.
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Message — одно подтверждённое сообщение. sender_id назначает сервер.
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
// AttachmentIDs — вложения в порядке, заданном клиентом. Никогда nil в ответах API
|
||||
// (контракт: attachment_ids обязателен, по умолчанию []).
|
||||
AttachmentIDs []uuid.UUID
|
||||
}
|
||||
|
||||
// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api.
|
||||
type PageCursor struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
Scope string
|
||||
}
|
||||
|
||||
// Store — пул соединений. Пул ограничен, у каждого запроса свой таймаут.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
hasher *auth.Hasher
|
||||
}
|
||||
|
||||
// Open поднимает пул. ConnectTimeout короткий, чтобы недоступная БД быстро стала 503,
|
||||
// а не висела до клиентского таймаута теста.
|
||||
// maxConns — на одну реплику; при N репликах суммарный пул ≈ N*maxConns.
|
||||
func Open(ctx context.Context, databaseURL string, hasher *auth.Hasher, maxConns int32) (*Store, error) {
|
||||
if maxConns < 1 {
|
||||
maxConns = 5
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database url: %w", err)
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
||||
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
// UTC, чтобы timestamptz читался так же, как мы его записали.
|
||||
// statement_timeout обрывает запрос, который внезапно решил сканировать всё.
|
||||
_, err := conn.Exec(ctx, `SET TIME ZONE 'UTC'; SET statement_timeout = '3s'`)
|
||||
return err
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{pool: pool, hasher: hasher}, nil
|
||||
}
|
||||
|
||||
// Close освобождает соединения при остановке процесса.
|
||||
func (s *Store) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
// Ping — проверка для /health/ready. Ошибка здесь значит «не готов», не «жив».
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateUser пишет пользователя. Повтор username → ErrConflict благодаря UNIQUE.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||
hash, err := auth.Hash(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := &User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, hash, u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// Authenticate проверяет Basic-логин. Нет пользователя и неверный пароль
|
||||
// выглядят одинаково: оба дают false без отдельной ошибки «такого логина нет».
|
||||
func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var u User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
s.hasher.Burn(password)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if !s.hasher.Verify(hash, password) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// GetUser нужен, чтобы ответ /users/me совпал с объектом из регистрации.
|
||||
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var u User
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// CreateChat атомарно создаёт чат и состав. Неизвестный участник откатывает всё:
|
||||
// в таблице chats не остаётся «пустой» строки без полного состава.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
chat := &Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
for _, uid := range memberIDs {
|
||||
// INSERT ... SELECT вставит 0 строк, если пользователя нет, и не нарушит FK.
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, id FROM users WHERE id = $2`, chat.ID, uid)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
// GetChat возвращает чат только участнику. Чужому — ErrNotFound (HTTP 404, не 403).
|
||||
func (s *Store) GetChat(ctx context.Context, chatID, userID uuid.UUID) (*Chat, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.loadChat(ctx, chatID)
|
||||
}
|
||||
|
||||
// ListChats — keyset по (created_at, id) только среди чатов этого пользователя.
|
||||
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, after *PageCursor) ([]Chat, *PageCursor, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
AND (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []Chat
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
next, items := trimPage(items, limit, func(c Chat) (time.Time, uuid.UUID) {
|
||||
return c.CreatedAt, c.ID
|
||||
})
|
||||
for i := range items {
|
||||
members, err := s.memberIDs(ctx, items[i].ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
items[i].MemberIDs = members
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if next {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// CreateMessage пишет сообщение только если отправитель состоит в чате.
|
||||
// Подтверждение — это COMMIT строки. Следующее чтение видит её без кэша истории.
|
||||
// Без идемпотентности — только для внутренних/тестовых случаев; HTTP использует CreateMessageIdempotent.
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (*Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
// Внутренний путь без вложений; поле не nil, чтобы JSON дал [], а не null.
|
||||
AttachmentIDs: []uuid.UUID{},
|
||||
}
|
||||
tag, err := s.pool.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
|
||||
)`, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// IdempotentMessage — либо только что созданное, либо ранее сохранённое по ключу сообщение.
|
||||
type IdempotentMessage struct {
|
||||
Message *Message
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу.
|
||||
//
|
||||
// Алгоритм (общая БД, любые реплики):
|
||||
// 1. BEGIN;
|
||||
// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов
|
||||
// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message;
|
||||
// 4. иначе проверить членство, затем вложения (lab4): все принадлежат ЭТОМУ чату и ready,
|
||||
// строки блокируются FOR SHARE, чтобы удаление (reconciler) не вклинилось до COMMIT;
|
||||
// 5. INSERT message + INSERT message_attachments + INSERT idempotency_keys в той же
|
||||
// транзакции: сообщение либо видно целиком вместе со ссылками на вложения, либо нет;
|
||||
// 6. COMMIT (advisory lock снимается вместе с транзакцией).
|
||||
//
|
||||
// Чужое и неизвестное вложение (в т.ч. из другого чата) неразличимы: оба дают ErrNotFound
|
||||
// (HTTP 404), чтобы нельзя было перебором выяснить, существует ли чужой файл.
|
||||
//
|
||||
// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает:
|
||||
// запись ключа только после успешной подготовки 201.
|
||||
func (s *Store) CreateMessageIdempotent(
|
||||
ctx context.Context,
|
||||
chatID, senderID uuid.UUID,
|
||||
text string,
|
||||
attachmentIDs []uuid.UUID,
|
||||
method, path, idemKey, requestHash string,
|
||||
) (*IdempotentMessage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
lockKey := idempotencyLockKey(senderID, method, path, idemKey)
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockKey); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var (
|
||||
storedHash string
|
||||
msgID uuid.UUID
|
||||
msgChat uuid.UUID
|
||||
msgSender uuid.UUID
|
||||
msgText string
|
||||
msgCreated time.Time
|
||||
)
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT i.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1 AND i.method = $2 AND i.path = $3 AND i.key = $4`,
|
||||
senderID, method, path, idemKey,
|
||||
).Scan(&storedHash, &msgID, &msgChat, &msgSender, &msgText, &msgCreated)
|
||||
if err == nil {
|
||||
if storedHash != requestHash {
|
||||
return nil, ErrIdempotencyConflict
|
||||
}
|
||||
// Replay обязан вернуть ТОТ ЖЕ набор вложений, что и первый ответ.
|
||||
replayIDs, err := loadMessageAttachmentIDs(ctx, tx, msgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{
|
||||
Message: &Message{
|
||||
ID: msgID,
|
||||
ChatID: msgChat,
|
||||
SenderID: msgSender,
|
||||
Text: msgText,
|
||||
CreatedAt: msgCreated,
|
||||
AttachmentIDs: replayIDs,
|
||||
},
|
||||
Replayed: true,
|
||||
}, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// Вложения проверяем ПОСЛЕ членства: посторонний в чат получает 404 по чату,
|
||||
// а не информацию о существовании файлов.
|
||||
if err := lockMessageAttachments(ctx, tx, chatID, attachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
// Порядок attachment_ids клиента сохраняется в position.
|
||||
for i, aid := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
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,
|
||||
"created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"),
|
||||
"attachment_ids": attachmentStrs,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `
|
||||
INSERT INTO idempotency_keys (
|
||||
user_id, method, path, key, request_hash,
|
||||
response_status, response_body, message_id, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
||||
senderID, method, path, idemKey, requestHash,
|
||||
201, bodyJSON, msg.ID, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{Message: msg, Replayed: false}, nil
|
||||
}
|
||||
|
||||
// idempotencyLockKey — стабильный int64 для pg_advisory_xact_lock из области ключа.
|
||||
func idempotencyLockKey(userID uuid.UUID, method, path, key string) int64 {
|
||||
sum := sha256.Sum256([]byte(userID.String() + "|" + method + "|" + path + "|" + key))
|
||||
return int64(binary.BigEndian.Uint64(sum[:8]))
|
||||
}
|
||||
|
||||
// ListMessages — keyset по индексу messages_history_idx. Берём limit+1 строку,
|
||||
// чтобы next_cursor был null, когда следующей записи уже нет.
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limit int, after *PageCursor) ([]Message, *PageCursor, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2`, chatID, limit+1)
|
||||
} else {
|
||||
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
|
||||
LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Message
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) {
|
||||
return m.CreatedAt, m.ID
|
||||
})
|
||||
// Вложения страницы одним запросом (а не N+1): WHERE message_id = ANY(id страницы).
|
||||
if err := s.attachMessageAttachments(ctx, items); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// ChatExistsForTitle помогает тесту отката: после ошибки создания чата строки нет.
|
||||
func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var n int
|
||||
err := s.pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&n)
|
||||
if err != nil {
|
||||
return 0, mapWriteErr(err)
|
||||
}
|
||||
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()
|
||||
var one int
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&one)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) loadChat(ctx context.Context, chatID uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var c Chat
|
||||
err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID).
|
||||
Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
c.MemberIDs, err = s.memberIDs(ctx, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (s *Store) memberIDs(ctx context.Context, chatID uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id`, chatID)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []uuid.UUID
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
func trimPage[T any](items []T, limit int, _ func(T) (time.Time, uuid.UUID)) (bool, []T) {
|
||||
if len(items) > limit {
|
||||
return true, items[:limit]
|
||||
}
|
||||
return false, items
|
||||
}
|
||||
|
||||
func nowUTC() time.Time {
|
||||
// Миллисекунда — точность, которую мы же и печатаем в JSON.
|
||||
return time.Now().UTC().Truncate(time.Millisecond)
|
||||
}
|
||||
|
||||
func mapWriteErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return ErrConflict
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || isConn(err) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isConn(err error) bool {
|
||||
msg := err.Error()
|
||||
// Не логируем и не возвращаем клиенту эту строку. Здесь только классификация.
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return false
|
||||
default:
|
||||
if stringsContains(msg, "connection refused") ||
|
||||
stringsContains(msg, "failed to connect") ||
|
||||
stringsContains(msg, "conn closed") ||
|
||||
stringsContains(msg, "closed pool") ||
|
||||
stringsContains(msg, "broken pipe") ||
|
||||
stringsContains(msg, "connection reset") ||
|
||||
stringsContains(msg, "SQLSTATE 57P01") ||
|
||||
stringsContains(msg, "SQLSTATE 08006") ||
|
||||
stringsContains(msg, "SQLSTATE 08001") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func stringsContains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (s == sub || len(sub) == 0 ||
|
||||
(func() bool { return contains(s, sub) })())
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL.
|
||||
//
|
||||
// Источник истины — только эти таблицы. Память процесса после рестарта пуста,
|
||||
// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2):
|
||||
// текст сообщения не склеивается в SQL.
|
||||
//
|
||||
// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе
|
||||
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||
//
|
||||
// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики:
|
||||
// два параллельных POST с одним ключом через разные API-контейнеры видят один PK.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gavrilenko-sxdees/lab4/internal/auth"
|
||||
)
|
||||
|
||||
const queryTimeout = 3 * time.Second
|
||||
|
||||
// Ошибки домена. HTTP-слой переводит их в коды контракта и не показывает SQL.
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
// ErrIdempotencyConflict — тот же ключ, но другое тело запроса.
|
||||
ErrIdempotencyConflict = errors.New("idempotency conflict")
|
||||
// ErrAttachmentNotReady — вложение существует, но ещё не ready (409 по контракту).
|
||||
// В lab4 все вложения создаются сразу ready; проверка нужна для lab5+ и защищает
|
||||
// от прикрепления недообработанного файла.
|
||||
ErrAttachmentNotReady = errors.New("attachment not ready")
|
||||
)
|
||||
|
||||
// User — публичные поля пользователя. Hash пароля в эту структуру не попадает.
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Chat — чат и явный состав участников.
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Message — одно подтверждённое сообщение. sender_id назначает сервер.
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
// AttachmentIDs — вложения в порядке, заданном клиентом. Никогда nil в ответах API
|
||||
// (контракт: attachment_ids обязателен, по умолчанию []).
|
||||
AttachmentIDs []uuid.UUID
|
||||
}
|
||||
|
||||
// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api.
|
||||
type PageCursor struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
Scope string
|
||||
}
|
||||
|
||||
// Store — пул соединений. Пул ограничен, у каждого запроса свой таймаут.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
hasher *auth.Hasher
|
||||
}
|
||||
|
||||
// Open поднимает пул. ConnectTimeout короткий, чтобы недоступная БД быстро стала 503,
|
||||
// а не висела до клиентского таймаута теста.
|
||||
// maxConns — на одну реплику; при N репликах суммарный пул ≈ N*maxConns.
|
||||
func Open(ctx context.Context, databaseURL string, hasher *auth.Hasher, maxConns int32) (*Store, error) {
|
||||
if maxConns < 1 {
|
||||
maxConns = 5
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database url: %w", err)
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
||||
cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
// UTC, чтобы timestamptz читался так же, как мы его записали.
|
||||
// statement_timeout обрывает запрос, который внезапно решил сканировать всё.
|
||||
_, err := conn.Exec(ctx, `SET TIME ZONE 'UTC'; SET statement_timeout = '3s'`)
|
||||
return err
|
||||
}
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{pool: pool, hasher: hasher}, nil
|
||||
}
|
||||
|
||||
// Close освобождает соединения при остановке процесса.
|
||||
func (s *Store) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
// Ping — проверка для /health/ready. Ошибка здесь значит «не готов», не «жив».
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateUser пишет пользователя. Повтор username → ErrConflict благодаря UNIQUE.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) {
|
||||
hash, err := auth.Hash(password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := &User{
|
||||
ID: uuid.New(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, hash, u.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// Authenticate проверяет Basic-логин. Нет пользователя и неверный пароль
|
||||
// выглядят одинаково: оба дают false без отдельной ошибки «такого логина нет».
|
||||
func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var u User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
s.hasher.Burn(password)
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if !s.hasher.Verify(hash, password) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// GetUser нужен, чтобы ответ /users/me совпал с объектом из регистрации.
|
||||
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (*User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var u User
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id).
|
||||
Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// CreateChat атомарно создаёт чат и состав. Неизвестный участник откатывает всё:
|
||||
// в таблице chats не остаётся «пустой» строки без полного состава.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
chat := &Chat{
|
||||
ID: uuid.New(),
|
||||
Title: title,
|
||||
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||
chat.ID, chat.Title, chat.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
for _, uid := range memberIDs {
|
||||
// INSERT ... SELECT вставит 0 строк, если пользователя нет, и не нарушит FK.
|
||||
tag, err := tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, id FROM users WHERE id = $2`, chat.ID, uid)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
// GetChat возвращает чат только участнику. Чужому — ErrNotFound (HTTP 404, не 403).
|
||||
func (s *Store) GetChat(ctx context.Context, chatID, userID uuid.UUID) (*Chat, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.loadChat(ctx, chatID)
|
||||
}
|
||||
|
||||
// ListChats — keyset по (created_at, id) только среди чатов этого пользователя.
|
||||
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, after *PageCursor) ([]Chat, *PageCursor, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2`, userID, limit+1)
|
||||
} else {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = $1
|
||||
AND (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []Chat
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
next, items := trimPage(items, limit, func(c Chat) (time.Time, uuid.UUID) {
|
||||
return c.CreatedAt, c.ID
|
||||
})
|
||||
for i := range items {
|
||||
members, err := s.memberIDs(ctx, items[i].ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
items[i].MemberIDs = members
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if next {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// CreateMessage пишет сообщение только если отправитель состоит в чате.
|
||||
// Подтверждение — это COMMIT строки. Следующее чтение видит её без кэша истории.
|
||||
// Без идемпотентности — только для внутренних/тестовых случаев; HTTP использует CreateMessageIdempotent.
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (*Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
// Внутренний путь без вложений; поле не nil, чтобы JSON дал [], а не null.
|
||||
AttachmentIDs: []uuid.UUID{},
|
||||
}
|
||||
tag, err := s.pool.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
|
||||
)`, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// IdempotentMessage — либо только что созданное, либо ранее сохранённое по ключу сообщение.
|
||||
type IdempotentMessage struct {
|
||||
Message *Message
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу.
|
||||
//
|
||||
// Алгоритм (общая БД, любые реплики):
|
||||
// 1. BEGIN;
|
||||
// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов
|
||||
// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения;
|
||||
// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message;
|
||||
// 4. иначе проверить членство, затем вложения (lab4): все принадлежат ЭТОМУ чату и ready,
|
||||
// строки блокируются FOR SHARE, чтобы удаление (reconciler) не вклинилось до COMMIT;
|
||||
// 5. INSERT message + INSERT message_attachments + INSERT idempotency_keys в той же
|
||||
// транзакции: сообщение либо видно целиком вместе со ссылками на вложения, либо нет;
|
||||
// 6. COMMIT (advisory lock снимается вместе с транзакцией).
|
||||
//
|
||||
// Чужое и неизвестное вложение (в т.ч. из другого чата) неразличимы: оба дают ErrNotFound
|
||||
// (HTTP 404), чтобы нельзя было перебором выяснить, существует ли чужой файл.
|
||||
//
|
||||
// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает:
|
||||
// запись ключа только после успешной подготовки 201.
|
||||
func (s *Store) CreateMessageIdempotent(
|
||||
ctx context.Context,
|
||||
chatID, senderID uuid.UUID,
|
||||
text string,
|
||||
attachmentIDs []uuid.UUID,
|
||||
method, path, idemKey, requestHash string,
|
||||
) (*IdempotentMessage, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
lockKey := idempotencyLockKey(senderID, method, path, idemKey)
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockKey); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var (
|
||||
storedHash string
|
||||
msgID uuid.UUID
|
||||
msgChat uuid.UUID
|
||||
msgSender uuid.UUID
|
||||
msgText string
|
||||
msgCreated time.Time
|
||||
)
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT i.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1 AND i.method = $2 AND i.path = $3 AND i.key = $4`,
|
||||
senderID, method, path, idemKey,
|
||||
).Scan(&storedHash, &msgID, &msgChat, &msgSender, &msgText, &msgCreated)
|
||||
if err == nil {
|
||||
if storedHash != requestHash {
|
||||
return nil, ErrIdempotencyConflict
|
||||
}
|
||||
// Replay обязан вернуть ТОТ ЖЕ набор вложений, что и первый ответ.
|
||||
replayIDs, err := loadMessageAttachmentIDs(ctx, tx, msgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{
|
||||
Message: &Message{
|
||||
ID: msgID,
|
||||
ChatID: msgChat,
|
||||
SenderID: msgSender,
|
||||
Text: msgText,
|
||||
CreatedAt: msgCreated,
|
||||
AttachmentIDs: replayIDs,
|
||||
},
|
||||
Replayed: true,
|
||||
}, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// Вложения проверяем ПОСЛЕ членства: посторонний в чат получает 404 по чату,
|
||||
// а не информацию о существовании файлов.
|
||||
if err := lockMessageAttachments(ctx, tx, chatID, attachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: nowUTC(),
|
||||
AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
// Порядок attachment_ids клиента сохраняется в position.
|
||||
for i, aid := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
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,
|
||||
"created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"),
|
||||
"attachment_ids": attachmentStrs,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `
|
||||
INSERT INTO idempotency_keys (
|
||||
user_id, method, path, key, request_hash,
|
||||
response_status, response_body, message_id, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
|
||||
senderID, method, path, idemKey, requestHash,
|
||||
201, bodyJSON, msg.ID, msg.CreatedAt); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &IdempotentMessage{Message: msg, Replayed: false}, nil
|
||||
}
|
||||
|
||||
// idempotencyLockKey — стабильный int64 для pg_advisory_xact_lock из области ключа.
|
||||
func idempotencyLockKey(userID uuid.UUID, method, path, key string) int64 {
|
||||
sum := sha256.Sum256([]byte(userID.String() + "|" + method + "|" + path + "|" + key))
|
||||
return int64(binary.BigEndian.Uint64(sum[:8]))
|
||||
}
|
||||
|
||||
// ListMessages — keyset по индексу messages_history_idx. Берём limit+1 строку,
|
||||
// чтобы next_cursor был null, когда следующей записи уже нет.
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limit int, after *PageCursor) ([]Message, *PageCursor, error) {
|
||||
if err := s.ensureMember(ctx, chatID, userID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
if after == nil {
|
||||
rows, err = s.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2`, chatID, limit+1)
|
||||
} else {
|
||||
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
|
||||
LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Message
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, mapWriteErr(err)
|
||||
}
|
||||
hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) {
|
||||
return m.CreatedAt, m.ID
|
||||
})
|
||||
// Вложения страницы одним запросом (а не N+1): WHERE message_id = ANY(id страницы).
|
||||
if err := s.attachMessageAttachments(ctx, items); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var cursor *PageCursor
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID}
|
||||
}
|
||||
return items, cursor, nil
|
||||
}
|
||||
|
||||
// ChatExistsForTitle помогает тесту отката: после ошибки создания чата строки нет.
|
||||
func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var n int
|
||||
err := s.pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&n)
|
||||
if err != nil {
|
||||
return 0, mapWriteErr(err)
|
||||
}
|
||||
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()
|
||||
var one int
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&one)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) loadChat(ctx context.Context, chatID uuid.UUID) (*Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
var c Chat
|
||||
err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID).
|
||||
Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
c.MemberIDs, err = s.memberIDs(ctx, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (s *Store) memberIDs(ctx context.Context, chatID uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id`, chatID)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []uuid.UUID
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
func trimPage[T any](items []T, limit int, _ func(T) (time.Time, uuid.UUID)) (bool, []T) {
|
||||
if len(items) > limit {
|
||||
return true, items[:limit]
|
||||
}
|
||||
return false, items
|
||||
}
|
||||
|
||||
func nowUTC() time.Time {
|
||||
// Миллисекунда — точность, которую мы же и печатаем в JSON.
|
||||
return time.Now().UTC().Truncate(time.Millisecond)
|
||||
}
|
||||
|
||||
func mapWriteErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return ErrConflict
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || isConn(err) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isConn(err error) bool {
|
||||
msg := err.Error()
|
||||
// Не логируем и не возвращаем клиенту эту строку. Здесь только классификация.
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return false
|
||||
default:
|
||||
if stringsContains(msg, "connection refused") ||
|
||||
stringsContains(msg, "failed to connect") ||
|
||||
stringsContains(msg, "conn closed") ||
|
||||
stringsContains(msg, "closed pool") ||
|
||||
stringsContains(msg, "broken pipe") ||
|
||||
stringsContains(msg, "connection reset") ||
|
||||
stringsContains(msg, "SQLSTATE 57P01") ||
|
||||
stringsContains(msg, "SQLSTATE 08006") ||
|
||||
stringsContains(msg, "SQLSTATE 08001") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func stringsContains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (s == sub || len(sub) == 0 ||
|
||||
(func() bool { return contains(s, sub) })())
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user