Implement lab4 S3 attachments and resilience

This commit is contained in:
Ilia Sokolov
2026-10-31 18:30:23 +03:00
parent ec540a1a72
commit 1493ecd990
29 changed files with 2906 additions and 25 deletions
+619
View File
@@ -0,0 +1,619 @@
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"mime"
"net/http"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode"
"unicode/utf8"
)
type API struct {
store *Store
hasher *Hasher
ttlSecs int
reqLimit time.Duration
blobs *BlobStore
maxUpload int
maxPixels int
// instanceID — стабильный на всё время жизни процесса псевдоним реплики (X-Instance-Id).
instanceID string
// draining выставляется по SIGTERM: /health/ready отвечает 503, новые запросы уходят на другие реплики.
draining atomic.Bool
}
// ---- аутентификация ----
// actor: «кто вы». Только действующая Bearer-сессия из PostgreSQL; ответ на любой сбой одинаков.
func (a *API) actor(r *http.Request) (User, string, *apiError) {
token, ok := bearerToken(r)
if !ok {
return User{}, "", unauthorized(bearerChallenge, "Требуется Authorization: Bearer <token>")
}
user, err := a.store.sessionUser(r.Context(), hashToken(token))
if errors.Is(err, errNotFound) {
return User{}, "", unauthorized(bearerChallenge, "Недействительная сессия")
}
if err != nil {
return User{}, "", dbFail(err)
}
return user, token, nil
}
func (a *API) createSession(r *http.Request) (int, any, *apiError) {
denied := unauthorized(basicChallenge, "Неверные учётные данные")
username, password, ok := parseBasic(r)
if !ok {
return 0, nil, denied
}
user, hash, err := a.store.userWithHash(r.Context(), username)
found := err == nil
if err != nil && !errors.Is(err, errNotFound) {
return 0, nil, dbFail(err)
}
if !found {
hash = a.hasher.dummy
}
match, herr := a.hasher.verify(r.Context(), password, hash)
if herr != nil && !errors.Is(herr, context.Canceled) && !errors.Is(herr, context.DeadlineExceeded) {
match = false // повреждённый хеш = отказ, не 500
} else if herr != nil {
return 0, nil, unavailable()
}
if !found || !match {
return 0, nil, denied
}
token, tokenHash := newToken()
expires, err := a.store.createSession(r.Context(), tokenHash, user.ID, a.ttlSecs)
if err != nil {
return 0, nil, dbFail(err)
}
return http.StatusCreated, map[string]any{
"token": token, "token_type": "Bearer", "expires_at": formatTime(expires), "user": user,
}, nil
}
func (a *API) revokeSession(r *http.Request) (int, any, *apiError) {
_, token, err := a.actor(r)
if err != nil {
return 0, nil, err
}
if rerr := a.store.revokeSession(r.Context(), hashToken(token)); rerr != nil {
return 0, nil, dbFail(rerr)
}
return http.StatusNoContent, nil, nil
}
// ---- пользователи ----
func (a *API) createUser(r *http.Request) (int, any, *apiError) {
body, err := readJSON(r)
if err != nil {
return 0, nil, err
}
if err := exactFields(body, "username", "display_name", "password"); err != nil {
return 0, nil, err
}
username, ok := body["username"].(string)
if !ok || !usernamePattern.MatchString(username) {
return 0, nil, invalid("Некорректный username")
}
displayName, err := requiredString(body["display_name"], 100, "display_name")
if err != nil {
return 0, nil, err
}
password, ok := body["password"].(string)
if n := utf8.RuneCountInString(password); !ok || !utf8.ValidString(password) || n < 12 || n > 128 {
return 0, nil, invalid("Некорректный password")
}
hash, herr := a.hasher.hash(r.Context(), password)
if herr != nil {
return 0, nil, unavailable()
}
user, serr := a.store.createUser(r.Context(), User{ID: newUUID(), Username: username, DisplayName: displayName}, hash)
if errors.Is(serr, errConflict) {
return 0, nil, fail(http.StatusConflict, "conflict", "Username уже занят")
}
if serr != nil {
return 0, nil, dbFail(serr)
}
return http.StatusCreated, user, nil
}
func (a *API) currentUser(r *http.Request) (int, any, *apiError) {
user, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
return http.StatusOK, user, nil
}
// ---- чаты ----
func (a *API) createChat(r *http.Request) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
body, err := readJSON(r)
if err != nil {
return 0, nil, err
}
if err := exactFields(body, "title", "member_ids"); err != nil {
return 0, nil, err
}
title, err := requiredString(body["title"], 100, "title")
if err != nil {
return 0, nil, err
}
rawMembers, ok := body["member_ids"].([]any)
if !ok || len(rawMembers) < 1 || len(rawMembers) > 100 {
return 0, nil, invalid("Некорректные участники")
}
members, seen := make([]string, 0, len(rawMembers)), map[string]bool{}
for _, raw := range rawMembers {
member, typeOK := raw.(string)
id, idOK := validUUID(member)
if !typeOK || !idOK || seen[id] {
return 0, nil, invalid("Некорректные участники")
}
seen[id] = true
members = append(members, id)
}
if !seen[actor.ID] {
return 0, nil, invalid("Создатель должен быть участником")
}
sort.Strings(members) // детерминированный порядок: одинаковый в POST и GET
chat, serr := a.store.createChat(r.Context(), Chat{ID: newUUID(), Title: title, MemberIDs: members}, actor.ID)
if errors.Is(serr, errInvalidMembers) {
return 0, nil, invalid("Некорректные участники")
}
if serr != nil {
return 0, nil, dbFail(serr)
}
return http.StatusCreated, chat, nil
}
func (a *API) listChats(r *http.Request) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
limit, rawCursor, err := parsePage(r)
if err != nil {
return 0, nil, err
}
var after *time.Time
var afterID string
if rawCursor != "" {
t, id, cerr := decodeCursor(rawCursor, "chats", actor.ID)
if cerr != nil {
return 0, nil, cerr
}
after, afterID = &t, id
}
items, next, serr := a.store.listChats(r.Context(), actor.ID, limit, after, afterID)
if serr != nil {
return 0, nil, dbFail(serr)
}
return http.StatusOK, pageBody(items, next), nil
}
func pageBody(items any, next string) map[string]any {
var cursor any
if next != "" {
cursor = next
}
return map[string]any{"items": items, "next_cursor": cursor}
}
// chatAccess: сначала аутентификация (вызывается до этого), затем доступ к конкретному чату.
// Чужой и несуществующий чат неразличимы: оба дают 404.
func (a *API) chatAccess(r *http.Request, actorID, rawID string) (string, *apiError) {
id, ok := validUUID(rawID)
if !ok {
return "", invalid("Некорректный идентификатор")
}
member, err := a.store.isMember(r.Context(), actorID, id)
if err != nil {
return "", dbFail(err)
}
if !member {
return "", notFound()
}
return id, nil
}
func (a *API) getChat(r *http.Request, rawID string) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
id, ok := validUUID(rawID)
if !ok {
return 0, nil, invalid("Некорректный идентификатор")
}
chat, serr := a.store.getChat(r.Context(), actor.ID, id)
if errors.Is(serr, errNotFound) {
return 0, nil, notFound()
}
if serr != nil {
return 0, nil, dbFail(serr)
}
return http.StatusOK, chat, nil
}
// ---- сообщения ----
func (a *API) createMessage(r *http.Request, rawID string) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
chatID, err := a.chatAccess(r, actor.ID, rawID)
if err != nil {
return 0, nil, err
}
keys := r.Header.Values("Idempotency-Key")
if len(keys) != 1 || !idempotencyKeyPattern.MatchString(keys[0]) {
return 0, nil, invalid("Требуется корректный заголовок Idempotency-Key")
}
key := keys[0]
body, err := readJSON(r)
if err != nil {
return 0, nil, err
}
// sender_id и прочие поля не принимаются (400). Отправитель берётся только из сессии.
for name := range body {
if name != "text" && name != "attachment_ids" {
return 0, nil, invalid("Неожиданные поля")
}
}
attachmentIDs := []string{}
if raw, present := body["attachment_ids"]; present {
list, ok := raw.([]any)
if !ok || len(list) > 10 {
return 0, nil, invalid("Некорректные attachment_ids")
}
seen := map[string]bool{}
for _, item := range list {
str, typeOK := item.(string)
id, idOK := validUUID(str)
if !typeOK || !idOK || seen[id] {
return 0, nil, invalid("Некорректные attachment_ids")
}
seen[id] = true
attachmentIDs = append(attachmentIDs, id)
}
}
var text string
if rawText, ok := body["text"].(string); !ok {
return 0, nil, invalid("Некорректное поле text")
} else if len(attachmentIDs) > 0 && rawText == "" {
text = "" // сообщение только из вложений
} else {
var terr *apiError
if text, terr = requiredString(rawText, 4000, "text"); terr != nil {
return 0, nil, terr
}
}
// Канонический вид тела: порядок ключей JSON и отсутствие attachment_ids == [] неразличимы.
hasher := sha256.New()
hasher.Write([]byte(text))
for _, id := range attachmentIDs {
hasher.Write([]byte{0})
hasher.Write([]byte(id))
}
sum := hasher.Sum(nil)
path := "/api/v1/chats/" + chatID + "/messages"
message, _, serr := a.store.createMessageIdempotent(r.Context(),
Message{ID: newUUID(), ChatID: chatID, SenderID: actor.ID, Text: text, AttachmentIDs: attachmentIDs}, key, path, sum)
if errors.Is(serr, errNotFound) {
return 0, nil, notFound()
}
if errors.Is(serr, errConflict) {
return 0, nil, fail(http.StatusConflict, "conflict", "Idempotency-Key уже использован с другим сообщением")
}
if serr != nil {
return 0, nil, dbFail(serr)
}
return http.StatusCreated, message, nil
}
func (a *API) listMessages(r *http.Request, rawID string) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
chatID, err := a.chatAccess(r, actor.ID, rawID)
if err != nil {
return 0, nil, err
}
limit, rawCursor, err := parsePage(r)
if err != nil {
return 0, nil, err
}
var after *time.Time
var afterID string
if rawCursor != "" {
t, id, cerr := decodeCursor(rawCursor, "messages", chatID)
if cerr != nil {
return 0, nil, cerr
}
after, afterID = &t, id
}
items, next, serr := a.store.listMessages(r.Context(), chatID, limit, after, afterID)
if serr != nil {
return 0, nil, dbFail(serr)
}
return http.StatusOK, pageBody(items, next), nil
}
// ---- вложения ----
// binaryBody — ответ с байтами (не JSON); пишется в ServeHTTP.
type binaryBody struct {
contentType string
size int64
body io.ReadCloser
}
// detectImage определяет формат по СОДЕРЖИМОМУ (заголовок Content-Type клиента лишь сверяется) и читает размеры
// без декодирования пикселей: лимит 40 млн px применяется до любой тяжёлой обработки.
func detectImage(data []byte) (mime string, pixels int64, ok bool) {
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width < 1 || cfg.Height < 1 {
return "", 0, false
}
switch format {
case "png":
mime = "image/png"
case "jpeg":
mime = "image/jpeg"
default:
return "", 0, false
}
return mime, int64(cfg.Width) * int64(cfg.Height), true
}
func validFilename(name string) bool {
n := utf8.RuneCountInString(name)
if !utf8.ValidString(name) || n < 1 || n > 255 || strings.TrimSpace(name) == "" {
return false
}
for _, c := range name {
if c == '/' || c == '\\' || c == 0 || unicode.IsControl(c) {
return false
}
}
return true
}
func (a *API) uploadAttachment(r *http.Request, rawID string) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
chatID, err := a.chatAccess(r, actor.ID, rawID)
if err != nil {
return 0, nil, err
}
query := r.URL.Query()
names := query["filename"]
if len(names) != 1 || !validFilename(names[0]) {
return 0, nil, invalid("Некорректный filename")
}
mediaType, _, merr := mime.ParseMediaType(r.Header.Get("Content-Type"))
if merr != nil || (mediaType != "image/png" && mediaType != "image/jpeg") {
return 0, nil, fail(http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен image/png или image/jpeg")
}
tooLarge := fail(http.StatusRequestEntityTooLarge, "payload_too_large", "Файл больше лимита")
if r.ContentLength > int64(a.maxUpload) {
return 0, nil, tooLarge
}
// Лимит применяется до чтения: больше maxUpload+1 байт из сокета не берётся.
data, rerr := io.ReadAll(io.LimitReader(r.Body, int64(a.maxUpload)+1))
if rerr != nil {
return 0, nil, invalid("Не удалось прочитать тело запроса")
}
if len(data) > a.maxUpload {
return 0, nil, tooLarge
}
if len(data) == 0 {
return 0, nil, invalid("Пустое тело")
}
detected, pixels, ok := detectImage(data)
if !ok || detected != mediaType {
return 0, nil, fail(http.StatusUnsupportedMediaType, "unsupported_media_type", "Содержимое не является корректным PNG/JPEG")
}
if pixels > int64(a.maxPixels) {
return 0, nil, tooLarge
}
sum := sha256.Sum256(data)
id := newUUID()
att := Attachment{
ID: id, ChatID: chatID, OwnerID: actor.ID, Filename: names[0], ContentType: detected,
SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]),
objectKey: "attachments/" + chatID + "/" + id, // ключ назначает сервер, filename в нём не участвует
}
// Порядок: сначала байты в S3, затем метаданные. 201 — только после обоих; при сбое БД объект удаляется.
if perr := a.blobs.put(r.Context(), att.objectKey, data, detected); perr != nil {
log.Printf("s3 put failed")
return 0, nil, unavailable()
}
created, serr := a.store.createAttachment(r.Context(), att)
if serr != nil {
a.blobs.remove(context.Background(), att.objectKey)
return 0, nil, dbFail(serr)
}
return http.StatusCreated, created, nil
}
func (a *API) getAttachment(r *http.Request, rawID string) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
id, ok := validUUID(rawID)
if !ok {
return 0, nil, invalid("Некорректный идентификатор")
}
att, serr := a.store.getAttachment(r.Context(), actor.ID, id)
if errors.Is(serr, errNotFound) {
return 0, nil, notFound()
}
if serr != nil {
return 0, nil, dbFail(serr)
}
return http.StatusOK, att, nil
}
func (a *API) downloadAttachment(r *http.Request, rawID string) (int, any, *apiError) {
actor, _, err := a.actor(r)
if err != nil {
return 0, nil, err
}
id, ok := validUUID(rawID)
if !ok {
return 0, nil, invalid("Некорректный идентификатор")
}
if v := r.URL.Query()["variant"]; len(v) > 1 || (len(v) == 1 && v[0] != "original") {
return 0, nil, invalid("Некорректный variant")
}
att, serr := a.store.getAttachment(r.Context(), actor.ID, id)
if errors.Is(serr, errNotFound) {
return 0, nil, notFound()
}
if serr != nil {
return 0, nil, dbFail(serr)
}
body, gerr := a.blobs.get(r.Context(), att.objectKey)
if gerr != nil {
log.Printf("s3 get failed")
return 0, nil, unavailable()
}
return http.StatusOK, &binaryBody{contentType: att.ContentType, size: att.SizeBytes, body: body}, nil
}
// ---- health ----
func (a *API) ready(r *http.Request) (int, any, *apiError) {
if a.draining.Load() {
return 0, nil, unavailable()
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := a.store.ready(ctx); err != nil {
log.Printf("readiness: dependency check failed")
return 0, nil, unavailable()
}
return http.StatusOK, map[string]string{"status": "ok"}, nil
}
// ---- маршрутизация ----
func (a *API) dispatch(r *http.Request) (int, any, *apiError) {
path := r.URL.Path
switch {
case r.Method == http.MethodGet && path == "/health/live":
return http.StatusOK, map[string]string{"status": "ok"}, nil
case r.Method == http.MethodGet && path == "/health/ready":
return a.ready(r)
case r.Method == http.MethodPost && path == "/api/v1/users":
return a.createUser(r)
case r.Method == http.MethodGet && path == "/api/v1/users/me":
return a.currentUser(r)
case r.Method == http.MethodPost && path == "/api/v1/auth/sessions":
return a.createSession(r) // единственное место, где принимается Basic
case r.Method == http.MethodDelete && path == "/api/v1/auth/sessions/current":
return a.revokeSession(r)
case r.Method == http.MethodPost && path == "/api/v1/chats":
return a.createChat(r)
case r.Method == http.MethodGet && path == "/api/v1/chats":
return a.listChats(r)
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if r.Method == http.MethodPost && len(parts) == 5 && strings.Join(parts[:3], "/") == "api/v1/chats" && parts[4] == "attachments" {
return a.uploadAttachment(r, parts[3])
}
if r.Method == http.MethodGet && len(parts) == 4 && strings.Join(parts[:3], "/") == "api/v1/attachments" {
return a.getAttachment(r, parts[3])
}
if r.Method == http.MethodGet && len(parts) == 5 && strings.Join(parts[:3], "/") == "api/v1/attachments" && parts[4] == "content" {
return a.downloadAttachment(r, parts[3])
}
if len(parts) == 4 && strings.Join(parts[:3], "/") == "api/v1/chats" && r.Method == http.MethodGet {
return a.getChat(r, parts[3])
}
if len(parts) == 5 && strings.Join(parts[:3], "/") == "api/v1/chats" && parts[4] == "messages" {
if r.Method == http.MethodPost {
return a.createMessage(r, parts[3])
}
if r.Method == http.MethodGet {
return a.listMessages(r, parts[3])
}
}
return 0, nil, notFound()
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) }
func (a *API) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
id := newUUID()
rw.Header().Set("X-Instance-Id", a.instanceID)
w := &statusWriter{ResponseWriter: rw, status: 200}
started := time.Now()
ctx, cancel := context.WithTimeout(r.Context(), a.reqLimit)
defer cancel()
r = r.WithContext(ctx)
defer func() {
if rec := recover(); rec != nil {
log.Printf("panic request_id=%s: %v\n%s", id, rec, debug.Stack())
writeError(w, id, fail(http.StatusInternalServerError, "internal_error", "Внутренняя ошибка"))
}
// В лог не попадают заголовки, query-строка, тела запросов и токены.
log.Printf("%s %s -> %d request_id=%s %s", r.Method, r.URL.Path, w.status, id, time.Since(started).Round(time.Millisecond))
}()
status, body, err := a.dispatch(r)
if err != nil {
writeError(w, id, err)
return
}
if bin, ok := body.(*binaryBody); ok {
defer bin.body.Close()
w.Header().Set("X-Request-Id", id)
w.Header().Set("Content-Type", bin.contentType)
w.Header().Set("Content-Length", strconv.FormatInt(bin.size, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Disposition", "attachment")
w.WriteHeader(status)
_, _ = io.Copy(w, bin.body)
return
}
if status == http.StatusNoContent {
w.Header().Set("X-Request-Id", id)
w.WriteHeader(status)
return
}
writeJSON(w, id, status, body)
}