forked from mtusi2026/mtusi2026lab4
ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)
This commit is contained in:
@@ -0,0 +1,294 @@
|
||||
// Package objectstore is the S3 adapter. PostgreSQL stores attachment
|
||||
// metadata; this package stores and streams the original bytes. No handler
|
||||
// talks to the S3 SDK directly, so error classification and timeouts are in one
|
||||
// place.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNotFound means the object (or a prerequisite such as the bucket) does
|
||||
// not exist. The HTTP layer maps it to 404 for an attachment read.
|
||||
ErrNotFound = errors.New("object not found")
|
||||
// ErrUnavailable means S3 could not answer. The HTTP layer maps it to 503
|
||||
// and never to a fabricated success.
|
||||
ErrUnavailable = errors.New("object store unavailable")
|
||||
)
|
||||
|
||||
// Config is the validated S3 connection. Credentials are never logged.
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Store is a thin, timeout-aware wrapper around minio-go.
|
||||
type Store struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// Open parses S3_ENDPOINT as a scheme://host:port URL and builds a client. The
|
||||
// caller must have validated that every field is non-empty.
|
||||
func Open(cfg Config) (*Store, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(cfg.Endpoint))
|
||||
if err != nil || parsed.Host == "" {
|
||||
return nil, errors.New("S3_ENDPOINT must be an http(s) URL with a host")
|
||||
}
|
||||
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return nil, errors.New("S3_ENDPOINT scheme must be http or https")
|
||||
}
|
||||
if parsed.Path != "" && parsed.Path != "/" {
|
||||
return nil, errors.New("S3_ENDPOINT must not contain a path")
|
||||
}
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = 30 * time.Second
|
||||
}
|
||||
transport := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
||||
MaxIdleConns: 32,
|
||||
MaxIdleConnsPerHost: 16,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: time.Second,
|
||||
}
|
||||
client, err := minio.New(parsed.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: parsed.Scheme == "https",
|
||||
Region: cfg.Region,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
Transport: transport,
|
||||
// The HTTP request is synchronous user work. One bounded retry is
|
||||
// enough; the default exponential retry series would hold an upload
|
||||
// request open for many seconds when S3 is unreachable.
|
||||
MaxRetries: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.New("could not create S3 client")
|
||||
}
|
||||
return &Store{client: client, bucket: cfg.Bucket, timeout: cfg.Timeout}, nil
|
||||
}
|
||||
|
||||
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.timeout)
|
||||
}
|
||||
|
||||
// Put uploads exactly size bytes with the declared content type. The caller
|
||||
// has already validated the image; this function does not buffer the body.
|
||||
func (s *Store) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, body, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
PartSize: 16 << 20,
|
||||
NumThreads: 1,
|
||||
DisableMultipart: size <= 16<<20,
|
||||
})
|
||||
if err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get opens the object stream. The caller closes it. A missing object is
|
||||
// ErrNotFound; an unreachable store is ErrUnavailable.
|
||||
//
|
||||
// The operation context must stay alive while the body is read: cancelling it
|
||||
// when Get returns would abort the HTTP response stream. Close releases both
|
||||
// the SDK object and its timeout.
|
||||
//
|
||||
// Existence and size come from a separate StatObject. Calling Stat on the
|
||||
// lazily opened Object would make minio-go attach an If-Match ETag to the
|
||||
// subsequent GET; SeaweedFS 3.98 rejects that conditional read for large
|
||||
// objects with 412 after the store has been restarted. A plain GET avoids the
|
||||
// false precondition while the HEAD still lets the handler return 404 before
|
||||
// it writes response headers.
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, ObjectInfo{}, classify(err)
|
||||
}
|
||||
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, ObjectInfo{}, classify(err)
|
||||
}
|
||||
return &objectStream{ReadCloser: object, cancel: cancel}, ObjectInfo{
|
||||
Key: key,
|
||||
Size: info.Size,
|
||||
ContentType: info.ContentType,
|
||||
LastModified: info.LastModified,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// objectStream ties the S3 read lifetime to Close. The standard S3 response
|
||||
// is not reusable after Close, and the caller always defers Close.
|
||||
type objectStream struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (s *objectStream) Close() error {
|
||||
err := s.ReadCloser.Close()
|
||||
s.cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
// Stat checks existence without downloading the bytes. It is used by the
|
||||
// metadata endpoint so a missing object is not reported as a ready attachment.
|
||||
func (s *Store) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return ObjectInfo{}, classify(err)
|
||||
}
|
||||
return ObjectInfo{
|
||||
Key: key,
|
||||
Size: info.Size,
|
||||
ContentType: info.ContentType,
|
||||
LastModified: info.LastModified,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Remove deletes one object. S3 delete is idempotent: a missing key is not an
|
||||
// error, which makes a repeated reconciler run safe.
|
||||
func (s *Store) Remove(ctx context.Context, key string) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ObjectInfo is the subset of S3 metadata the reconciler needs.
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
ContentType string
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// List returns every object under prefix. The reconciler uses it once per run;
|
||||
// the HTTP path never lists the bucket.
|
||||
func (s *Store) List(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
result := make([]ObjectInfo, 0, 64)
|
||||
for object := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if object.Err != nil {
|
||||
return nil, classify(object.Err)
|
||||
}
|
||||
result = append(result, ObjectInfo{
|
||||
Key: object.Key,
|
||||
Size: object.Size,
|
||||
ContentType: object.ContentType,
|
||||
LastModified: object.LastModified,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// EnsureBucket creates the bucket if it is absent. It is safe to run
|
||||
// concurrently and repeatedly: an already existing bucket is not an error.
|
||||
// The caller uses administrative credentials; API credentials are not allowed
|
||||
// to create buckets.
|
||||
func (s *Store) EnsureBucket(ctx context.Context) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return false, classify(err)
|
||||
}
|
||||
if exists {
|
||||
return false, nil
|
||||
}
|
||||
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region()}); err != nil {
|
||||
response := minio.ToErrorResponse(err)
|
||||
switch response.Code {
|
||||
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
|
||||
return false, nil
|
||||
}
|
||||
return false, classify(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) region() string {
|
||||
// minio-go keeps the region in an unexported field. Passing an empty
|
||||
// region lets it discover us-east-1 for SeaweedFS; the explicit region is
|
||||
// still set in the client options for signed requests.
|
||||
return ""
|
||||
}
|
||||
|
||||
// Probe writes, stats and removes a tiny object. It proves that the configured
|
||||
// credentials can actually use the private bucket without leaving test data.
|
||||
func (s *Store) Probe(ctx context.Context) error {
|
||||
const key = "_bootstrap/probe"
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
body := strings.NewReader("mtusi-lab4-bucket-probe")
|
||||
if _, err := s.client.PutObject(ctx, s.bucket, key, body, int64(body.Len()), minio.PutObjectOptions{
|
||||
ContentType: "text/plain",
|
||||
PartSize: 5 << 20,
|
||||
}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// classify converts an S3/SDK error into the two dependency classes the HTTP
|
||||
// layer understands. An access-denied or malformed-bucket error stays a plain
|
||||
// error and becomes a generic 500: it is a server configuration defect, not a
|
||||
// user error and not a transient outage.
|
||||
func classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
response := minio.ToErrorResponse(err)
|
||||
switch response.Code {
|
||||
case "NoSuchKey", "NoSuchObject", "NotFound":
|
||||
return ErrNotFound
|
||||
case "NoSuchBucket", "SlowDown", "InternalError", "ServiceUnavailable", "XMinioServerNotInitialized":
|
||||
return fmt.Errorf("%w: %s", ErrUnavailable, response.Code)
|
||||
}
|
||||
if response.StatusCode >= 500 {
|
||||
return fmt.Errorf("%w: HTTP %d", ErrUnavailable, response.StatusCode)
|
||||
}
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user