Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.
Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready; компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
This commit is contained in:
@@ -0,0 +1,448 @@
|
||||
package api
|
||||
|
||||
// Вложения lab4: загрузка, метаданные, скачивание.
|
||||
//
|
||||
// Загрузка (POST /chats/{id}/attachments?filename=...) идёт строго по шагам, и каждый шаг
|
||||
// отсекает запрос как можно раньше и дешевле:
|
||||
//
|
||||
// 1. Bearer-аутентификация (requireUser), затем членство в чате: посторонний получает 404;
|
||||
// 2. filename: 1–255 code points, без «/», «\», NUL и управляющих символов — иначе 400;
|
||||
// 3. заявленный Content-Type — только image/png или image/jpeg, иначе 415;
|
||||
// 4. тело копируется в спул (временный файл, при его отказе — память) с одновременным SHA-256
|
||||
// и жёстким лимитом MaxUploadBytes+1: больше лимита — 413. Тело не буферизуется целиком
|
||||
// в куче через ReadAll, поэтому пик RAM на загрузку — буфер копирования, а не размер файла;
|
||||
// 5. тип по содержимому (http.DetectContentType) обязан совпасть с заявленным, иначе 415 (подмена MIME);
|
||||
// 6. размеры берутся из заголовка PNG/JPEG БЕЗ декодирования пикселей; больше
|
||||
// MaxImagePixels — 413. Это делается до любой «распаковки»: bomb 60000×60000 весит килобайты;
|
||||
// 7. дешёвая структурная проверка (PNG: CRC всех чанков и IEND, JPEG: EOI) ловит обрезанные
|
||||
// и повреждённые файлы — 415;
|
||||
// 8. PUT в S3 по серверному ключу originals/<uuid>, затем INSERT метаданных. Только после
|
||||
// обоих шагов — 201. Если INSERT не удался, объект удаляется сразу, а при отказе удаления
|
||||
// его подберёт reconciler (cmd/reconcile) после grace period.
|
||||
//
|
||||
// До шага 8 в S3 ничего не пишется, поэтому оборванная загрузка клиента не оставляет объектов.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
_ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"mtusi2026lab4/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxMessageAttachments = 10
|
||||
maxFilenameRunes = 255
|
||||
// После превышения лимита дочитываем (и выбрасываем) не больше этого объёма:
|
||||
// клиент успевает получить 413, а не «connection reset» посреди своей отправки.
|
||||
drainOnOverflow = 64 << 20
|
||||
)
|
||||
|
||||
var (
|
||||
errBadImage = errors.New("not a valid png/jpeg image")
|
||||
errTooManyPixels = errors.New("image has too many pixels")
|
||||
errTooLarge = errors.New("upload exceeds size limit")
|
||||
)
|
||||
|
||||
func (s *Server) handleUploadAttachment(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
|
||||
}
|
||||
uid := userFrom(r)
|
||||
if err := s.Store.EnsureChatMember(r.Context(), chatID, uid); err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if !validFilename(filename) {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid filename")
|
||||
return
|
||||
}
|
||||
declared, ok := declaredImageType(r.Header.Get("Content-Type"))
|
||||
if !ok {
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "only image/png and image/jpeg are accepted")
|
||||
return
|
||||
}
|
||||
// Клиент заранее заявил размер сильно больше лимита — не читаем ни байта.
|
||||
if r.ContentLength > s.MaxUploadBytes+drainOnOverflow {
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
return
|
||||
}
|
||||
|
||||
sp, err := spoolBody(r.Body, s.MaxUploadBytes)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, errTooLarge):
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
|
||||
default:
|
||||
// Обрыв чтения тела или таймаут клиента. Ничего не записано ни в S3, ни в БД.
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "could not read request body")
|
||||
}
|
||||
return
|
||||
}
|
||||
defer sp.Close()
|
||||
|
||||
if err := inspectImage(sp.reader(), sp.size, declared, s.MaxImagePixels); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, errTooManyPixels):
|
||||
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels")
|
||||
default:
|
||||
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "invalid or unsupported image")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
att := &store.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: uid,
|
||||
Filename: filename,
|
||||
ContentType: declared,
|
||||
SizeBytes: sp.size,
|
||||
SHA256: sp.sum,
|
||||
ObjectKey: blob.KeyPrefix + id.String(),
|
||||
}
|
||||
|
||||
// 1) S3. Тело отдаём как ReadSeeker: minio-go шлёт один PUT без буферизации в памяти.
|
||||
if err := s.Blob.Put(r.Context(), att.ObjectKey, sp.reader(), sp.size, declared); err != nil {
|
||||
s.writeBlobErr(w, r, err)
|
||||
return
|
||||
}
|
||||
// 2) PostgreSQL. Ошибка здесь оставила бы объект без строки — убираем его сразу.
|
||||
if err := s.Store.CreateAttachment(r.Context(), att); err != nil {
|
||||
s.compensateOrphan(r, att.ObjectKey)
|
||||
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, attachmentDTO(att))
|
||||
}
|
||||
|
||||
// compensateOrphan удаляет объект, для которого не удалось записать метаданные.
|
||||
// Контекст отвязан от запроса: клиент мог отключиться, а чистить всё равно нужно.
|
||||
// Если и удаление не удалось (S3 мигнул), объект останется до reconciler — это допустимо.
|
||||
func (s *Server) compensateOrphan(r *http.Request, key string) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := s.Blob.Delete(ctx, key); err != nil {
|
||||
log.Printf("request_id=%s orphan_cleanup_failed key=%s (reconciler will remove after grace)", requestID(r), key)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleGetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
att, ok := s.loadAttachment(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, attachmentDTO(att))
|
||||
}
|
||||
|
||||
// handleDownloadAttachment отдаёт оригинал побайтно через API, без редиректа на S3:
|
||||
// приватный bucket сам по себе не заменяет проверку членства в чате.
|
||||
func (s *Server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
att, ok := s.loadAttachment(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// variant по умолчанию original. В lab4 вариантов нет (variants=[]), значит любой
|
||||
// другой — «отсутствующий вариант ready-объекта», то есть 404.
|
||||
if v := r.URL.Query().Get("variant"); v != "" && v != "original" {
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
switch att.Status {
|
||||
case "ready":
|
||||
default:
|
||||
writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready")
|
||||
return
|
||||
}
|
||||
rc, err := s.Blob.Get(r.Context(), att.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, blob.ErrNotFound) {
|
||||
// Строка есть, объекта нет — несогласованность, её чинит reconciler.
|
||||
log.Printf("request_id=%s attachment_object_missing id=%s", requestID(r), att.ID)
|
||||
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
|
||||
return
|
||||
}
|
||||
s.writeBlobErr(w, r, err)
|
||||
return
|
||||
}
|
||||
defer rc.Close()
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", att.ContentType)
|
||||
h.Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10))
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Cache-Control", "private, no-store")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, rc); err != nil {
|
||||
// Заголовки уже ушли; клиент увидит обрыв. В лог — без деталей S3.
|
||||
log.Printf("request_id=%s attachment_stream_error id=%s", requestID(r), att.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// loadAttachment разбирает {attachment_id} и проверяет членство в чате вложения.
|
||||
func (s *Server) loadAttachment(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.GetAttachment(r.Context(), id, userFrom(r))
|
||||
if err != nil {
|
||||
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
|
||||
return nil, false
|
||||
}
|
||||
return att, true
|
||||
}
|
||||
|
||||
// writeBlobErr: недоступный S3 — 503, остальное — 500. Текст ошибки клиенту не уходит.
|
||||
func (s *Server) writeBlobErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, blob.ErrUnavailable) {
|
||||
log.Printf("request_id=%s s3_unavailable", requestID(r))
|
||||
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
|
||||
return
|
||||
}
|
||||
log.Printf("request_id=%s blob_error_type=%T", requestID(r), err)
|
||||
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
}
|
||||
|
||||
func attachmentDTO(a *store.Attachment) map[string]any {
|
||||
var errCode any
|
||||
if a.ErrorCode != nil {
|
||||
errCode = *a.ErrorCode
|
||||
}
|
||||
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,
|
||||
"variants": []any{},
|
||||
"error_code": errCode,
|
||||
"created_at": formatTime(a.CreatedAt),
|
||||
"updated_at": formatTime(a.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
// validFilename: 1–255 code points, валидный UTF-8, не «пустой» после TrimSpace.
|
||||
// «/», «\», NUL и управляющие символы запрещены: имя только отображается и никогда не
|
||||
// становится путём или ключом S3. «.» и «..» отвергаются как заведомо опасные.
|
||||
func validFilename(name string) bool {
|
||||
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" {
|
||||
return false
|
||||
}
|
||||
if n := utf8.RuneCountInString(name); n < 1 || n > maxFilenameRunes {
|
||||
return false
|
||||
}
|
||||
if name == "." || name == ".." {
|
||||
return false
|
||||
}
|
||||
for _, c := range name {
|
||||
if c == '/' || c == '\\' || c == 0 || unicode.IsControl(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// declaredImageType возвращает заявленный Content-Type без параметров, если он разрешён.
|
||||
func declaredImageType(header string) (string, bool) {
|
||||
mt, _, err := mime.ParseMediaType(header)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
switch mt {
|
||||
case "image/png", "image/jpeg":
|
||||
return mt, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// spooled — принятое тело: размер, SHA-256 и произвольный доступ для проверок и PUT.
|
||||
type spooled struct {
|
||||
ra io.ReaderAt
|
||||
size int64
|
||||
sum string
|
||||
cleanup func()
|
||||
}
|
||||
|
||||
func (s *spooled) reader() *io.SectionReader { return io.NewSectionReader(s.ra, 0, s.size) }
|
||||
func (s *spooled) Close() { s.cleanup() }
|
||||
|
||||
// spoolBody читает тело не больше max байт. Временный файл защищает кучу от 10 одновременных
|
||||
// загрузок по 10 MiB; если /tmp недоступен, откатываемся на память (всё равно ограниченную max).
|
||||
func spoolBody(body io.Reader, max int64) (*spooled, error) {
|
||||
h := sha256.New()
|
||||
f, ferr := os.CreateTemp("", "upload-*")
|
||||
var (
|
||||
dst io.Writer
|
||||
buf *bytes.Buffer
|
||||
cleanup = func() {}
|
||||
)
|
||||
if ferr == nil {
|
||||
cleanup = func() { _ = f.Close(); _ = os.Remove(f.Name()) }
|
||||
dst = io.MultiWriter(f, h)
|
||||
} else {
|
||||
buf = &bytes.Buffer{}
|
||||
dst = io.MultiWriter(buf, h)
|
||||
}
|
||||
n, err := io.Copy(dst, io.LimitReader(body, max+1))
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, err
|
||||
}
|
||||
if n > max {
|
||||
cleanup()
|
||||
_, _ = io.CopyN(io.Discard, body, drainOnOverflow)
|
||||
return nil, errTooLarge
|
||||
}
|
||||
sp := &spooled{size: n, sum: hex.EncodeToString(h.Sum(nil)), cleanup: cleanup}
|
||||
if f != nil && ferr == nil {
|
||||
sp.ra = f
|
||||
} else {
|
||||
sp.ra = bytes.NewReader(buf.Bytes())
|
||||
}
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
// inspectImage проверяет содержимое. Порядок важен: тип → размеры из заголовка (лимит
|
||||
// пикселей до любой распаковки) → структура файла.
|
||||
func inspectImage(sr *io.SectionReader, size int64, declared string, maxPixels int64) error {
|
||||
head := make([]byte, 512)
|
||||
n, _ := sr.ReadAt(head, 0)
|
||||
detected := ""
|
||||
if n > 0 {
|
||||
detected = http.DetectContentType(head[:n])
|
||||
}
|
||||
if size < 1 || (detected != "image/png" && detected != "image/jpeg") || detected != declared {
|
||||
return errBadImage
|
||||
}
|
||||
|
||||
var w, h int64
|
||||
switch detected {
|
||||
case "image/png":
|
||||
// IHDR всегда первый чанк: 8 байт сигнатуры, 4 длина, 4 тип, затем width/height.
|
||||
// Читаем сами: image/png.DecodeConfig отвергает файл с битым CRC раньше, чем
|
||||
// мы успели бы честно ответить «слишком много пикселей».
|
||||
if n < 24 || string(head[12:16]) != "IHDR" || binary.BigEndian.Uint32(head[8:12]) != 13 {
|
||||
return errBadImage
|
||||
}
|
||||
w = int64(binary.BigEndian.Uint32(head[16:20]))
|
||||
h = int64(binary.BigEndian.Uint32(head[20:24]))
|
||||
case "image/jpeg":
|
||||
cfg, _, err := image.DecodeConfig(io.NewSectionReader(sr, 0, size))
|
||||
if err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
w, h = int64(cfg.Width), int64(cfg.Height)
|
||||
}
|
||||
if w < 1 || h < 1 {
|
||||
return errBadImage
|
||||
}
|
||||
if w*h > maxPixels {
|
||||
return errTooManyPixels
|
||||
}
|
||||
|
||||
if detected == "image/png" {
|
||||
return verifyPNG(io.NewSectionReader(sr, 0, size), size)
|
||||
}
|
||||
return verifyJPEGTail(sr, size)
|
||||
}
|
||||
|
||||
// verifyPNG обходит чанки и проверяет их CRC без декомпрессии IDAT: обрезанный или
|
||||
// испорченный PNG отвергается за один линейный проход по файлу.
|
||||
func verifyPNG(r io.Reader, size int64) error {
|
||||
br := bufio.NewReaderSize(r, 64<<10)
|
||||
if _, err := br.Discard(8); err != nil { // сигнатура уже проверена DetectContentType
|
||||
return errBadImage
|
||||
}
|
||||
consumed := int64(8)
|
||||
var (
|
||||
hdr [8]byte
|
||||
crcBuf [4]byte
|
||||
first = true
|
||||
sawIDAT bool
|
||||
sawIEND bool
|
||||
crcHasher = crc32.NewIEEE()
|
||||
)
|
||||
for !sawIEND {
|
||||
if _, err := io.ReadFull(br, hdr[:]); err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
length := int64(binary.BigEndian.Uint32(hdr[0:4]))
|
||||
ctype := string(hdr[4:8])
|
||||
if length > size-consumed-12 {
|
||||
return errBadImage
|
||||
}
|
||||
if first && ctype != "IHDR" {
|
||||
return errBadImage
|
||||
}
|
||||
first = false
|
||||
crcHasher.Reset()
|
||||
_, _ = crcHasher.Write(hdr[4:8])
|
||||
if _, err := io.CopyN(crcHasher, br, length); err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
if _, err := io.ReadFull(br, crcBuf[:]); err != nil {
|
||||
return errBadImage
|
||||
}
|
||||
if crcHasher.Sum32() != binary.BigEndian.Uint32(crcBuf[:]) {
|
||||
return errBadImage
|
||||
}
|
||||
consumed += 12 + length
|
||||
switch ctype {
|
||||
case "IDAT":
|
||||
sawIDAT = true
|
||||
case "IEND":
|
||||
sawIEND = true
|
||||
}
|
||||
}
|
||||
// Данные после IEND — признак полиглота или склейки файлов, не принимаем.
|
||||
if !sawIDAT || consumed != size {
|
||||
return errBadImage
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyJPEGTail требует маркер конца изображения EOI (FF D9) в хвосте файла.
|
||||
// Допускаются нулевые/мусорные байты выравнивания после него (до 1 KiB).
|
||||
func verifyJPEGTail(sr *io.SectionReader, size int64) error {
|
||||
tailLen := int64(1024)
|
||||
if size < tailLen {
|
||||
tailLen = size
|
||||
}
|
||||
tail := make([]byte, tailLen)
|
||||
if _, err := sr.ReadAt(tail, size-tailLen); err != nil && !errors.Is(err, io.EOF) {
|
||||
return errBadImage
|
||||
}
|
||||
if bytes.LastIndex(tail, []byte{0xFF, 0xD9}) < 0 {
|
||||
return errBadImage
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,780 @@
|
||||
// Package api — HTTP-слой lab4 (поверх lab3: LB, идемпотентность, сессии в Redis).
|
||||
//
|
||||
// Порядок обработки запроса:
|
||||
// 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:
|
||||
// без них нельзя честно принять запись или узнать, кто делает запрос.
|
||||
//
|
||||
// POST сообщения требует Idempotency-Key; результат хранится в общей БД, а не в памяти реплики.
|
||||
//
|
||||
// Вложения (attachments.go): сырой PNG/JPEG в теле POST, байты в приватном S3, метаданные в
|
||||
// PostgreSQL. Скачивание — только через этот API, без редиректа на S3.
|
||||
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"
|
||||
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"mtusi2026lab4/internal/session"
|
||||
"mtusi2026lab4/internal/store"
|
||||
)
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const (
|
||||
userKey ctxKey = iota
|
||||
tokenKey
|
||||
requestIDKey
|
||||
)
|
||||
|
||||
const (
|
||||
challengeBasic = `Basic realm="messenger", charset="UTF-8"`
|
||||
challengeBearer = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
// Лимиты вложений по контракту lab4.
|
||||
const (
|
||||
DefaultMaxUploadBytes int64 = 10 << 20 // 10 MiB = 10 485 760
|
||||
DefaultMaxImagePixels int64 = 40_000_000
|
||||
)
|
||||
|
||||
// BlobStore — то, что API требует от S3-клиента. *blob.Client его реализует;
|
||||
// интерфейс нужен, чтобы тест мог подставить недоступное хранилище.
|
||||
type BlobStore interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
var _ BlobStore = (*blob.Client)(nil)
|
||||
|
||||
// Server связывает HTTP с PostgreSQL, Redis и S3.
|
||||
type Server struct {
|
||||
Store *store.Store
|
||||
Sessions *session.Store
|
||||
Blob BlobStore
|
||||
InstanceID string
|
||||
// Лимиты загрузки. По умолчанию контрактные; main.go может только ужесточить.
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
// New помечает процесс готовым. Реальная зависимость всё равно проверяется в /health/ready.
|
||||
// instanceID попадает в X-Instance-Id каждого ответа и стабилен на жизнь процесса.
|
||||
func New(st *store.Store, sessions *session.Store, bl BlobStore, instanceID string) *Server {
|
||||
s := &Server{
|
||||
Store: st, Sessions: sessions, Blob: bl, InstanceID: instanceID,
|
||||
MaxUploadBytes: DefaultMaxUploadBytes,
|
||||
MaxImagePixels: DefaultMaxImagePixels,
|
||||
}
|
||||
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))
|
||||
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
|
||||
}
|
||||
// S3 — обязательная зависимость синхронного пути (загрузка и скачивание вложений).
|
||||
if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil ||
|
||||
s.Blob.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 и [] равны для хэша.
|
||||
if len(body.AttachmentIDs) > maxMessageAttachments {
|
||||
writeError(w, r, http.StatusBadRequest, "invalid_request", "too many attachments")
|
||||
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, но только если вложений нет:
|
||||
// text="" с хотя бы одним вложением разрешён контрактом lab4.
|
||||
// Пробелы по краям сохраняются как есть, иначе «пробел + 4000 букв» проходил бы как 4000.
|
||||
if utf8.RuneCountInString(body.Text) > 4000 ||
|
||||
(len(attachmentIDs) == 0 && strings.TrimSpace(body.Text) == "") {
|
||||
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.ErrNotReady) {
|
||||
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 {
|
||||
// Всегда массив, даже пустой: клиент lab3 без вложений видит [] (контракт 1.4.0).
|
||||
att := make([]string, len(m.AttachmentIDs))
|
||||
for i, id := range m.AttachmentIDs {
|
||||
att[i] = id.String()
|
||||
}
|
||||
return map[string]any{
|
||||
"id": m.ID.String(),
|
||||
"chat_id": m.ChatID.String(),
|
||||
"sender_id": m.SenderID.String(),
|
||||
"text": m.Text,
|
||||
"attachment_ids": att,
|
||||
"created_at": formatTime(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
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,162 @@
|
||||
package blob
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Memory — in-memory BlobStore для student-tests без живого MinIO.
|
||||
// Не для production: нет persistence между процессами.
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
objects map[string]memObj
|
||||
down bool
|
||||
bucketOK bool
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type memObj struct {
|
||||
data []byte
|
||||
modTime time.Time
|
||||
}
|
||||
|
||||
// NewMemory создаёт пустое хранилище с «живым» бакетом.
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{
|
||||
objects: make(map[string]memObj),
|
||||
bucketOK: true,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// SetUnavailable имитирует падение S3 (Ping/Put/Get → ErrUnavailable).
|
||||
func (m *Memory) SetUnavailable(v bool) { m.mu.Lock(); m.down = v; m.mu.Unlock() }
|
||||
|
||||
func (m *Memory) Bucket() string { return "memory" }
|
||||
|
||||
func (m *Memory) Ping(ctx context.Context) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down || !m.bucketOK {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Put(ctx context.Context, key string, r io.Reader, size int64, _ string) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ErrUnavailable
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(r, size+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if int64(len(data)) != size {
|
||||
return ErrUnavailable
|
||||
}
|
||||
m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: m.now()}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
o, ok := m.objects[key]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(o.data)), nil
|
||||
}
|
||||
|
||||
func (m *Memory) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ObjectInfo{}, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ObjectInfo{}, ErrUnavailable
|
||||
}
|
||||
o, ok := m.objects[key]
|
||||
if !ok {
|
||||
return ObjectInfo{}, ErrNotFound
|
||||
}
|
||||
return ObjectInfo{Key: key, Size: int64(len(o.data)), LastModified: o.modTime}, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(ctx context.Context, key string) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ErrUnavailable
|
||||
}
|
||||
delete(m.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var out []ObjectInfo
|
||||
for k, o := range m.objects {
|
||||
if len(prefix) == 0 || (len(k) >= len(prefix) && k[:len(prefix)] == prefix) {
|
||||
out = append(out, ObjectInfo{Key: k, Size: int64(len(o.data)), LastModified: o.modTime})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Seed кладёт объект напрямую (для тестов reconciler).
|
||||
func (m *Memory) Seed(key string, data []byte, modTime time.Time) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if modTime.IsZero() {
|
||||
modTime = m.now()
|
||||
}
|
||||
m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: modTime}
|
||||
}
|
||||
|
||||
var _ interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
} = (*Memory)(nil)
|
||||
@@ -0,0 +1,197 @@
|
||||
// Package blob — тонкая обёртка над MinIO (S3 API) для оригиналов вложений lab4.
|
||||
//
|
||||
// Байты файлов живут только здесь, а не в PostgreSQL и не на диске API-реплики.
|
||||
// Ключ объекта назначает сервер (originals/<uuid>); filename клиента в ключ не попадает.
|
||||
// Bucket приватный: прямого доступа без подписи нет, скачивание идёт через авторизованный API.
|
||||
//
|
||||
// Ошибки сведены к двум классам, чтобы HTTP-слой не знал про minio-go:
|
||||
// ErrNotFound — объекта нет (404/500 по контексту), ErrUnavailable — S3 недоступен (503).
|
||||
package blob
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// KeyPrefix — префикс ключей оригиналов. Reconciler обходит только его.
|
||||
const KeyPrefix = "originals/"
|
||||
|
||||
var (
|
||||
// ErrNotFound — такого объекта в бакете нет.
|
||||
ErrNotFound = errors.New("blob: not found")
|
||||
// ErrUnavailable — S3 не отвечает, отказал в доступе или вернул неожиданную ошибку.
|
||||
ErrUnavailable = errors.New("blob: unavailable")
|
||||
)
|
||||
|
||||
// Config — параметры подключения. Секреты приходят из окружения/файла, в логи не попадают.
|
||||
type Config struct {
|
||||
Endpoint string // host:port без схемы, например minio:9000
|
||||
UseSSL bool
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
// ObjectInfo — то, что reconciler и тесты знают об объекте.
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// Client — клиент одного бакета.
|
||||
type Client struct {
|
||||
mc *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
// New создаёт клиента. Сеть не трогает: доступность проверяют Ping/EnsureBucket.
|
||||
//
|
||||
// Таймауты заданы явно. Без них connection refused ретраится minio-go десяток раз,
|
||||
// и «S3 лежит» вместо быстрого 503 превращается в зависший запрос.
|
||||
func New(cfg Config) (*Client, error) {
|
||||
if cfg.Endpoint == "" || cfg.Bucket == "" {
|
||||
return nil, fmt.Errorf("blob: endpoint and bucket are required")
|
||||
}
|
||||
tr := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 2 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 64,
|
||||
MaxIdleConnsPerHost: 32,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 20 * time.Second,
|
||||
}
|
||||
mc, err := minio.New(cfg.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
Transport: tr,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("blob: init client: %w", err)
|
||||
}
|
||||
return &Client{mc: mc, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
// Bucket возвращает имя бакета (для логов и отчётов).
|
||||
func (c *Client) Bucket() string { return c.bucket }
|
||||
|
||||
// EnsureBucket создаёт бакет, если его нет. Идемпотентно.
|
||||
// В Compose бакет создаёт minio-init с root-правами, а у app-пользователя прав на
|
||||
// создание нет — функция нужна локальным тестам и ручному запуску на «голом» MinIO.
|
||||
func (c *Client) EnsureBucket(ctx context.Context) error {
|
||||
ok, err := c.mc.BucketExists(ctx, c.bucket)
|
||||
if err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
if err := c.mc.MakeBucket(ctx, c.bucket, minio.MakeBucketOptions{}); err != nil {
|
||||
// Гонка двух инициализаторов: бакет уже создан соседом.
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
if code == "BucketAlreadyOwnedByYou" || code == "BucketAlreadyExists" {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping — проверка для /health/ready. Короткий таймаут: readiness не должна висеть.
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancel()
|
||||
ok, err := c.mc.BucketExists(ctx, c.bucket)
|
||||
if err != nil || !ok {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Put кладёт объект известного размера. r должен уметь Seek (файл или bytes.Reader):
|
||||
// тогда minio-go отправляет тело одним запросом без буферизации в памяти.
|
||||
func (c *Client) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := c.mc.PutObject(ctx, c.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
// Один PUT для файлов до лимита lab4 (10 MiB): multipart не нужен.
|
||||
DisableMultipart: true,
|
||||
})
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// Get открывает объект на чтение. Существование проверяется сразу (Stat), чтобы HTTP-слой
|
||||
// успел вернуть 404/503 до отправки заголовков 200.
|
||||
func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
obj, err := c.mc.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, classify(err)
|
||||
}
|
||||
if _, err := obj.Stat(); err != nil {
|
||||
_ = obj.Close()
|
||||
return nil, classify(err)
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// Stat возвращает метаданные объекта или ErrNotFound.
|
||||
func (c *Client) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
st, err := c.mc.StatObject(ctx, c.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return ObjectInfo{}, classify(err)
|
||||
}
|
||||
return ObjectInfo{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil
|
||||
}
|
||||
|
||||
// Delete удаляет объект. Отсутствие объекта — не ошибка (S3 DELETE идемпотентен).
|
||||
func (c *Client) Delete(ctx context.Context, key string) error {
|
||||
err := c.mc.RemoveObject(ctx, c.bucket, key, minio.RemoveObjectOptions{})
|
||||
if err != nil && errors.Is(classify(err), ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// ListKeys возвращает все объекты с префиксом (рекурсивно). Для reconciler:
|
||||
// стоимость обхода — O(число объектов), память — по записи на объект.
|
||||
func (c *Client) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
var out []ObjectInfo
|
||||
for o := range c.mc.ListObjects(ctx, c.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if o.Err != nil {
|
||||
return nil, classify(o.Err)
|
||||
}
|
||||
out = append(out, ObjectInfo{Key: o.Key, Size: o.Size, LastModified: o.LastModified})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// classify сводит ошибки minio-go к ErrNotFound/ErrUnavailable. Текст исходной ошибки
|
||||
// наружу не возвращаем: в нём могут быть endpoint и имя бакета.
|
||||
func classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return ErrNotFound
|
||||
}
|
||||
if minio.ToErrorResponse(err).StatusCode == http.StatusNotFound &&
|
||||
minio.ToErrorResponse(err).Code != "NoSuchBucket" {
|
||||
return ErrNotFound
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Package config читает настройки процесса из окружения.
|
||||
//
|
||||
// Для lab4 добавлены S3_* и лимиты вложений.
|
||||
//
|
||||
// Прямые 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). Контракт: 10 MiB и 40 млн пикселей.
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
// ReconcileGrace — минимальный возраст объекта/строки, прежде чем reconciler их тронет.
|
||||
ReconcileGrace time.Duration
|
||||
}
|
||||
|
||||
// S3 — параметры подключения к S3-совместимому хранилищу.
|
||||
type S3 struct {
|
||||
Endpoint string
|
||||
UseSSL bool
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
cfg.MaxUploadBytes, err = getenvInt64("MAX_UPLOAD_BYTES", 10485760, 1, 10485760)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.MaxImagePixels, err = getenvInt64("MAX_IMAGE_PIXELS", 40000000, 1, 40000000)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
graceSec, err := getenvInt64("S3_RECONCILE_GRACE_SECONDS", 60, 0, 7*24*3600)
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.ReconcileGrace = time.Duration(graceSec) * time.Second
|
||||
|
||||
cfg.RunMigrations = truthy(os.Getenv("RUN_MIGRATIONS"))
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadS3 читает настройки S3. Ключи — из S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY
|
||||
// либо из файлов *_FILE. Пустые ключи — ошибка запуска API (migrate без S3 обходится).
|
||||
func LoadS3() (S3, error) {
|
||||
var (
|
||||
c S3
|
||||
err error
|
||||
)
|
||||
c.Endpoint = getenv("S3_ENDPOINT", "minio:9000")
|
||||
// Endpoint может прийти со схемой http:// — minio-go ждёт host:port.
|
||||
c.Endpoint = strings.TrimPrefix(c.Endpoint, "https://")
|
||||
c.Endpoint = strings.TrimPrefix(c.Endpoint, "http://")
|
||||
c.Region = getenv("S3_REGION", "us-east-1")
|
||||
c.Bucket = getenv("S3_BUCKET", "messenger-attachments")
|
||||
c.UseSSL = truthy(os.Getenv("S3_USE_SSL"))
|
||||
c.AccessKey, err = getenvOrFile("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.SecretKey, err = getenvOrFile("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, 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 getenvInt64(key string, fallback, lo, hi int64) (int64, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(key))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || n < lo || n > hi {
|
||||
return 0, fmt.Errorf("invalid %s", key)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
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,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,209 @@
|
||||
// Вложения lab4: метаданные в PostgreSQL, байты в S3 (пакет blob).
|
||||
//
|
||||
// Согласованность двух хранилищ строится на порядке «сначала S3, потом БД»:
|
||||
// 1. PUT объекта в S3 по серверному ключу;
|
||||
// 2. INSERT строки attachments.
|
||||
//
|
||||
// Если PUT прошёл, а INSERT нет, остаётся объект без строки (orphan). API пытается удалить
|
||||
// его сразу, а если не вышло, его удалит reconciler после grace period. Обратный порядок
|
||||
// опаснее: строка без объекта отдавала бы клиенту 201 на файл, которого нет.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// ErrNotReady — вложение существует в этом чате, но ещё не ready (в lab4 недостижимо,
|
||||
// зарезервировано под асинхронную обработку lab5).
|
||||
var ErrNotReady = errors.New("attachment not ready")
|
||||
|
||||
// Attachment — метаданные оригинала. ObjectKey во внешний JSON не попадает.
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
ObjectKey string
|
||||
Status string
|
||||
ErrorCode *string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// CreateAttachment пишет метаданные после успешного PUT в S3. ID и ObjectKey задаёт вызывающий:
|
||||
// ключ нужен до записи в БД. Членство в чате проверяется в самом INSERT — если автора уже
|
||||
// нет в чате, строка не появится и вернётся ErrNotFound.
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
now := nowUTC()
|
||||
a.Status = "ready"
|
||||
a.ErrorCode = nil
|
||||
a.CreatedAt, a.UpdatedAt = now, now
|
||||
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, created_at, updated_at
|
||||
)
|
||||
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $10
|
||||
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.CreatedAt)
|
||||
if err != nil {
|
||||
return mapWriteErr(err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAttachment отдаёт вложение только участнику его чата. Чужому и несуществующему —
|
||||
// одинаковый ErrNotFound (HTTP 404): наличие чужого файла не раскрываем.
|
||||
func (s *Store) GetAttachment(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.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.CreatedAt, &a.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// EnsureChatMember — публичная проверка «пользователь состоит в чате» (ErrNotFound иначе).
|
||||
func (s *Store) EnsureChatMember(ctx context.Context, chatID, userID uuid.UUID) error {
|
||||
return s.ensureMember(ctx, chatID, userID)
|
||||
}
|
||||
|
||||
// ListAttachmentIDsForMessage возвращает ID вложений сообщения в порядке запроса.
|
||||
// Пустой результат — непустой срез нулевой длины, чтобы JSON дал [], а не null.
|
||||
func (s *Store) ListAttachmentIDsForMessage(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, queryTimeout)
|
||||
defer cancel()
|
||||
byMsg, err := attachmentIDsByMessage(ctx, s.pool, []uuid.UUID{messageID})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return byMsg[messageID], nil
|
||||
}
|
||||
|
||||
// querier — общая часть pgxpool.Pool и pgx.Tx.
|
||||
type querier interface {
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
// attachmentIDsByMessage — один запрос на страницу сообщений (без N+1).
|
||||
// Все ключи результата заполнены: у сообщений без вложений значение — пустой срез.
|
||||
//
|
||||
// q — пул или транзакция: внутри транзакции запрос обязан идти по её соединению, иначе при
|
||||
// маленьком пуле транзакция занимает соединение и ждёт второе.
|
||||
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))
|
||||
if len(messageIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
strs := make([]string, len(messageIDs))
|
||||
for i, id := range messageIDs {
|
||||
out[id] = []uuid.UUID{}
|
||||
strs[i] = id.String()
|
||||
}
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position`, strs)
|
||||
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())
|
||||
}
|
||||
|
||||
// AttachmentRef — строка attachments для reconciler: только то, что нужно для сверки с S3.
|
||||
type AttachmentRef struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
SizeBytes int64
|
||||
CreatedAt time.Time
|
||||
Referenced bool // есть ли хотя бы одно сообщение со ссылкой на файл
|
||||
}
|
||||
|
||||
// ListAttachmentRefs — keyset-страница по id. Страницы небольшие: у соединения
|
||||
// statement_timeout 3 с, один огромный SELECT на большой таблице под него не уложится.
|
||||
func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, 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.size_bytes, a.created_at,
|
||||
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)
|
||||
FROM attachments a
|
||||
WHERE a.id > $1
|
||||
ORDER BY a.id
|
||||
LIMIT $2`, after, 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.SizeBytes, &r.CreatedAt, &r.Referenced); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, mapWriteErr(rows.Err())
|
||||
}
|
||||
|
||||
// AttachmentKeyExists — повторная проверка перед удалением orphan: между листингом S3
|
||||
// и удалением объект мог получить строку (загрузка закончилась). Это страховка поверх grace.
|
||||
func (s *Store) AttachmentKeyExists(ctx context.Context, objectKey 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)`, objectKey).Scan(&ok)
|
||||
return ok, mapWriteErr(err)
|
||||
}
|
||||
|
||||
// DeleteUnreferencedAttachment удаляет строку, только если на неё нет ссылок из сообщений.
|
||||
// Условие NOT EXISTS в самом DELETE закрывает гонку «сообщение прикрепили, пока мы решали».
|
||||
// Возвращает true, если строка была удалена.
|
||||
func (s *Store) DeleteUnreferencedAttachment(ctx context.Context, id uuid.UUID) (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 NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`, id)
|
||||
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,33 @@
|
||||
-- Вложения lab4. Метаданные в PostgreSQL, байты в приватном S3-bucket (MinIO).
|
||||
-- Ключ объекта назначает сервер: originals/<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),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
object_key text COLLATE "C" NOT NULL,
|
||||
status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready')),
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT attachments_object_key_unique UNIQUE (object_key)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments (chat_id);
|
||||
|
||||
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,723 @@
|
||||
// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL.
|
||||
//
|
||||
// Источник истины — только эти таблицы. Память процесса после рестарта пуста,
|
||||
// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2):
|
||||
// текст сообщения не склеивается в SQL.
|
||||
//
|
||||
// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе
|
||||
// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка
|
||||
// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке).
|
||||
//
|
||||
// Вложения (lab4) — файл attachments.go: метаданные в PostgreSQL, байты в S3. Сообщение
|
||||
// ссылается на вложения через message_attachments; ссылки пишутся в той же транзакции,
|
||||
// что и само сообщение и ключ идемпотентности.
|
||||
//
|
||||
// Идемпотентность сообщения тоже живёт в 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"
|
||||
|
||||
"mtusi2026lab4/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 назначает сервер.
|
||||
// AttachmentIDs всегда непустой срез нулевой длины, если вложений нет (JSON даёт []).
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
AttachmentIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// 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(),
|
||||
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. иначе проверить членство в чате и вложения: каждое должно существовать, лежать
|
||||
// в ЭТОМ чате и быть ready (чужое/неизвестное — ErrNotFound, не ready — ErrNotReady);
|
||||
// 5. INSERT message + message_attachments + idempotency_keys в той же транзакции;
|
||||
// 6. COMMIT (advisory lock снимается вместе с транзакцией).
|
||||
//
|
||||
// attachmentIDs уже без дубликатов (проверяет HTTP-слой), порядок сохраняется.
|
||||
// Пустой текст допустим только вместе с вложениями — это тоже проверяет HTTP-слой.
|
||||
// Другой 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()
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
byMsg, err := attachmentIDsByMessage(ctx, tx, []uuid.UUID{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,
|
||||
AttachmentIDs: byMsg[msgID],
|
||||
CreatedAt: msgCreated,
|
||||
},
|
||||
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)
|
||||
}
|
||||
|
||||
attStrs := make([]string, len(attachmentIDs))
|
||||
for i, id := range attachmentIDs {
|
||||
attStrs[i] = id.String()
|
||||
}
|
||||
if len(attStrs) > 0 {
|
||||
// chat_id = $2 — вложение другого чата неотличимо от несуществующего (404, не 403).
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT status FROM attachments WHERE id = ANY($1::uuid[]) AND chat_id = $2`, attStrs, chatID)
|
||||
if err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
found, notReady := 0, false
|
||||
for rows.Next() {
|
||||
var status string
|
||||
if err := rows.Scan(&status); err != nil {
|
||||
rows.Close()
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
found++
|
||||
if status != "ready" {
|
||||
notReady = true
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
if found != len(attStrs) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if notReady {
|
||||
return nil, ErrNotReady
|
||||
}
|
||||
}
|
||||
|
||||
msg := &Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...),
|
||||
CreatedAt: nowUTC(),
|
||||
}
|
||||
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)
|
||||
}
|
||||
if len(attStrs) > 0 {
|
||||
// WITH ORDINALITY сохраняет порядок attachment_ids из запроса.
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
SELECT $1, u.id, (u.ord - 1)::smallint
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord)`, msg.ID, attStrs); err != nil {
|
||||
return nil, mapWriteErr(err)
|
||||
}
|
||||
}
|
||||
|
||||
// response_body заполняем каноническим Message JSON уже здесь, чтобы replay
|
||||
// не зависел от повторной сериализации в HTTP-слое с другим порядком полей.
|
||||
bodyJSON, err := json.Marshal(map[string]any{
|
||||
"id": msg.ID.String(),
|
||||
"chat_id": msg.ChatID.String(),
|
||||
"sender_id": msg.SenderID.String(),
|
||||
"text": msg.Text,
|
||||
"attachment_ids": attStrs,
|
||||
"created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"),
|
||||
})
|
||||
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
|
||||
})
|
||||
// Вложения страницы — одним запросом, а не по запросу на сообщение.
|
||||
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 nil, nil, err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].AttachmentIDs = byMsg[items[i].ID]
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
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