feat:lab4-catchup
This commit is contained in:
@@ -0,0 +1,213 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
type S3Store struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
tr *http.Transport
|
||||
}
|
||||
|
||||
func NewS3Store(ctx context.Context, endpoint, region, bucket, access, secret string, maxBytes, maxPixels int64) (*S3Store, error) {
|
||||
if endpoint == "" || access == "" || secret == "" || bucket == "" {
|
||||
return nil, errors.New("s3 configuration incomplete")
|
||||
}
|
||||
|
||||
tr := &http.Transport{
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 100,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 3 * time.Second, // Быстрый отказ при недоступности
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
cli, err := minio.New(endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(access, secret, ""),
|
||||
Secure: strings.HasPrefix(endpoint, "https://"),
|
||||
Region: region,
|
||||
Transport: tr,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := cli.BucketExists(pingCtx, bucket); err != nil {
|
||||
return nil, fmt.Errorf("s3 bucket check: %w", err)
|
||||
}
|
||||
return &S3Store{client: cli, bucket: bucket, maxBytes: maxBytes, maxPixels: maxPixels, tr: tr}, nil
|
||||
}
|
||||
|
||||
type UploadResult struct {
|
||||
ObjectKey string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
Width int
|
||||
Height int
|
||||
}
|
||||
|
||||
// PutValidatedImage читает тело потоково во временный файл на диске,
|
||||
// проверяет размер, MIME, пиксели и затем стримит в S3.
|
||||
// Это гарантирует, что память не растёт с размером файла.
|
||||
func (s *S3Store) PutValidatedImage(ctx context.Context, objectKey string, body io.Reader) (*UploadResult, error) {
|
||||
// 1. Создаём временный файл.
|
||||
tmpFile, err := os.CreateTemp("", "upload-*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tmpPath := tmpFile.Name()
|
||||
defer func() {
|
||||
tmpFile.Close()
|
||||
os.Remove(tmpPath)
|
||||
}()
|
||||
|
||||
// 2. Копируем тело в файл с ограничением.
|
||||
limited := io.LimitReader(body, s.maxBytes+1)
|
||||
size, err := io.Copy(tmpFile, limited)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size > s.maxBytes {
|
||||
return nil, ErrTooLarge
|
||||
}
|
||||
if size == 0 {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
|
||||
// 3. Проверяем MIME по первым 512 байтам.
|
||||
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
header := make([]byte, 512)
|
||||
n, err := io.ReadFull(tmpFile, header)
|
||||
if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
header = header[:n]
|
||||
ct := http.DetectContentType(header)
|
||||
if ct != "image/png" && ct != "image/jpeg" {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
|
||||
// 4. Проверяем заголовок изображения (размеры).
|
||||
// DecodeConfig читает только начало, но мы используем файл, поэтому это безопасно.
|
||||
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg, _, err := image.DecodeConfig(tmpFile)
|
||||
if err != nil {
|
||||
return nil, ErrNotImage
|
||||
}
|
||||
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
|
||||
return nil, ErrNotImage
|
||||
}
|
||||
|
||||
// 5. Считаем SHA-256 и стримим файл в S3.
|
||||
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var hasher hash.Hash = sha256.New()
|
||||
tee := io.TeeReader(tmpFile, hasher)
|
||||
|
||||
putCtx, cancelPut := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancelPut()
|
||||
|
||||
_, err = s.client.PutObject(putCtx, s.bucket, objectKey, tee, size,
|
||||
minio.PutObjectOptions{ContentType: ct})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sha := hex.EncodeToString(hasher.Sum(nil))
|
||||
|
||||
return &UploadResult{
|
||||
ObjectKey: objectKey,
|
||||
ContentType: ct,
|
||||
SizeBytes: size,
|
||||
SHA256: sha,
|
||||
Width: cfg.Width,
|
||||
Height: cfg.Height,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *S3Store) GetObject(ctx context.Context, objectKey string) (io.ReadCloser, string, int64, error) {
|
||||
// Общий дедлайн на все попытки — 6 секунд.
|
||||
overallCtx, overallCancel := context.WithTimeout(ctx, 6*time.Second)
|
||||
defer overallCancel()
|
||||
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
if attempt > 0 {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
s.tr.CloseIdleConnections()
|
||||
}
|
||||
|
||||
attemptCtx, cancel := context.WithTimeout(overallCtx, 3*time.Second)
|
||||
obj, err := s.client.GetObject(attemptCtx, s.bucket, objectKey, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
cancel()
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
info, err := obj.Stat()
|
||||
if err != nil {
|
||||
obj.Close()
|
||||
cancel()
|
||||
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
|
||||
return nil, "", 0, ErrNotFound
|
||||
}
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(obj)
|
||||
obj.Close()
|
||||
cancel()
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if int64(len(data)) != info.Size {
|
||||
lastErr = fmt.Errorf("size mismatch: got %d, expected %d", len(data), info.Size)
|
||||
continue
|
||||
}
|
||||
|
||||
return io.NopCloser(bytes.NewReader(data)), info.ContentType, info.Size, nil
|
||||
}
|
||||
|
||||
s.tr.CloseIdleConnections()
|
||||
return nil, "", 0, fmt.Errorf("s3 get failed after retries: %w", lastErr)
|
||||
}
|
||||
|
||||
func (s *S3Store) DeleteObject(ctx context.Context, objectKey string) error {
|
||||
return s.client.RemoveObject(ctx, s.bucket, objectKey, minio.RemoveObjectOptions{})
|
||||
}
|
||||
Reference in New Issue
Block a user