Files
mtusi2026lab4/internal/objectstore/s3.go
T

179 lines
4.8 KiB
Go

// Package objectstore stores original bytes; chat authorization belongs to the service.
package objectstore
import (
"context"
"encoding/hex"
"errors"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/s3utils"
)
var (
ErrConfig = errors.New("invalid S3 configuration")
ErrInput = errors.New("invalid object input")
ErrNotFound = errors.New("S3 object not found")
ErrUnavailable = errors.New("S3 unavailable")
)
const operationTimeout = 30 * time.Second
type Config struct {
Endpoint, Region, Bucket string
AccessKeyFile, SecretKeyFile string
}
type S3 struct {
core *minio.Core
bucket string
transport *http.Transport
}
func New(config Config) (*S3, error) {
u, err := url.Parse(config.Endpoint)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" || config.Region == "" {
return nil, ErrConfig
}
if err := s3utils.CheckValidBucketNameStrict(config.Bucket); err != nil {
return nil, ErrConfig
}
access, err := readSecret(config.AccessKeyFile)
if err != nil {
return nil, err
}
secret, err := readSecret(config.SecretKeyFile)
if err != nil {
return nil, err
}
transport := &http.Transport{
DialContext: (&net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 5 * time.Second,
IdleConnTimeout: 60 * time.Second, MaxIdleConns: 10, MaxIdleConnsPerHost: 10,
}
core, err := minio.NewCore(u.Host, &minio.Options{
Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https",
Region: config.Region, BucketLookup: minio.BucketLookupPath,
Transport: transport, MaxRetries: 1,
})
if err != nil {
return nil, ErrConfig
}
return &S3{core: core, bucket: config.Bucket, transport: transport}, nil
}
func readSecret(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", ErrConfig
}
value := strings.TrimRight(string(data), "\r\n")
if strings.TrimSpace(value) == "" {
return "", ErrConfig
}
return value, nil
}
func (s *S3) Close() { s.transport.CloseIdleConnections() }
func (s *S3) Check(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond)
defer cancel()
exists, err := s.core.BucketExists(ctx, s.bucket)
if err != nil {
return storageError(ctx, err)
}
if !exists {
return ErrUnavailable
}
return nil
}
func ObjectKey(id string) (string, error) {
parsed, err := uuid.Parse(id)
if err != nil || parsed.String() != id {
return "", ErrInput
}
return "attachments/" + id, nil
}
func (s *S3) Put(ctx context.Context, id string, source io.Reader, size int64, contentType, sha256 string) error {
key, err := ObjectKey(id)
checksum, checksumErr := hex.DecodeString(sha256)
if err != nil || source == nil || size < 1 || size > 10485760 || (contentType != "image/png" && contentType != "image/jpeg") || checksumErr != nil || len(checksum) != 32 || strings.ToLower(sha256) != sha256 {
return ErrInput
}
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
defer cancel()
_, err = s.core.PutObject(ctx, s.bucket, key, source, size, "", sha256, minio.PutObjectOptions{ContentType: contentType})
return storageError(ctx, err)
}
type Original struct {
Body io.ReadCloser
SizeBytes int64
ContentType string
}
func (s *S3) Open(ctx context.Context, id string) (Original, error) {
key, err := ObjectKey(id)
if err != nil {
return Original{}, err
}
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
body, info, _, err := s.core.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
if err != nil {
mapped := storageError(ctx, err)
cancel()
return Original{}, mapped
}
return Original{Body: &originalBody{ReadCloser: body, cancel: cancel}, SizeBytes: info.Size, ContentType: info.ContentType}, nil
}
func (s *S3) Delete(ctx context.Context, id string) error {
key, err := ObjectKey(id)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
defer cancel()
return storageError(ctx, s.core.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}))
}
func storageError(ctx context.Context, err error) error {
if err == nil {
return nil
}
if ctx.Err() != nil {
return ctx.Err()
}
switch minio.ToErrorResponse(err).Code {
case "NoSuchKey", "NoSuchObject":
return ErrNotFound
default:
return ErrUnavailable
}
}
type originalBody struct {
io.ReadCloser
cancel context.CancelFunc
once sync.Once
err error
}
func (b *originalBody) Close() error {
b.once.Do(func() { b.err = b.ReadCloser.Close(); b.cancel() })
return b.err
}