forked from mtusi2026/mtusi2026lab4
lab 4 na 4
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxAttachmentBytes = 10 << 20
|
||||
maxPixels = 40_000_000
|
||||
fullDecodePixels = 4_000_000 // полное декодирование только для небольших изображений
|
||||
)
|
||||
|
||||
func validFilename(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
if n < 1 || n > 255 || strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *api) acquireUploadSlot(ctx context.Context) (func(), bool) {
|
||||
t := time.NewTimer(5 * time.Second)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case a.uploadSem <- struct{}{}:
|
||||
return func() { <-a.uploadSem }, true
|
||||
case <-t.C:
|
||||
return nil, false
|
||||
case <-ctx.Done():
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID, ok := uuidParam(w, r, requestID, "chat_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if a.blobs == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, u.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
return
|
||||
}
|
||||
|
||||
q := r.URL.Query()
|
||||
filename := q.Get("filename")
|
||||
if !q.Has("filename") || !validFilename(filename) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid filename")
|
||||
return
|
||||
}
|
||||
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || (mt != "image/png" && mt != "image/jpeg") {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "only image/png and image/jpeg are accepted")
|
||||
return
|
||||
}
|
||||
if r.ContentLength > maxAttachmentBytes {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large")
|
||||
return
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp("", "upload-*")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
defer func() { tmp.Close(); os.Remove(tmp.Name()) }()
|
||||
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(io.MultiWriter(tmp, h), http.MaxBytesReader(w, r.Body, maxAttachmentBytes))
|
||||
if err != nil {
|
||||
var mbe *http.MaxBytesError
|
||||
if errors.As(err, &mbe) {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large")
|
||||
} else {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "upload interrupted")
|
||||
}
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "empty or invalid image")
|
||||
return
|
||||
}
|
||||
|
||||
release, ok := a.acquireUploadSlot(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "upload capacity reached, retry later")
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
|
||||
head := make([]byte, 512)
|
||||
hn, _ := tmp.ReadAt(head, 0)
|
||||
if http.DetectContentType(head[:hn]) != mt {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "content does not match declared type")
|
||||
return
|
||||
}
|
||||
cfg, format, err := image.DecodeConfig(io.NewSectionReader(tmp, 0, n))
|
||||
want := map[string]string{"image/png": "png", "image/jpeg": "jpeg"}[mt]
|
||||
if err != nil || format != want || cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "invalid image")
|
||||
return
|
||||
}
|
||||
pixels := int64(cfg.Width) * int64(cfg.Height)
|
||||
if pixels > maxPixels {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "image has too many pixels")
|
||||
return
|
||||
}
|
||||
if pixels <= fullDecodePixels {
|
||||
if _, _, err := image.Decode(io.NewSectionReader(tmp, 0, n)); err != nil {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "corrupted image")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
id := idgen.GenerateUUIDv4()
|
||||
key := "attachments/" + chatID + "/" + id
|
||||
|
||||
baseCtx := context.WithoutCancel(r.Context())
|
||||
putCtx, cancel := context.WithTimeout(baseCtx, 30*time.Second)
|
||||
err = a.blobs.Put(putCtx, key, io.NewSectionReader(tmp, 0, n), n, mt)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("s3 put failed: %v", err)
|
||||
delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second)
|
||||
_ = a.blobs.Delete(delCtx, key)
|
||||
delCancel()
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
dbCtx, dbCancel := context.WithTimeout(baseCtx, 10*time.Second)
|
||||
defer dbCancel()
|
||||
att, err := a.store.CreateAttachment(dbCtx, model.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: u.ID, Filename: filename, ContentType: mt,
|
||||
SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("attachment metadata insert failed, compensating: %v", err)
|
||||
if derr := a.blobs.Delete(dbCtx, key); derr != nil {
|
||||
log.Printf("compensation delete failed (reconciler will clean up) key=%s: %v", key, derr)
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, requestID, att)
|
||||
}
|
||||
|
||||
func (a *api) loadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) (model.Attachment, bool) {
|
||||
id, ok := uuidParam(w, r, requestID, "attachment_id")
|
||||
if !ok {
|
||||
return model.Attachment{}, false
|
||||
}
|
||||
att, err := a.store.GetAttachmentForUser(r.Context(), id, u.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrAttachmentNotFound) {
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "attachment not found")
|
||||
} else {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
}
|
||||
return model.Attachment{}, false
|
||||
}
|
||||
return att, true
|
||||
}
|
||||
|
||||
func (a *api) handleGetAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
att, ok := a.loadAttachment(w, r, u, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, att)
|
||||
}
|
||||
|
||||
func (a *api) handleDownloadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
if q := r.URL.Query(); q.Has("variant") && q.Get("variant") != "original" {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "unknown variant")
|
||||
return
|
||||
}
|
||||
att, ok := a.loadAttachment(w, r, u, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if a.blobs == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
t := time.AfterFunc(8*time.Second, cancel)
|
||||
body, err := a.blobs.Get(ctx, att.ObjectKey)
|
||||
t.Stop()
|
||||
if err != nil {
|
||||
if errors.Is(err, blobstore.ErrNotFound) {
|
||||
log.Printf("INCONSISTENCY: metadata without object id=%s key=%s", att.ID, att.ObjectKey)
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
} else {
|
||||
log.Printf("s3 get failed: %v", err)
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
}
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", att.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10))
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.Copy(w, body)
|
||||
}
|
||||
@@ -3,18 +3,45 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
)
|
||||
|
||||
func handleHealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, newRequestID(), map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, draining *atomic.Bool) http.HandlerFunc {
|
||||
type blobProbe struct {
|
||||
mu sync.Mutex
|
||||
at time.Time
|
||||
err error
|
||||
st blobstore.Store
|
||||
}
|
||||
|
||||
func (p *blobProbe) check(ctx context.Context) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if time.Since(p.at) < time.Second {
|
||||
return p.err
|
||||
}
|
||||
cctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
p.err = p.st.Ping(cctx)
|
||||
p.at = time.Now()
|
||||
return p.err
|
||||
}
|
||||
|
||||
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, blobs blobstore.Store, draining *atomic.Bool) http.HandlerFunc {
|
||||
var probe *blobProbe
|
||||
if blobs != nil {
|
||||
probe = &blobProbe{st: blobs}
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
if draining.Load() {
|
||||
@@ -34,6 +61,12 @@ func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, draining *atomic.B
|
||||
return
|
||||
}
|
||||
}
|
||||
if probe != nil {
|
||||
if err := probe.check(ctx); err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,12 +15,14 @@ import (
|
||||
type errorCode string
|
||||
|
||||
const (
|
||||
codeInvalidRequest errorCode = "invalid_request"
|
||||
codeUnauthorized errorCode = "unauthorized"
|
||||
codeNotFound errorCode = "not_found"
|
||||
codeConflict errorCode = "conflict"
|
||||
codeUnavailable errorCode = "unavailable"
|
||||
codeInternal errorCode = "internal_error"
|
||||
codeInvalidRequest errorCode = "invalid_request"
|
||||
codeUnauthorized errorCode = "unauthorized"
|
||||
codeNotFound errorCode = "not_found"
|
||||
codeConflict errorCode = "conflict"
|
||||
codeUnavailable errorCode = "unavailable"
|
||||
codeInternal errorCode = "internal_error"
|
||||
codeTooLarge errorCode = "payload_too_large"
|
||||
codeUnsupportedMedia errorCode = "unsupported_media_type"
|
||||
)
|
||||
|
||||
func newRequestID() string {
|
||||
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
@@ -12,7 +14,7 @@ import (
|
||||
var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID, ok := chatIDParam(w, r, requestID)
|
||||
chatID, ok := uuidParam(w, r, requestID, "chat_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -28,11 +30,27 @@ func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u mode
|
||||
return
|
||||
}
|
||||
|
||||
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text)
|
||||
ids := make([]string, 0, len(req.AttachmentIDs))
|
||||
seen := map[string]bool{}
|
||||
for _, id := range req.AttachmentIDs {
|
||||
id = strings.ToLower(id)
|
||||
if !idgen.IsValidUUID(id) || seen[id] {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid attachment_ids")
|
||||
return
|
||||
}
|
||||
seen[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) > 10 || !store.ValidMessageBody(req.Text, len(ids) > 0) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid text or attachment_ids")
|
||||
return
|
||||
}
|
||||
|
||||
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text, ids)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrChatNotFound):
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
case errors.Is(err, store.ErrChatNotFound), errors.Is(err, store.ErrAttachmentNotFound):
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat or attachment not found")
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
writeError(w, http.StatusConflict, requestID, codeConflict, "Idempotency-Key was used with a different request body")
|
||||
case errors.Is(err, store.ErrValidation):
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
@@ -17,6 +18,8 @@ type Options struct {
|
||||
InstanceID string
|
||||
Redis *redis.Client
|
||||
Draining *atomic.Bool
|
||||
Blobs blobstore.Store
|
||||
MaxUploads int
|
||||
}
|
||||
|
||||
func NewRouter(s *store.Store, pool *pgxpool.Pool, sessionStores ...sessionstore.Store) http.Handler {
|
||||
@@ -45,10 +48,16 @@ func NewRouterWithCache(
|
||||
o.Draining = new(atomic.Bool)
|
||||
}
|
||||
|
||||
if o.MaxUploads <= 0 {
|
||||
o.MaxUploads = 4
|
||||
}
|
||||
|
||||
a := &api{
|
||||
store: s,
|
||||
sessionStore: sessionStore,
|
||||
chatCache: chatCache,
|
||||
blobs: o.Blobs,
|
||||
uploadSem: make(chan struct{}, o.MaxUploads),
|
||||
}
|
||||
|
||||
apiMux := http.NewServeMux()
|
||||
@@ -60,6 +69,9 @@ func NewRouterWithCache(
|
||||
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage))
|
||||
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages))
|
||||
apiMux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
|
||||
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", a.authMiddleware(a.handleUploadAttachment))
|
||||
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}", a.authMiddleware(a.handleGetAttachment))
|
||||
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", a.authMiddleware(a.handleDownloadAttachment))
|
||||
apiMux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.authMiddleware(
|
||||
func(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
a.handleDeleteSession(w, r)
|
||||
@@ -67,7 +79,7 @@ func NewRouterWithCache(
|
||||
|
||||
root := http.NewServeMux()
|
||||
root.HandleFunc("GET /health/live", handleHealthLive)
|
||||
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Draining))
|
||||
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
|
||||
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
|
||||
|
||||
var h http.Handler = root
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"mtusi2026/internal/auth"
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
@@ -22,6 +23,8 @@ type api struct {
|
||||
sessionStore sessionstore.Store
|
||||
chatCache *cache.Cache
|
||||
chatFlight singleflight.Group
|
||||
blobs blobstore.Store
|
||||
uploadSem chan struct{}
|
||||
}
|
||||
|
||||
func (a *api) authMiddleware(next func(w http.ResponseWriter, r *http.Request, u model.User, requestID string)) http.HandlerFunc {
|
||||
|
||||
@@ -43,3 +43,12 @@ func chatIDParam(w http.ResponseWriter, r *http.Request, requestID string) (stri
|
||||
}
|
||||
return strings.ToLower(id), true
|
||||
}
|
||||
|
||||
func uuidParam(w http.ResponseWriter, r *http.Request, requestID, name string) (string, bool) {
|
||||
id := r.PathValue(name)
|
||||
if !idgen.IsValidUUID(id) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid "+name)
|
||||
return "", false
|
||||
}
|
||||
return strings.ToLower(id), true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user