feat: attachments over S3 (grade 3)

This commit is contained in:
2026-11-20 03:55:39 +03:00
parent 083d0d80cc
commit 89e9e7b4d4
44 changed files with 1468 additions and 67 deletions
+76
View File
@@ -0,0 +1,76 @@
package handler
import (
"io"
"mime"
"net/http"
"strconv"
"uuid"
"github.com/go-chi/chi/v5"
)
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
chatID, err := chatIDParam(r)
if err != nil {
h.fail(w, r, err)
return
}
filename := r.URL.Query().Get("filename")
if filename == "" {
h.fail(w, r, badRequest("filename is required"))
return
}
contentType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
contentType = ""
}
attachment, err := h.attachments.Upload(r.Context(), actor(r), chatID, filename, contentType, r.Body)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusCreated, toAttachmentResponse(attachment))
}
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
id, err := attachmentIDParam(r)
if err != nil {
h.fail(w, r, err)
return
}
attachment, err := h.attachments.Get(r.Context(), actor(r), id)
if err != nil {
h.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toAttachmentResponse(attachment))
}
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
id, err := attachmentIDParam(r)
if err != nil {
h.fail(w, r, err)
return
}
attachment, content, err := h.attachments.Open(r.Context(), actor(r), id, r.URL.Query().Get("variant"))
if err != nil {
h.fail(w, r, err)
return
}
defer content.Close()
w.Header().Set("Content-Type", attachment.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(attachment.SizeBytes, 10))
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, content); err != nil {
h.log.Error("attachment download interrupted", "request_id", w.Header().Get(headerRequestID), "err", err)
}
}
func attachmentIDParam(r *http.Request) (uuid.UUID, error) {
id, ok := parseUUID(chi.URLParam(r, "attachment_id"))
if !ok {
return uuid.UUID{}, badRequest("attachment_id must be a UUID")
}
return id, nil
}
+64 -11
View File
@@ -2,6 +2,7 @@ package handler
import (
"time"
"uuid"
"messenger/internal/domain"
)
@@ -18,7 +19,8 @@ type createChatRequest struct {
}
type createMessageRequest struct {
Text *string `json:"text"`
Text *string `json:"text"`
AttachmentIDs *[]string `json:"attachment_ids"`
}
type userResponse struct {
@@ -36,11 +38,36 @@ type chatResponse struct {
}
type messageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type variantResponse struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
type attachmentResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []variantResponse `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type pageResponse[T any] struct {
@@ -106,14 +133,40 @@ func toChatResponse(c domain.Chat) chatResponse {
func toMessageResponse(m domain.Message) messageResponse {
return messageResponse{
ID: m.ID.String(),
ChatID: m.ChatID.String(),
SenderID: m.SenderID.String(),
Text: m.Text,
CreatedAt: formatTime(m.CreatedAt),
ID: m.ID.String(),
ChatID: m.ChatID.String(),
SenderID: m.SenderID.String(),
Text: m.Text,
CreatedAt: formatTime(m.CreatedAt),
AttachmentIDs: toIDStrings(m.AttachmentIDs),
}
}
func toAttachmentResponse(a domain.Attachment) attachmentResponse {
return attachmentResponse{
ID: a.ID.String(),
ChatID: a.ChatID.String(),
OwnerID: a.OwnerID.String(),
Filename: a.Filename,
ContentType: a.ContentType,
SizeBytes: a.SizeBytes,
SHA256: a.SHA256,
Status: a.Status,
Variants: []variantResponse{},
ErrorCode: a.ErrorCode,
CreatedAt: formatTime(a.CreatedAt),
UpdatedAt: formatTime(a.UpdatedAt),
}
}
func toIDStrings(ids []uuid.UUID) []string {
result := make([]string, len(ids))
for i, id := range ids {
result[i] = id.String()
}
return result
}
func toPageResponse[D, R any](p domain.Page[D], conv func(D) R) pageResponse[R] {
items := make([]R, len(p.Items))
for i, it := range p.Items {
+4
View File
@@ -43,6 +43,10 @@ func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
writeError(w, http.StatusNotFound, "not_found", "resource not found")
case errors.Is(err, domain.ErrConflict):
writeError(w, http.StatusConflict, "conflict", err.Error())
case errors.Is(err, domain.ErrTooLarge):
writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large", err.Error())
case errors.Is(err, domain.ErrUnsupportedMedia):
writeError(w, http.StatusUnsupportedMediaType, "unsupported_media_type", err.Error())
case errors.Is(err, domain.ErrUnavailable):
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
+12 -9
View File
@@ -12,18 +12,21 @@ import (
type Pinger func(ctx context.Context) error
type Handler struct {
users *service.UserService
auth *service.AuthService
chats *service.ChatService
messages *service.MessageService
deps []Pinger
log *slog.Logger
draining atomic.Bool
users *service.UserService
auth *service.AuthService
chats *service.ChatService
messages *service.MessageService
attachments *service.AttachmentService
deps []Pinger
log *slog.Logger
draining atomic.Bool
}
func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService,
messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler {
return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log}
messages *service.MessageService, attachments *service.AttachmentService,
deps []Pinger, log *slog.Logger) *Handler {
return &Handler{users: users, auth: auth, chats: chats, messages: messages,
attachments: attachments, deps: deps, log: log}
}
func (h *Handler) StartDraining() {
+36 -1
View File
@@ -5,6 +5,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
@@ -15,6 +16,7 @@ import (
"time"
"uuid"
"messenger/internal/domain"
"messenger/internal/handler"
"messenger/internal/repository/postgres"
"messenger/internal/repository/redis"
@@ -22,6 +24,38 @@ import (
"messenger/internal/service"
)
type stubObjectStore struct {
objects map[string][]byte
}
func newStubObjectStore() *stubObjectStore {
return &stubObjectStore{objects: map[string][]byte{}}
}
func (s *stubObjectStore) Put(_ context.Context, key string, r io.Reader, _ int64, _ string) error {
data, err := io.ReadAll(r)
if err != nil {
return err
}
s.objects[key] = data
return nil
}
func (s *stubObjectStore) Get(_ context.Context, key string) (io.ReadCloser, error) {
data, ok := s.objects[key]
if !ok {
return nil, domain.ErrNotFound
}
return io.NopCloser(strings.NewReader(string(data))), nil
}
func (s *stubObjectStore) Delete(_ context.Context, key string) error {
delete(s.objects, key)
return nil
}
func (s *stubObjectStore) Ping(context.Context) error { return nil }
func testURLs(t *testing.T) (string, string) {
t.Helper()
dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL")
@@ -56,7 +90,8 @@ func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest
auth := service.NewAuthService(store, sessions, ttl)
chats := service.NewChatService(store)
messages := service.NewMessageService(chats, store)
h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
attachments := service.NewAttachmentService(chats, store, newStubObjectStore(), 10485760, 40000000)
h := handler.New(users, auth, chats, messages, attachments, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
srv := httptest.NewServer(router.New(h, "test"))
t.Cleanup(srv.Close)
return srv
+14 -1
View File
@@ -3,6 +3,7 @@ package handler
import (
"net/http"
"regexp"
"uuid"
)
const headerIdempotencyKey = "Idempotency-Key"
@@ -29,7 +30,19 @@ func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
h.fail(w, r, badRequest("text is required"))
return
}
msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text)
var attachmentIDs []uuid.UUID
if req.AttachmentIDs != nil {
attachmentIDs = make([]uuid.UUID, len(*req.AttachmentIDs))
for i, raw := range *req.AttachmentIDs {
id, ok := parseUUID(raw)
if !ok {
h.fail(w, r, badRequest("attachment_ids must contain UUIDs"))
return
}
attachmentIDs[i] = id
}
}
msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text, attachmentIDs)
if err != nil {
h.fail(w, r, err)
return