Files
mtusi2026lab5/internal/transport/rest/attachments.go
T
Vladislav Kunetskiy 4bdcac3dfa lab5: асинхронная очередь, worker и идемпотентный pipeline
API принимает 202 после durable staging и TX intent (job+outbox); отдельные relay и worker публикуют/обрабатывают задания с publisher confirm, lease, retry/backoff, DLQ и replay. Добавлены версии pipeline, варианты thumbnail/crop/optimized, presign в verified staging, status-aware sweeper и admission control.
2026-10-30 22:36:52 +03:00

184 lines
5.0 KiB
Go

package rest
import (
"context"
"fmt"
"io"
"mtusi-messenger/internal/domain"
attachmentService "mtusi-messenger/internal/service/attachment"
"mtusi-messenger/internal/transport/rest/internal/oas"
)
func (h *Handler) UploadAttachment(
ctx context.Context,
req oas.UploadAttachmentReq,
params oas.UploadAttachmentParams,
) (oas.UploadAttachmentRes, error) {
body, declared, err := uploadBody(req)
if err != nil {
return nil, err
}
attachment, err := h.attachments.Upload(ctx, attachmentService.UploadInput{
ChatID: params.ChatID,
OwnerID: caller(ctx),
Filename: params.Filename,
DeclaredContentType: declared,
Body: body,
})
if err != nil {
return nil, err
}
return &oas.AttachmentHeaders{
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
Response: attachmentResponse(attachment),
}, nil
}
func (h *Handler) GetAttachment(
ctx context.Context,
params oas.GetAttachmentParams,
) (oas.GetAttachmentRes, error) {
attachment, err := h.attachments.Get(ctx, caller(ctx), params.AttachmentID)
if err != nil {
return nil, err
}
return &oas.AttachmentHeaders{
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
Response: attachmentResponse(attachment),
}, nil
}
func (h *Handler) DownloadAttachment(
ctx context.Context,
params oas.DownloadAttachmentParams,
) (oas.DownloadAttachmentRes, error) {
variant := domain.VariantOriginal
if requested, ok := params.Variant.Get(); ok {
variant = domain.VariantName(requested)
}
attachment, metadata, body, err := h.attachments.OpenVariant(
ctx, caller(ctx), params.AttachmentID, variant,
)
if err != nil {
return nil, err
}
// The generated transport copies the body after the handler returns. Close
// the S3 stream when the client disconnects; closeOnEOF covers the normal
// path.
_ = context.AfterFunc(ctx, func() { _ = body.Close() })
requestID := oas.NewOptString(requestIDFromContext(ctx))
reader := closeOnEOF{ReadCloser: body}
switch metadata.ContentType {
case "image/png":
return &oas.DownloadAttachmentOKImagePNGHeaders{
XRequestID: requestID,
Response: oas.DownloadAttachmentOKImagePNG{Data: reader},
}, nil
case "image/jpeg":
return &oas.DownloadAttachmentOKImageJpegHeaders{
XRequestID: requestID,
Response: oas.DownloadAttachmentOKImageJpeg{Data: reader},
}, nil
case "image/webp":
return &oas.DownloadAttachmentOKImageWEBPHeaders{
XRequestID: requestID,
Response: oas.DownloadAttachmentOKImageWEBP{Data: reader},
}, nil
default:
_ = body.Close()
return nil, fmt.Errorf("%w: unexpected content type %q", domain.ErrUnavailable, attachment.ContentType)
}
}
func uploadBody(req oas.UploadAttachmentReq) (io.Reader, string, error) {
switch typed := req.(type) {
case *oas.UploadAttachmentReqImagePNG:
return typed.Data, "image/png", nil
case *oas.UploadAttachmentReqImageJpeg:
return typed.Data, "image/jpeg", nil
default:
return nil, "", fmt.Errorf("%w: request body must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
}
}
func attachmentResponse(attachment domain.Attachment) oas.Attachment {
response := oas.Attachment{
ID: attachment.ID,
ChatID: attachment.ChatID,
OwnerID: attachment.OwnerID,
Filename: attachment.Filename,
SizeBytes: int(attachment.SizeBytes),
SHA256: attachment.SHA256,
Status: attachmentStatus(attachment.Status),
ErrorCode: oas.NilString{Null: true},
CreatedAt: attachment.CreatedAt,
UpdatedAt: attachment.UpdatedAt,
Variants: make([]oas.Variant, 0, len(attachment.Variants)),
}
switch attachment.ContentType {
case "image/png":
response.ContentType = oas.AttachmentContentTypeImagePNG
case "image/jpeg":
response.ContentType = oas.AttachmentContentTypeImageJpeg
default:
response.ContentType = oas.AttachmentContentType(attachment.ContentType)
}
if attachment.ErrorCode != nil {
response.ErrorCode = oas.NilString{Value: *attachment.ErrorCode}
}
for _, variant := range attachment.Variants {
response.Variants = append(response.Variants, oas.Variant{
Name: oas.VariantName(variant.Name),
ContentType: oas.VariantContentType(variant.ContentType),
SizeBytes: int(variant.SizeBytes),
Width: variant.Width,
Height: variant.Height,
SHA256: variant.SHA256,
})
}
return response
}
func attachmentStatus(status domain.AttachmentStatus) oas.AttachmentStatus {
switch status {
case domain.AttachmentQueued:
return oas.AttachmentStatusQueued
case domain.AttachmentProcessing:
return oas.AttachmentStatusProcessing
case domain.AttachmentReady:
return oas.AttachmentStatusReady
case domain.AttachmentFailed:
return oas.AttachmentStatusFailed
default:
// Pending is internal and never reaches the transport; map it to the
// closest public state rather than inventing a new enum value.
return oas.AttachmentStatusQueued
}
}
type closeOnEOF struct {
io.ReadCloser
}
func (r closeOnEOF) Read(p []byte) (int, error) {
n, err := r.ReadCloser.Read(p)
if err != nil {
_ = r.Close()
}
return n, err
}