feat: add MinIO presigned direct upload endpoints

Add POST /files/presign-upload and /files/complete-upload so clients can PUT files directly to MinIO with upload progress tracking.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-06-14 05:07:59 -07:00
parent d3b9cbf204
commit b57b306372
4 changed files with 315 additions and 0 deletions

View File

@ -2,13 +2,18 @@ package minio
import (
"context"
"errors"
"io"
"net/http"
"net/url"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var ErrObjectNotFound = errors.New("object not found")
type Client struct {
mc *minio.Client
bucketName string
@ -62,6 +67,32 @@ func (c *Client) GetFileURL(ctx context.Context, objectKey string, expiry time.D
return u.String(), nil
}
// PresignedPutURL returns a presigned PUT URL so clients can upload directly to MinIO.
func (c *Client) PresignedPutURL(ctx context.Context, objectKey, contentType string, expiry time.Duration) (string, error) {
reqParams := make(url.Values)
if contentType != "" {
reqParams.Set("Content-Type", contentType)
}
u, err := c.mc.Presign(ctx, http.MethodPut, c.bucketName, objectKey, expiry, reqParams)
if err != nil {
return "", err
}
return u.String(), nil
}
// StatObject returns metadata for an object if it exists.
func (c *Client) StatObject(ctx context.Context, objectKey string) (minio.ObjectInfo, error) {
info, err := c.mc.StatObject(ctx, c.bucketName, objectKey, minio.StatObjectOptions{})
if err != nil {
var resp minio.ErrorResponse
if errors.As(err, &resp) && (resp.Code == "NoSuchKey" || resp.StatusCode == http.StatusNotFound) {
return minio.ObjectInfo{}, ErrObjectNotFound
}
return minio.ObjectInfo{}, err
}
return info, nil
}
// DeleteFile removes an object from the bucket.
func (c *Client) DeleteFile(ctx context.Context, objectKey string) error {
return c.mc.RemoveObject(ctx, c.bucketName, objectKey, minio.RemoveObjectOptions{})

View File

@ -3,6 +3,7 @@ package minio
import (
minioclient "Yimaru-Backend/internal/pkgs/minio"
"context"
"errors"
"fmt"
"io"
"path"
@ -12,6 +13,8 @@ import (
"go.uber.org/zap"
)
var ErrUploadedObjectNotFound = minioclient.ErrObjectNotFound
type Service struct {
client *minioclient.Client
logger *zap.Logger
@ -29,11 +32,21 @@ func (s *Service) Init(ctx context.Context) error {
return s.client.EnsureBucket(ctx)
}
const defaultPresignedUploadExpiry = 15 * time.Minute
// UploadResult holds the result of an upload operation.
type UploadResult struct {
ObjectKey string
}
// PresignedUploadResult holds a client-direct MinIO upload slot.
type PresignedUploadResult struct {
ObjectKey string
UploadURL string
ContentType string
ExpiresIn int
}
// Upload stores a file in MinIO under the given subdirectory.
// It generates a unique filename and returns the object key.
func (s *Service) Upload(ctx context.Context, subDir string, filename string, reader io.Reader, fileSize int64, contentType string) (*UploadResult, error) {
@ -66,6 +79,45 @@ func (s *Service) GetURL(ctx context.Context, objectKey string, expiry time.Dura
return s.client.GetFileURL(ctx, objectKey, expiry)
}
// CreatePresignedUpload allocates an object key and returns a presigned PUT URL for direct client upload.
func (s *Service) CreatePresignedUpload(ctx context.Context, subDir, filename, contentType string) (*PresignedUploadResult, error) {
ext := path.Ext(filename)
objectKey := subDir + "/" + uuid.New().String() + ext
uploadURL, err := s.client.PresignedPutURL(ctx, objectKey, contentType, defaultPresignedUploadExpiry)
if err != nil {
s.logger.Error("Failed to create presigned upload URL",
zap.String("object_key", objectKey),
zap.Error(err),
)
return nil, fmt.Errorf("failed to create presigned upload URL: %w", err)
}
s.logger.Info("Created presigned MinIO upload URL",
zap.String("object_key", objectKey),
zap.String("content_type", contentType),
)
return &PresignedUploadResult{
ObjectKey: objectKey,
UploadURL: uploadURL,
ContentType: contentType,
ExpiresIn: int(defaultPresignedUploadExpiry.Seconds()),
}, nil
}
// ConfirmUploadedObject verifies that a presigned upload completed and returns object metadata.
func (s *Service) ConfirmUploadedObject(ctx context.Context, objectKey string) (int64, string, error) {
info, err := s.client.StatObject(ctx, objectKey)
if err != nil {
if errors.Is(err, minioclient.ErrObjectNotFound) {
return 0, "", err
}
return 0, "", fmt.Errorf("failed to verify uploaded object: %w", err)
}
return info.Size, info.ContentType, nil
}
func (s *Service) BucketName() string {
return s.client.BucketName()
}

View File

@ -3,7 +3,9 @@ package handlers
import (
dbgen "Yimaru-Backend/gen/db"
"Yimaru-Backend/internal/domain"
minioservice "Yimaru-Backend/internal/services/minio"
"bytes"
"errors"
"fmt"
"io"
"net/http"
@ -33,6 +35,29 @@ type uploadMediaByURLReq struct {
Description string `json:"description"`
}
type presignedUploadReq struct {
MediaType string `json:"media_type"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
FileSize int64 `json:"file_size"`
}
type presignedUploadRes struct {
ObjectKey string `json:"object_key"`
UploadURL string `json:"upload_url"`
Reference string `json:"reference"`
ContentType string `json:"content_type"`
MediaType string `json:"media_type"`
Provider string `json:"provider"`
ExpiresIn int `json:"expires_in"`
}
type completePresignedUploadReq struct {
ObjectKey string `json:"object_key"`
MediaType string `json:"media_type"`
FileSize int64 `json:"file_size,omitempty"`
}
type refreshFileURLReq struct {
Reference string `json:"reference"`
}
@ -175,6 +200,211 @@ func (h *Handler) RefreshFileURL(c *fiber.Ctx) error {
})
}
// CreatePresignedUpload returns a presigned PUT URL so the client can upload directly to MinIO with progress tracking.
// @Summary Create presigned MinIO upload URL
// @Description Returns a short-lived PUT URL and object key. Upload the file with HTTP PUT to upload_url using the same Content-Type, then call POST /files/complete-upload.
// @Tags files
// @Accept json
// @Produce json
// @Param body body presignedUploadReq true "Presigned upload request"
// @Success 201 {object} domain.Response
// @Router /api/v1/files/presign-upload [post]
func (h *Handler) CreatePresignedUpload(c *fiber.Ctx) error {
if h.minioSvc == nil {
return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{
Message: "File storage service is not available",
})
}
var req presignedUploadReq
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
mediaType := strings.ToLower(strings.TrimSpace(req.MediaType))
filename := strings.TrimSpace(req.Filename)
contentType := strings.TrimSpace(req.ContentType)
if mediaType == "" || filename == "" || contentType == "" || req.FileSize <= 0 {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: "media_type, filename, content_type, and file_size are required",
})
}
if mediaType == "video" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Use Vimeo TUS for video uploads",
Error: "POST /api/v1/vimeo/uploads/tus for video files",
})
}
if !isPresignedMinIOMediaType(mediaType) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid media_type",
Error: "media_type must be one of: image, audio, pdf",
})
}
maxSize := maxUploadSizeForMediaType(mediaType)
if req.FileSize > maxSize {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "File too large",
Error: "File exceeds size limit for selected media_type",
})
}
normalizedType, err := normalizeAndValidateMediaContentType(mediaType, contentType, filename)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid file type",
Error: err.Error(),
})
}
result, err := h.minioSvc.CreatePresignedUpload(c.Context(), mediaType, filename, normalizedType)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to create presigned upload URL",
Error: err.Error(),
})
}
reference := "minio://" + result.ObjectKey
return c.Status(fiber.StatusCreated).JSON(domain.Response{
Message: "Presigned upload URL created successfully",
Data: presignedUploadRes{
ObjectKey: result.ObjectKey,
UploadURL: result.UploadURL,
Reference: reference,
ContentType: result.ContentType,
MediaType: mediaType,
Provider: "MINIO",
ExpiresIn: result.ExpiresIn,
},
Success: true,
StatusCode: fiber.StatusCreated,
})
}
// CompletePresignedUpload verifies a client-direct MinIO upload and returns the stored file reference.
// @Summary Complete presigned MinIO upload
// @Description Call after PUT upload to upload_url. Returns the same file metadata shape as POST /files/upload.
// @Tags files
// @Accept json
// @Produce json
// @Param body body completePresignedUploadReq true "Complete upload request"
// @Success 200 {object} domain.Response
// @Router /api/v1/files/complete-upload [post]
func (h *Handler) CompletePresignedUpload(c *fiber.Ctx) error {
if h.minioSvc == nil {
return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{
Message: "File storage service is not available",
})
}
var req completePresignedUploadReq
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: err.Error(),
})
}
objectKey := strings.TrimSpace(req.ObjectKey)
mediaType := strings.ToLower(strings.TrimSpace(req.MediaType))
if objectKey == "" || mediaType == "" {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid request body",
Error: "object_key and media_type are required",
})
}
if !isPresignedMinIOMediaType(mediaType) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid media_type",
Error: "media_type must be one of: image, audio, pdf",
})
}
if !objectKeyMatchesMediaType(objectKey, mediaType) {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Invalid object_key",
Error: "object_key does not match media_type",
})
}
size, contentType, err := h.minioSvc.ConfirmUploadedObject(c.Context(), objectKey)
if err != nil {
if errors.Is(err, minioservice.ErrUploadedObjectNotFound) {
return c.Status(fiber.StatusNotFound).JSON(domain.ErrorResponse{
Message: "Uploaded file not found",
Error: "Complete the PUT upload to MinIO before calling this endpoint",
})
}
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
Message: "Failed to verify uploaded file",
Error: err.Error(),
})
}
if req.FileSize > 0 && size != req.FileSize {
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Uploaded file size mismatch",
Error: fmt.Sprintf("expected %d bytes, got %d", req.FileSize, size),
})
}
if maxSize := maxUploadSizeForMediaType(mediaType); size > maxSize {
_ = h.minioSvc.Delete(c.Context(), objectKey)
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
Message: "Uploaded file too large",
Error: "File exceeds size limit for selected media_type",
})
}
storedPath := "minio://" + objectKey
return c.Status(fiber.StatusOK).JSON(domain.Response{
Message: "File uploaded successfully",
Data: uploadMediaRes{
ObjectKey: objectKey,
URL: h.resolveFileURL(c, storedPath),
ContentType: contentType,
MediaType: mediaType,
Provider: "MINIO",
},
Success: true,
StatusCode: fiber.StatusOK,
})
}
func isPresignedMinIOMediaType(mediaType string) bool {
switch mediaType {
case "image", "audio", "pdf":
return true
default:
return false
}
}
func maxUploadSizeForMediaType(mediaType string) int64 {
switch mediaType {
case "image":
return 10 * 1024 * 1024
case "audio":
return 50 * 1024 * 1024
case "pdf":
return 25 * 1024 * 1024
default:
return 100 * 1024 * 1024
}
}
func objectKeyMatchesMediaType(objectKey, mediaType string) bool {
prefix := mediaType + "/"
if !strings.HasPrefix(objectKey, prefix) {
return false
}
rest := strings.TrimPrefix(objectKey, prefix)
return rest != "" && !strings.Contains(rest, "/")
}
// UploadMedia uploads an image/audio/video/pdf file and returns its URL and key.
// @Summary Upload media file
// @Tags files

View File

@ -176,6 +176,8 @@ func (a *App) initAppRoutes() {
// File storage (MinIO)
groupV1.Get("/files/url", a.authMiddleware, h.GetFileURL)
groupV1.Post("/files/refresh-url", a.authMiddleware, h.RefreshFileURL)
groupV1.Post("/files/presign-upload", a.authMiddleware, h.CreatePresignedUpload)
groupV1.Post("/files/complete-upload", a.authMiddleware, h.CompletePresignedUpload)
groupV1.Post("/files/upload", a.authMiddleware, h.UploadMedia)
groupV1.Post("/files/audio", a.authMiddleware, h.UploadAudio)
groupV1.Post("/questions/audio-answer", a.authMiddleware, h.SubmitAudioAnswer)