Реализовать 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
|
||||
}
|
||||
Reference in New Issue
Block a user