diff --git a/internal/app/app.go b/internal/app/app.go index e01cb8b..ec2e889 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -97,16 +97,19 @@ func Run() error { userService := service.NewUserService(queries) chatService := service.NewChatService(pool, queries) messageService := service.NewMessageService(pool, queries) + attachmentService := service.NewAttachmentService(queries, s3Client, cfg.S3.MaxUploadBytes, cfg.S3.MaxImagePixels) router := NewRouter( log, cfg.Server.InstanceID, cfg.Server.MaxInflightRequests, + cfg.S3.MaxUploadBytes, pool, authService, userService, chatService, messageService, + attachmentService, ) server := &http.Server{ diff --git a/internal/app/router.go b/internal/app/router.go index 85a87f2..8170224 100644 --- a/internal/app/router.go +++ b/internal/app/router.go @@ -16,11 +16,13 @@ func NewRouter( log *slog.Logger, instanceID string, maxInflightRequests int, + maxUploadBytes int, db handler.Pinger, authService *service.AuthService, userService *service.UserService, chatService *service.ChatService, messageService *service.MessageService, + attachmentService *service.AttachmentService, ) http.Handler { router := chi.NewRouter() @@ -29,6 +31,7 @@ func NewRouter( userHandler := handler.NewUserHandler(userService) chatHandler := handler.NewChatHandler(chatService) messageHandler := handler.NewMessageHandler(messageService) + attachmentHandler := handler.NewAttachmentHandler(attachmentService, maxUploadBytes) router.Use(middleware.InstanceID(instanceID)) router.Use(middleware.RequestTimeout(5 * time.Second)) @@ -55,6 +58,10 @@ func NewRouter( r.Post("/api/v1/chats/{chat_id}/messages", messageHandler.Create) r.Get("/api/v1/chats/{chat_id}/messages", messageHandler.List) + + r.Post("/api/v1/chats/{chat_id}/attachments", attachmentHandler.Upload) + r.Get("/api/v1/attachments/{attachment_id}", attachmentHandler.Get) + r.Get("/api/v1/attachments/{attachment_id}/content", attachmentHandler.GetContent) }) router.Handle("/swagger/*", http.StripPrefix("/swagger/", http.FileServer(http.Dir("web/swagger")))) diff --git a/internal/dto/attachment.go b/internal/dto/attachment.go new file mode 100644 index 0000000..b635f91 --- /dev/null +++ b/internal/dto/attachment.go @@ -0,0 +1,71 @@ +package dto + +import ( + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/model" +) + +type CreateAttachmentRequest struct { + Filename string +} + +type VariantResponse struct { + Name string `json:"name"` + ContentType string `json:"content_type"` + SizeBytes int `json:"size_bytes"` + Width int `json:"width"` + Height int `json:"height"` + Sha256 string `json:"sha256"` +} + +type AttachmentResponse struct { + ID uuid.UUID `json:"id"` + ChatID uuid.UUID `json:"chat_id"` + OwnerID uuid.UUID `json:"owner_id"` + Filename string `json:"filename"` + ContentType string `json:"content_type"` + SizeBytes int `json:"size_bytes"` + Sha256 string `json:"sha256"` + Status string `json:"status"` + Variants []VariantResponse `json:"variants"` + ErrorCode *string `json:"error_code"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func (r CreateAttachmentRequest) Validate() bool { + if n := utf8.RuneCountInString(r.Filename); n < 1 || n > 255 { + return false + } + + for _, ch := range r.Filename { + if ch == '/' || ch == '\\' || ch == 0 || unicode.IsControl(ch) { + return false + } + } + + return true +} + +func ToAttachmentResponse(a model.Attachment) AttachmentResponse { + variants := make([]VariantResponse, 0) + return AttachmentResponse{ + ID: a.ID, + ChatID: a.ChatID, + OwnerID: a.OwnerID, + Filename: a.Filename, + ContentType: string(a.ContentType), + SizeBytes: a.SizeBytes, + Sha256: a.Sha256, + Status: string(a.Status), + Variants: variants, + ErrorCode: a.ErrorCode, + CreatedAt: a.CreatedAt, + UpdatedAt: a.UpdatedAt, + } +} diff --git a/internal/handler/attachment.go b/internal/handler/attachment.go new file mode 100644 index 0000000..6c29dda --- /dev/null +++ b/internal/handler/attachment.go @@ -0,0 +1,122 @@ +package handler + +import ( + "errors" + "io" + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" + "mtusi2026-messenger/internal/middleware" + "mtusi2026-messenger/internal/service" +) + +type AttachmentHandler struct { + service *service.AttachmentService + maxBytes int +} + +func NewAttachmentHandler(service *service.AttachmentService, maxBytes int) *AttachmentHandler { + return &AttachmentHandler{ + service: service, + maxBytes: maxBytes, + } +} + +func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid chat_id", requestID) + return + } + + req := dto.CreateAttachmentRequest{ + Filename: r.URL.Query().Get("filename"), + } + if !req.Validate() { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid filename", requestID) + return + } + + contentType := r.Header.Get("Content-Type") + r.Body = http.MaxBytesReader(w, r.Body, int64(h.maxBytes)) + + body, err := io.ReadAll(r.Body) + if err != nil { + var maxBytesErr *http.MaxBytesError + if errors.As(err, &maxBytesErr) { + httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodeInvalidRequest, "file too large", requestID) + return + } + + httpx.WriteError(w, http.StatusInternalServerError, dto.ErrorCodeInternalError, "read error", requestID) + return + } + + att, err := h.service.Upload(r.Context(), userID, chatID, req.Filename, body, contentType) + switch { + case errors.Is(err, service.ErrInvalidSize): + httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodeInvalidRequest, "file too large", requestID) + case errors.Is(err, service.ErrInvalidImage): + httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeInvalidRequest, "invalid image", requestID) + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.ToAttachmentResponse(att)) +} + +func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id")) + if err != nil { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID) + return + } + + att, err := h.service.Get(r.Context(), userID, attachmentID) + switch { + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + httpx.WriteJSON(w, http.StatusOK, dto.ToAttachmentResponse(att)) +} + +func (h *AttachmentHandler) GetContent(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + attachmentID, err := uuid.Parse(chi.URLParam(r, "attachment_id")) + if err != nil { + httpx.WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid attachment_id", requestID) + return + } + + data, contentType, err := h.service.GetContent(r.Context(), userID, attachmentID) + switch { + case errors.Is(err, service.ErrAttachmentNotFound): + httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) + case err != nil: + httpx.WriteInternalError(w, requestID, err) + return + } + + w.Header().Set("Content-Type", string(contentType)) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(data) +} diff --git a/internal/model/attachment.go b/internal/model/attachment.go new file mode 100644 index 0000000..c3c76ea --- /dev/null +++ b/internal/model/attachment.go @@ -0,0 +1,34 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type ContentType string + +const ( + ContentTypePNG ContentType = "image/png" + ContentTypeJPEG ContentType = "image/jpeg" +) + +type AttachmentStatus string + +const ( + AttachmentStatusReady AttachmentStatus = "ready" +) + +type Attachment struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + Filename string + ContentType ContentType + SizeBytes int + Sha256 string + Status AttachmentStatus + ErrorCode *string + CreatedAt time.Time + UpdatedAt time.Time +} diff --git a/internal/service/attachment.go b/internal/service/attachment.go new file mode 100644 index 0000000..298ca38 --- /dev/null +++ b/internal/service/attachment.go @@ -0,0 +1,217 @@ +package service + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "image" + "io" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/db" + "mtusi2026-messenger/internal/model" + "mtusi2026-messenger/internal/postgres" + s3store "mtusi2026-messenger/internal/s3" +) + +var ( + ErrAttachmentNotFound = errors.New("attachment not found") + ErrInvalidImage = errors.New("invalid image") + ErrInvalidSize = errors.New("invalid size") +) + +type attachmentQueries interface { + CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) + GetAttachmentByID(ctx context.Context, id uuid.UUID) (db.Attachment, error) + IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error) +} + +type AttachmentService struct { + q attachmentQueries + s3 *s3store.Client + maxBytes int + maxPixels int +} + +func NewAttachmentService( + q attachmentQueries, + s3 *s3store.Client, + maxBytes, maxPixels int, +) *AttachmentService { + return &AttachmentService{ + q: q, + s3: s3, + maxBytes: maxBytes, + maxPixels: maxPixels, + } +} + +func (s *AttachmentService) Upload( + ctx context.Context, + userID, chatID uuid.UUID, + filename string, + body []byte, + contentType string, +) (model.Attachment, error) { + if len(body) > s.maxBytes { + return model.Attachment{}, ErrInvalidSize + } + + if err := s.ensureMember(ctx, userID, chatID); err != nil { + return model.Attachment{}, err + } + + detectedType, err := s.checkImage(body, contentType) + if err != nil { + return model.Attachment{}, err + } + + id, err := uuid.NewV7() + if err != nil { + return model.Attachment{}, err + } + + sum := sha256.Sum256(body) + hash := hex.EncodeToString(sum[:]) + + key := "chats/" + chatID.String() + "/attachments/" + id.String() + + if err := s.s3.Put(ctx, key, bytes.NewReader(body), int64(len(body)), string(detectedType)); err != nil { + return model.Attachment{}, err + } + + row, err := s.q.CreateAttachment(ctx, db.CreateAttachmentParams{ + ID: id, + ChatID: chatID, + OwnerID: userID, + S3Key: key, + Filename: filename, + ContentType: db.AttachmentContentType(detectedType), + SizeBytes: len(body), + Sha256: hash, + Status: db.AttachmentStatusReady, + ErrorCode: "", + }) + if err != nil { + return model.Attachment{}, err + } + + return model.Attachment{ + ID: row.ID, + ChatID: row.ChatID, + OwnerID: row.OwnerID, + Filename: row.Filename, + ContentType: model.ContentType(row.ContentType), + SizeBytes: row.SizeBytes, + Sha256: row.Sha256, + Status: model.AttachmentStatus(row.Status), + ErrorCode: row.ErrorCode, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + }, nil +} + +func (s *AttachmentService) Get( + ctx context.Context, + userID, attachmentID uuid.UUID, +) (model.Attachment, error) { + row, err := s.q.GetAttachmentByID(ctx, attachmentID) + if postgres.IsNotFound(err) { + return model.Attachment{}, ErrAttachmentNotFound + } + if err != nil { + return model.Attachment{}, err + } + + if err := s.ensureMember(ctx, userID, row.ChatID); err != nil { + return model.Attachment{}, err + } + + return model.Attachment{ + ID: row.ID, + ChatID: row.ChatID, + OwnerID: row.OwnerID, + Filename: row.Filename, + ContentType: model.ContentType(row.ContentType), + SizeBytes: row.SizeBytes, + Sha256: row.Sha256, + Status: model.AttachmentStatus(row.Status), + ErrorCode: row.ErrorCode, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + }, nil +} + +func (s *AttachmentService) GetContent( + ctx context.Context, + userID, attachmentID uuid.UUID, +) ([]byte, model.ContentType, error) { + row, err := s.q.GetAttachmentByID(ctx, attachmentID) + if postgres.IsNotFound(err) { + return nil, "", ErrAttachmentNotFound + } + if err != nil { + return nil, "", err + } + + if err := s.ensureMember(ctx, userID, row.ChatID); err != nil { + return nil, "", err + } + + out, err := s.s3.Get(ctx, row.S3Key) + if err != nil { + return nil, "", err + } + defer out.Body.Close() + + data, err := io.ReadAll(out.Body) + if err != nil { + return nil, "", err + } + + return data, model.ContentType(row.ContentType), nil +} + +func (s *AttachmentService) checkImage(data []byte, contentType string) (model.ContentType, error) { + cfg, format, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return "", ErrInvalidImage + } + + if cfg.Width*cfg.Height > s.maxPixels { + return "", ErrInvalidSize + } + + switch format { + case "png": + if contentType != string(model.ContentTypePNG) { + return "", ErrInvalidImage + } + return model.ContentTypePNG, nil + case "jpeg": + if contentType != string(model.ContentTypeJPEG) { + return "", ErrInvalidImage + } + return model.ContentTypeJPEG, nil + default: + return "", ErrInvalidImage + } +} + +func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID uuid.UUID) error { + member, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{ + ChatID: chatID, + UserID: userID, + }) + if err != nil { + return err + } + if !member { + return ErrAttachmentNotFound + } + + return nil +} diff --git a/internal/service/message.go b/internal/service/message.go index a993d59..79b830c 100644 --- a/internal/service/message.go +++ b/internal/service/message.go @@ -20,7 +20,6 @@ import ( var ( ErrMessageChatNotFound = errors.New("chat not found") - ErrAttachmentNotFound = errors.New("attachment not found") ErrAttachmentNotReady = errors.New("attachment not ready") ErrIdempotencyKeyConflict = errors.New("idempotency key reused with different request") )