202 lines
6.6 KiB
Go
202 lines
6.6 KiB
Go
package s3store
|
|
|
|
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"
|
|
"github.com/minio/minio-go/v7/pkg/s3utils"
|
|
|
|
"messenger/internal/attachment"
|
|
"messenger/internal/platform/config"
|
|
)
|
|
|
|
const MaxPageSize = 500
|
|
|
|
const codeBucketAlreadyOwnedByYou = "BucketAlreadyOwnedByYou"
|
|
|
|
type Store struct {
|
|
client *minio.Core
|
|
region string
|
|
bucket string
|
|
}
|
|
|
|
var _ attachment.Blobs = (*Store)(nil)
|
|
|
|
// New validates configuration without contacting S3, so text-only service startup
|
|
// and readiness do not depend on object storage being reachable.
|
|
func New(cfg config.S3) (*Store, error) {
|
|
u, err := url.Parse(cfg.Endpoint)
|
|
if err != nil || u == nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
|
|
return nil, errors.New("s3: endpoint must be an http(s) origin without credentials, query or fragment")
|
|
}
|
|
if strings.TrimSpace(cfg.Region) == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
|
|
return nil, errors.New("s3: region and credentials are required")
|
|
}
|
|
if err := s3utils.CheckValidBucketNameStrict(cfg.Bucket); err != nil {
|
|
return nil, fmt.Errorf("s3: invalid bucket: %w", err)
|
|
}
|
|
transport := &http.Transport{
|
|
Proxy: http.ProxyFromEnvironment,
|
|
DialContext: (&net.Dialer{Timeout: time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
|
TLSHandshakeTimeout: time.Second,
|
|
// The first write can wait for the single master's election and volume
|
|
// creation. The caller's shorter context still takes precedence.
|
|
ResponseHeaderTimeout: 30 * time.Second,
|
|
ExpectContinueTimeout: time.Second,
|
|
IdleConnTimeout: 30 * time.Second,
|
|
MaxIdleConns: 64,
|
|
MaxIdleConnsPerHost: 32,
|
|
MaxConnsPerHost: 64,
|
|
DisableCompression: true,
|
|
}
|
|
client, err := minio.NewCore(u.Host, &minio.Options{
|
|
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
|
Secure: u.Scheme == "https",
|
|
Region: cfg.Region,
|
|
BucketLookup: minio.BucketLookupPath,
|
|
Transport: transport,
|
|
// A consumed upload stream cannot be replayed. Let the caller decide
|
|
// whether to retry a whole operation within its own deadline.
|
|
MaxRetries: 1,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("s3: client: %w", err)
|
|
}
|
|
return &Store{client: client, region: cfg.Region, bucket: cfg.Bucket}, nil
|
|
}
|
|
|
|
// Bootstrap is used only by the admin init command, never by API startup.
|
|
func (s *Store) Bootstrap(ctx context.Context) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region})
|
|
code := minio.ToErrorResponse(err).Code
|
|
if err != nil && code != codeBucketAlreadyOwnedByYou {
|
|
return wrap("create bucket", err)
|
|
}
|
|
return s.WaitReady(ctx)
|
|
}
|
|
|
|
func (s *Store) Put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if size < 0 || r == nil {
|
|
return errors.New("s3: PUT requires a reader and known nonnegative length")
|
|
}
|
|
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, "", "", minio.PutObjectOptions{
|
|
ContentType: mime,
|
|
DisableMultipart: true,
|
|
})
|
|
return wrap("put object", err)
|
|
}
|
|
|
|
func (s *Store) Open(ctx context.Context, key string) (io.ReadCloser, error) {
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
// Core.GetObject performs GET eagerly and returns the streaming body;
|
|
// Client.GetObject is lazy and would defer missing/access errors to Read.
|
|
r, _, _, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
|
if err != nil {
|
|
return nil, wrap("open object", err)
|
|
}
|
|
return r, nil
|
|
}
|
|
|
|
func (s *Store) Stat(ctx context.Context, key string) (attachment.Object, error) {
|
|
if err := ctx.Err(); err != nil {
|
|
return attachment.Object{}, err
|
|
}
|
|
obj, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
|
if err != nil {
|
|
// HEAD has no XML error body. The SDK synthesizes NoSuchKey for any
|
|
// object-path 404, including a missing bucket; confirm the bucket first.
|
|
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
|
|
exists, bucketErr := s.client.BucketExists(ctx, s.bucket)
|
|
if bucketErr != nil {
|
|
return attachment.Object{}, wrap("stat bucket", bucketErr)
|
|
}
|
|
if !exists {
|
|
return attachment.Object{}, errors.New("s3: stat object: bucket does not exist")
|
|
}
|
|
}
|
|
return attachment.Object{}, wrap("stat object", err)
|
|
}
|
|
return attachment.Object{Key: key, Size: obj.Size, Modified: obj.LastModified}, nil
|
|
}
|
|
|
|
func (s *Store) Copy(ctx context.Context, source, dest string) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.client.Client.CopyObject(ctx,
|
|
minio.CopyDestOptions{Bucket: s.bucket, Object: dest},
|
|
minio.CopySrcOptions{Bucket: s.bucket, Object: source},
|
|
)
|
|
return wrap("copy object", err)
|
|
}
|
|
|
|
func (s *Store) Delete(ctx context.Context, key string) error {
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
|
|
// S3 DELETE is idempotent even when the object no longer exists.
|
|
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
|
|
return nil
|
|
}
|
|
return wrap("delete object", err)
|
|
}
|
|
|
|
// List returns at most limit keys in byte-lexicographic order, strictly after
|
|
// after. The synchronous iterator stops before fetching the next page.
|
|
func (s *Store) List(ctx context.Context, prefix, after string, limit int) ([]attachment.Object, error) {
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if limit < 1 || limit > MaxPageSize {
|
|
return nil, fmt.Errorf("s3: list limit must be between 1 and %d", MaxPageSize)
|
|
}
|
|
listCtx, cancel := context.WithCancel(ctx)
|
|
defer cancel()
|
|
objects := make([]attachment.Object, 0, limit)
|
|
for obj := range s.client.ListObjectsIter(listCtx, s.bucket, minio.ListObjectsOptions{
|
|
Prefix: prefix, StartAfter: after, Recursive: true, MaxKeys: limit,
|
|
}) {
|
|
if obj.Err != nil {
|
|
return nil, wrap("list objects", obj.Err)
|
|
}
|
|
objects = append(objects, attachment.Object{Key: obj.Key, Size: obj.Size, Modified: obj.LastModified})
|
|
if len(objects) == limit {
|
|
break
|
|
}
|
|
}
|
|
if err := ctx.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return objects, nil
|
|
}
|
|
|
|
func wrap(op string, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
// Never treat authorization errors, a missing bucket, or an outage as a
|
|
// missing blob: the reconciler would otherwise mark valid files failed.
|
|
if code := minio.ToErrorResponse(err).Code; code == "NoSuchKey" || code == "NoSuchObject" {
|
|
return fmt.Errorf("s3: %s: %w", op, attachment.ErrObjectMissing)
|
|
}
|
|
return fmt.Errorf("s3: %s: %w", op, err)
|
|
}
|