lab4: вложения в S3 (MinIO), reconciler PostgreSQL↔S3, тесты и CI
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
// Package storage — приватное S3-хранилище байтов вложений (MinIO).
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// ErrNotFound — объекта нет в bucket.
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
|
||||
// Object — элемент листинга.
|
||||
type Object struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// Store — то, что нужно приложению и reconciler от объектного хранилища.
|
||||
type Store interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, int64, error)
|
||||
Stat(ctx context.Context, key string) (Object, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
// List отдаёт объекты с префиксом в лексикографическом (байтовом) порядке ключей.
|
||||
List(ctx context.Context, prefix string, fn func(Object) error) error
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func NewS3(endpoint, region, bucket, accessKey, secretKey string) (*S3, error) {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Host == "" {
|
||||
return nil, fmt.Errorf("bad S3 endpoint %q", endpoint)
|
||||
}
|
||||
c, err := minio.New(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
||||
Secure: u.Scheme == "https",
|
||||
Region: region,
|
||||
// По умолчанию minio-go повторяет до 10 раз; при недоступном S3 клиент
|
||||
// должен быстро получить 503, а не ждать таймаута LB.
|
||||
MaxRetries: 2,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 client: %w", err)
|
||||
}
|
||||
return &S3{client: c, bucket: bucket}, nil
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
return code == "NoSuchKey" || code == "NotFound"
|
||||
}
|
||||
|
||||
// Put пишет объект одним PUT, читая r потоково (size известен заранее).
|
||||
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
DisableMultipart: true,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("s3 put: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) {
|
||||
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("s3 get: %w", err)
|
||||
}
|
||||
// GetObject ленивый: ошибки (нет объекта, S3 недоступен) видны на Stat.
|
||||
st, err := obj.Stat()
|
||||
if err != nil {
|
||||
obj.Close()
|
||||
if isNotFound(err) {
|
||||
return nil, 0, ErrNotFound
|
||||
}
|
||||
return nil, 0, fmt.Errorf("s3 stat: %w", err)
|
||||
}
|
||||
return obj, st.Size, nil
|
||||
}
|
||||
|
||||
func (s *S3) Stat(ctx context.Context, key string) (Object, error) {
|
||||
st, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return Object{}, ErrNotFound
|
||||
}
|
||||
return Object{}, fmt.Errorf("s3 stat: %w", err)
|
||||
}
|
||||
return Object{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil
|
||||
}
|
||||
|
||||
// Delete идемпотентен: удаление отсутствующего объекта не ошибка.
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil && !isNotFound(err) {
|
||||
return fmt.Errorf("s3 delete: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) List(ctx context.Context, prefix string, fn func(Object) error) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
for o := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if o.Err != nil {
|
||||
return fmt.Errorf("s3 list: %w", o.Err)
|
||||
}
|
||||
if strings.HasSuffix(o.Key, "/") {
|
||||
continue
|
||||
}
|
||||
if err := fn(Object{Key: o.Key, Size: o.Size, LastModified: o.LastModified}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user