forked from mtusi2026/mtusi2026lab4
feat: add minio
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"messenger/src/backend/repositories"
|
||||
"mime"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const MaxUploadBytes int64 = 10485760
|
||||
const MaxImagePixels int64 = 40000000
|
||||
|
||||
var ErrPayloadTooLarge = errors.New("payload too large")
|
||||
var ErrUnsupportedMedia = errors.New("unsupported image")
|
||||
var ErrAttachmentNotFound = errors.New("attachment not found")
|
||||
|
||||
type AttachmentService struct {
|
||||
metadata *repositories.AttachmentStore
|
||||
objects *repositories.ObjectStore
|
||||
uploadSlot chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(metadata *repositories.AttachmentStore, objects *repositories.ObjectStore) *AttachmentService {
|
||||
return &AttachmentService{metadata: metadata, objects: objects, uploadSlot: make(chan struct{}, 1)}
|
||||
}
|
||||
func ValidateFilename(name string) error {
|
||||
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
|
||||
return InvalidInput{"filename must contain 1-255 characters"}
|
||||
}
|
||||
for _, r := range name {
|
||||
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
||||
return InvalidInput{"invalid filename"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func ValidateImage(data []byte, declared string) (string, error) {
|
||||
contentType, _, err := mime.ParseMediaType(declared)
|
||||
if err != nil || (contentType != "image/png" && contentType != "image/jpeg") {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
config, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
actual := "image/" + format
|
||||
if actual != contentType {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
if config.Width <= 0 || config.Height <= 0 || int64(config.Width) > MaxImagePixels/int64(config.Height) {
|
||||
return "", ErrPayloadTooLarge
|
||||
}
|
||||
// DecodeConfig alone accepts truncated headers; decode only after bounding pixels.
|
||||
decoded, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
_ = decoded
|
||||
return actual, nil
|
||||
}
|
||||
func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename, contentType string, body io.Reader) (repositories.Attachment, error) {
|
||||
select {
|
||||
case s.uploadSlot <- struct{}{}:
|
||||
defer func() { <-s.uploadSlot }()
|
||||
case <-ctx.Done():
|
||||
return repositories.Attachment{}, ctx.Err()
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(body, MaxUploadBytes+1))
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if int64(len(data)) > MaxUploadBytes {
|
||||
return repositories.Attachment{}, ErrPayloadTooLarge
|
||||
}
|
||||
actual, err := ValidateImage(data, contentType)
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a.ObjectKey = "originals/" + a.ID
|
||||
if err = s.objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if err = s.metadata.Create(ctx, a); err != nil {
|
||||
// A connection error can hide a successful autocommit. Delete only after
|
||||
// a definite SQL rejection; otherwise preserve bytes for later reconciliation.
|
||||
var rejected *pgconn.PgError
|
||||
if errors.As(err, &rejected) {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if cleanupErr := s.objects.Delete(cleanup, a.ObjectKey); cleanupErr != nil {
|
||||
log.Printf("attachment compensation failed for %s", a.ID)
|
||||
}
|
||||
} else {
|
||||
log.Printf("attachment metadata outcome uncertain for %s; preserving S3 object", a.ID)
|
||||
}
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
func (s *AttachmentService) Get(ctx context.Context, id, userID string) (repositories.Attachment, error) {
|
||||
a, err := s.metadata.GetForMember(ctx, id, userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return a, ErrAttachmentNotFound
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
func (s *AttachmentService) Content(ctx context.Context, a repositories.Attachment) (io.ReadCloser, error) {
|
||||
return s.objects.Get(ctx, a.ObjectKey)
|
||||
}
|
||||
|
||||
func NormalizeAttachmentIDs(ids []string) ([]string, error) {
|
||||
if len(ids) > 10 {
|
||||
return nil, InvalidInput{"at most 10 attachments are allowed"}
|
||||
}
|
||||
result := make([]string, 0, len(ids))
|
||||
seen := map[string]bool{}
|
||||
for _, id := range ids {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
return nil, InvalidInput{"invalid attachment id"}
|
||||
}
|
||||
id = strings.ToLower(parsed.String())
|
||||
if seen[id] {
|
||||
return nil, InvalidInput{"duplicate attachment id"}
|
||||
}
|
||||
seen[id] = true
|
||||
result = append(result, id)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
Reference in New Issue
Block a user