Implement lab4 S3 attachments and resilience
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// BlobStore — приватное S3-хранилище байтов вложений (MinIO). Ключи объектов назначает сервер.
|
||||
type BlobStore struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
var errBlobMissing = errors.New("blob missing")
|
||||
|
||||
func newBlobStore(cfg Config) (*BlobStore, error) {
|
||||
u, err := url.Parse(cfg.S3Endpoint)
|
||||
if err != nil || u.Host == "" {
|
||||
return nil, errors.New("invalid S3_ENDPOINT")
|
||||
}
|
||||
// Короткие таймауты: недоступный S3 быстро превращается в 503, а не в зависший запрос.
|
||||
transport := &http.Transport{
|
||||
DialContext: (&net.Dialer{Timeout: 2 * time.Second}).DialContext,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 8 * time.Second,
|
||||
MaxIdleConnsPerHost: 10,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
}
|
||||
client, err := minio.New(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.S3AccessKey, cfg.S3SecretKey, ""),
|
||||
Secure: u.Scheme == "https",
|
||||
Region: cfg.S3Region,
|
||||
Transport: transport,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 client: %w", err)
|
||||
}
|
||||
return &BlobStore{client: client, bucket: cfg.S3Bucket}, nil
|
||||
}
|
||||
|
||||
// ensureBucket создаёт приватный bucket (анонимный доступ в MinIO по умолчанию запрещён).
|
||||
// Операция идемпотентна и ждёт готовности S3 до ~60 с: вызывается из одноразовой команды migrate.
|
||||
func (b *BlobStore) ensureBucket(ctx context.Context) error {
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for {
|
||||
ok, err := b.client.BucketExists(ctx, b.bucket)
|
||||
if err == nil && !ok {
|
||||
err = b.client.MakeBucket(ctx, b.bucket, minio.MakeBucketOptions{Region: ""})
|
||||
if err != nil {
|
||||
if resp := minio.ToErrorResponse(err); resp.Code == "BucketAlreadyOwnedByYou" || resp.Code == "BucketAlreadyExists" {
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) || ctx.Err() != nil {
|
||||
return fmt.Errorf("s3 bucket init: %w", err)
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BlobStore) put(ctx context.Context, key string, data []byte, contentType string) error {
|
||||
_, err := b.client.PutObject(ctx, b.bucket, key, bytes.NewReader(data), int64(len(data)),
|
||||
minio.PutObjectOptions{ContentType: contentType})
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *BlobStore) remove(ctx context.Context, key string) {
|
||||
_ = b.client.RemoveObject(ctx, b.bucket, key, minio.RemoveObjectOptions{})
|
||||
}
|
||||
|
||||
// get возвращает поток байт; ошибки S3 (в том числе недоступность) проявляются здесь, до записи заголовков ответа.
|
||||
func (b *BlobStore) get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
obj, err := b.client.GetObject(ctx, b.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := obj.Stat(); err != nil {
|
||||
_ = obj.Close()
|
||||
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
|
||||
return nil, errBlobMissing
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
Reference in New Issue
Block a user