feat: add 4 grade things

This commit is contained in:
TAskMAster339
2026-10-18 19:23:27 +03:00
parent e3cd2516ba
commit 4d91357932
23 changed files with 2015 additions and 140 deletions
+59 -29
View File
@@ -6,20 +6,20 @@ import (
"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"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
const MaxUploadBytes int64 = 10485760
@@ -31,11 +31,16 @@ var ErrAttachmentNotFound = errors.New("attachment not found")
type AttachmentService struct {
metadata *repositories.AttachmentStore
objects *repositories.ObjectStore
objects AttachmentObjects
uploadSlot chan struct{}
}
func NewAttachmentService(metadata *repositories.AttachmentStore, objects *repositories.ObjectStore) *AttachmentService {
type AttachmentObjects interface {
Put(context.Context, string, io.Reader, int64, string) error
Get(context.Context, string) (io.ReadCloser, error)
}
func NewAttachmentService(metadata *repositories.AttachmentStore, objects AttachmentObjects) *AttachmentService {
return &AttachmentService{metadata: metadata, objects: objects, uploadSlot: make(chan struct{}, 1)}
}
func ValidateFilename(name string) error {
@@ -50,11 +55,15 @@ func ValidateFilename(name string) error {
return nil
}
func ValidateImage(data []byte, declared string) (string, error) {
return ValidateImageReader(bytes.NewReader(data), declared)
}
func ValidateImageReader(reader io.ReadSeeker, 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))
config, format, err := image.DecodeConfig(reader)
if err != nil {
return "", ErrUnsupportedMedia
}
@@ -66,7 +75,10 @@ func ValidateImage(data []byte, declared string) (string, error) {
return "", ErrPayloadTooLarge
}
// DecodeConfig alone accepts truncated headers; decode only after bounding pixels.
decoded, _, err := image.Decode(bytes.NewReader(data))
if _, err = reader.Seek(0, io.SeekStart); err != nil {
return "", err
}
decoded, _, err := image.Decode(reader)
if err != nil {
return "", ErrUnsupportedMedia
}
@@ -80,37 +92,55 @@ func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename
case <-ctx.Done():
return repositories.Attachment{}, ctx.Err()
}
data, err := io.ReadAll(io.LimitReader(body, MaxUploadBytes+1))
grace, err := repositories.UploadCleanupGrace()
if err != nil {
return repositories.Attachment{}, err
}
if int64(len(data)) > MaxUploadBytes {
directory := os.Getenv("UPLOAD_TMP_DIR")
file, err := os.CreateTemp(directory, "upload-*")
if err != nil {
return repositories.Attachment{}, err
}
defer file.Close()
// Linux keeps the open descriptor usable; no abandoned pathname survives a crash.
if err = os.Remove(file.Name()); err != nil {
return repositories.Attachment{}, err
}
hash := sha256.New()
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(body, MaxUploadBytes+1), make([]byte, 32*1024))
if err != nil {
return repositories.Attachment{}, err
}
if size > MaxUploadBytes {
return repositories.Attachment{}, ErrPayloadTooLarge
}
actual, err := ValidateImage(data, contentType)
if err = ctx.Err(); err != nil {
return repositories.Attachment{}, err
}
if _, err = file.Seek(0, io.SeekStart); err != nil {
return repositories.Attachment{}, err
}
actual, err := ValidateImageReader(file, 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 {
if err = ctx.Err(); 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)
}
if _, err = file.Seek(0, io.SeekStart); err != nil {
return repositories.Attachment{}, err
}
now := time.Now().UTC().Truncate(time.Microsecond)
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
a.ObjectKey = "originals/" + a.ID
if err = s.metadata.ReserveUpload(ctx, a, grace); err != nil {
return repositories.Attachment{}, err
}
err = s.metadata.PublishUpload(ctx, a, func(ctx context.Context) error {
return s.objects.Put(ctx, a.ObjectKey, file, a.SizeBytes, a.ContentType)
})
// On any uncertainty leave the durable reservation to the cleanup worker.
if err != nil {
return repositories.Attachment{}, err
}
return a, nil